com.serotonin.modbus4j.exception.ErrorResponseException Java Examples

The following examples show how to use com.serotonin.modbus4j.exception.ErrorResponseException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CustomDriverServiceImpl.java    From iot-dc3 with Apache License 2.0 6 votes vote down vote up
/**
 * 获取 Value
 *
 * @param modbusMaster
 * @param pointInfo
 * @return
 * @throws ModbusTransportException
 * @throws ErrorResponseException
 * @throws ModbusInitException
 */
public String readValue(ModbusMaster modbusMaster, Map<String, AttributeInfo> pointInfo, String type) throws ModbusTransportException, ErrorResponseException, ModbusInitException {
    int slaveId = attribute(pointInfo, "slaveId");
    int functionCode = attribute(pointInfo, "functionCode");
    int offset = attribute(pointInfo, "offset");
    switch (functionCode) {
        case 1:
            BaseLocator<Boolean> coilLocator = BaseLocator.coilStatus(slaveId, offset);
            Boolean coilValue = modbusMaster.getValue(coilLocator);
            return String.valueOf(coilValue);
        case 2:
            BaseLocator<Boolean> inputLocator = BaseLocator.inputStatus(slaveId, offset);
            Boolean inputStatusValue = modbusMaster.getValue(inputLocator);
            return String.valueOf(inputStatusValue);
        case 3:
            BaseLocator<Number> holdingLocator = BaseLocator.holdingRegister(slaveId, offset, getValueType(type));
            Number holdingValue = modbusMaster.getValue(holdingLocator);
            return String.valueOf(holdingValue);
        case 4:
            BaseLocator<Number> inputRegister = BaseLocator.inputRegister(slaveId, offset, getValueType(type));
            Number inputRegisterValue = modbusMaster.getValue(inputRegister);
            return String.valueOf(inputRegisterValue);
        default:
            return "0";
    }
}
 
Example #2
Source File: CustomDriverServiceImpl.java    From iot-dc3 with Apache License 2.0 6 votes vote down vote up
/**
 * 写 Value
 *
 * @param modbusMaster
 * @param pointInfo
 * @param type
 * @param value
 * @return
 * @throws ModbusTransportException
 * @throws ErrorResponseException
 */
public boolean writeValue(ModbusMaster modbusMaster, Map<String, AttributeInfo> pointInfo, String type, String value) throws ModbusTransportException, ErrorResponseException {
    int slaveId = attribute(pointInfo, "slaveId");
    int functionCode = attribute(pointInfo, "functionCode");
    int offset = attribute(pointInfo, "offset");
    switch (functionCode) {
        case 1:
            boolean coilValue = value(type, value);
            WriteCoilRequest coilRequest = new WriteCoilRequest(slaveId, offset, coilValue);
            WriteCoilResponse coilResponse = (WriteCoilResponse) modbusMaster.send(coilRequest);
            if (coilResponse.isException()) {
                return false;
            }
            return true;
        case 3:
            BaseLocator<Number> locator = BaseLocator.holdingRegister(slaveId, offset, getValueType(type));
            modbusMaster.setValue(locator, value(type, value));
            return true;
        default:
            return false;
    }
}
 
Example #3
Source File: ModbusMaster.java    From modbus4j with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Useful for sending a number of polling commands at once, or at least in as optimal a batch as possible.
 *
 * @param batch a {@link com.serotonin.modbus4j.BatchRead} object.
 * @return a {@link com.serotonin.modbus4j.BatchResults} object.
 * @throws com.serotonin.modbus4j.exception.ModbusTransportException if any.
 * @throws com.serotonin.modbus4j.exception.ErrorResponseException if any.
 * @param <K> type of result
 */
public <K> BatchResults<K> send(BatchRead<K> batch) throws ModbusTransportException, ErrorResponseException {
    if (!initialized)
        throw new ModbusTransportException("not initialized");

    BatchResults<K> results = new BatchResults<>();
    List<ReadFunctionGroup<K>> functionGroups = batch.getReadFunctionGroups(this);

    // Execute each read function and process the results.
    for (ReadFunctionGroup<K> functionGroup : functionGroups) {
        sendFunctionGroup(functionGroup, results, batch.isErrorsInResults(), batch.isExceptionsInResults());
        if (batch.isCancel())
            break;
    }

    return results;
}
 
Example #4
Source File: ModbusMaster.java    From modbus4j with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sets the given value in the modbus network according to the given locator information. Various data types are
 * allowed to be set including including multi-word types. The determination of the correct write message to send is
 * handled automatically.
 *
 * @param locator
 *            the information required to locate the value in the modbus network.
 * @param value an object representing the value to be set. This will be one of Boolean, Short, Integer, Long, BigInteger,
 *        Float, or Double. See the DataType enumeration for details on which type to expect.
 * @throws com.serotonin.modbus4j.exception.ModbusTransportException
 *             if there was an IO error or other technical failure while sending the message
 * @throws com.serotonin.modbus4j.exception.ErrorResponseException
 *             if the response returned from the slave was an exception.
 * @param <T> type of locator
 */
public <T> void setValue(BaseLocator<T> locator, Object value) throws ModbusTransportException,
        ErrorResponseException {
    int slaveId = locator.getSlaveId();
    int registerRange = locator.getRange();
    int writeOffset = locator.getOffset();

    // Determine the request type that we will use
    if (registerRange == RegisterRange.INPUT_STATUS || registerRange == RegisterRange.INPUT_REGISTER)
        throw new RuntimeException("Cannot write to input status or input register ranges");

    if (registerRange == RegisterRange.COIL_STATUS) {
        if (!(value instanceof Boolean))
            throw new InvalidDataConversionException("Only boolean values can be written to coils");
        if (multipleWritesOnly)
            setValue(new WriteCoilsRequest(slaveId, writeOffset, new boolean[] { ((Boolean) value).booleanValue() }));
        else
            setValue(new WriteCoilRequest(slaveId, writeOffset, ((Boolean) value).booleanValue()));
    }
    else {
        // Writing to holding registers.
        if (locator.getDataType() == DataType.BINARY) {
            if (!(value instanceof Boolean))
                throw new InvalidDataConversionException("Only boolean values can be written to coils");
            setHoldingRegisterBit(slaveId, writeOffset, ((BinaryLocator) locator).getBit(),
                    ((Boolean) value).booleanValue());
        }
        else {
            // Writing some kind of value to a holding register.
            @SuppressWarnings("unchecked")
            short[] data = locator.valueToShorts((T) value);
            if (data.length == 1 && !multipleWritesOnly)
                setValue(new WriteRegisterRequest(slaveId, writeOffset, data[0]));
            else
                setValue(new WriteRegistersRequest(slaveId, writeOffset, data));
        }
    }

}
 
Example #5
Source File: ModbusMaster.java    From modbus4j with GNU General Public License v3.0 5 votes vote down vote up
private void setValue(ModbusRequest request) throws ModbusTransportException, ErrorResponseException {
    ModbusResponse response = send(request);
    if (response == null)
        // This should only happen if the request was a broadcast
        return;
    if (response.isException())
        throw new ErrorResponseException(request, response);
}
 
Example #6
Source File: ModbusMaster.java    From modbus4j with GNU General Public License v3.0 5 votes vote down vote up
private void setHoldingRegisterBit(int slaveId, int writeOffset, int bit, boolean value)
        throws ModbusTransportException, ErrorResponseException {
    // Writing a bit in a holding register field. There are two ways to do this. The easy way is to
    // use a write mask request, but it is not always supported. The hard way is to read the value, change
    // the appropriate bit, and then write it back again (so as not to overwrite the other bits in the
    // value). However, since the hard way is not atomic, it is not fail-safe either, but it should be
    // at least possible.
    SlaveProfile sp = getSlaveProfile(slaveId);
    if (sp.getWriteMaskRegister()) {
        // Give the write mask a try.
        WriteMaskRegisterRequest request = new WriteMaskRegisterRequest(slaveId, writeOffset);
        request.setBit(bit, value);
        ModbusResponse response = send(request);
        if (response == null)
            // This should only happen if the request was a broadcast
            return;
        if (!response.isException())
            // Hey, cool, it worked.
            return;

        if (response.getExceptionCode() == ExceptionCode.ILLEGAL_FUNCTION)
            // The function is probably not supported. Fail-over to the two step.
            sp.setWriteMaskRegister(false);
        else
            throw new ErrorResponseException(request, response);
    }

    // Do it the hard way. Get the register's current value.
    int regValue = (Integer) getValue(new NumericLocator(slaveId, RegisterRange.HOLDING_REGISTER, writeOffset,
            DataType.TWO_BYTE_INT_UNSIGNED));

    // Modify the value according to the given bit and value.
    if (value)
        regValue = regValue | 1 << bit;
    else
        regValue = regValue & ~(1 << bit);

    // Write the new register value.
    setValue(new WriteRegisterRequest(slaveId, writeOffset, regValue));
}
 
Example #7
Source File: ModbusMaster.java    From modbus4j with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Returns a value from the modbus network according to the given locator information. Various data types are
 * allowed to be requested including multi-word types. The determination of the correct request message to send is
 * handled automatically.
 *
 * @param locator
 *            the information required to locate the value in the modbus network.
 * @return an object representing the value found. This will be one of Boolean, Short, Integer, Long, BigInteger,
 *         Float, or Double. See the DataType enumeration for details on which type to expect.
 * @throws com.serotonin.modbus4j.exception.ModbusTransportException
 *             if there was an IO error or other technical failure while sending the message
 * @throws com.serotonin.modbus4j.exception.ErrorResponseException
 *             if the response returned from the slave was an exception.
 * @param <T> a T object.
 */
@SuppressWarnings("unchecked")
public <T> T getValue(BaseLocator<T> locator) throws ModbusTransportException, ErrorResponseException {
    BatchRead<String> batch = new BatchRead<>();
    batch.addLocator("", locator);
    BatchResults<String> result = send(batch);
    return (T) result.getValue("");
}
 
Example #8
Source File: MasterTest2.java    From modbus4j with GNU General Public License v3.0 3 votes vote down vote up
public static void main(String[] args) throws Exception {
    IpParameters ipParameters = new IpParameters();
    ipParameters.setHost("localhost");
    // ipParameters.setHost("99.247.60.96");
    // ipParameters.setHost("193.109.41.121");
    //ipParameters.setHost("141.211.194.29");
    ipParameters.setPort(502);

    ModbusFactory modbusFactory = new ModbusFactory();
    // ModbusMaster master = modbusFactory.createTcpMaster(ipParameters, true);
    ModbusMaster master = modbusFactory.createTcpMaster(ipParameters, false);
    master.setTimeout(4000);
    master.setRetries(1);

    BatchRead<Integer> batch = new BatchRead<Integer>();
    //        batch.addLocator(0, new ModbusLocator(1, RegisterRange.COIL_STATUS, 2048, DataType.BINARY));
    //        batch.addLocator(1, new ModbusLocator(1, RegisterRange.COIL_STATUS, 2049, DataType.BINARY));
    //        batch.addLocator(2, new ModbusLocator(1, RegisterRange.COIL_STATUS, 2050, DataType.BINARY));
    //        batch.addLocator(3, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3584, DataType.BINARY));
    //        batch.addLocator(4, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3585, DataType.BINARY));
    //        batch.addLocator(5, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3648, DataType.BINARY));
    //        batch.addLocator(6, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3649, DataType.BINARY));
    //        batch.addLocator(7, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3650, DataType.BINARY));
    //        batch.addLocator(8, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3651, DataType.BINARY));
    //        batch.addLocator(9, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3652, DataType.BINARY));
    //        batch.addLocator(10, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3653, DataType.BINARY));
    //        batch.addLocator(11, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3654, DataType.BINARY));
    //        batch.addLocator(12, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3661, DataType.BINARY));
    //        batch.addLocator(13, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3662, DataType.BINARY));
    //        batch.addLocator(15, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3665, DataType.BINARY));
    //        batch.addLocator(16, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3668, DataType.BINARY));
    //        batch.addLocator(18, new ModbusLocator(1, RegisterRange.COIL_STATUS, 3969, DataType.BINARY));

    batch.addLocator(0, BaseLocator.holdingRegister(5, 80, DataType.TWO_BYTE_INT_SIGNED));
    batch.addLocator(1, BaseLocator.holdingRegister(5, 202, DataType.EIGHT_BYTE_INT_SIGNED));

    try {
        master.init();

        while (true) {
            batch.setContiguousRequests(false);
            BatchResults<Integer> results = master.send(batch);
            System.out.println(results.getValue(0));
            System.out.println(results.getValue(1));

            Thread.sleep(2000);
        }
    }
    catch (ErrorResponseException e) {
        System.out.println(e.getErrorResponse().getExceptionMessage());
    }
    finally {
        master.destroy();
    }
}