Search in sources :

Example 1 with SerialParameters

use of com.ghgande.j2mod.modbus.util.SerialParameters in project openems by OpenEMS.

the class ModbusRtu method getModbusConnection.

private SerialConnection getModbusConnection() throws OpenemsModbusException {
    if (!connection.isPresent()) {
        if (!baudrate.valueOptional().isPresent() || !databits.valueOptional().isPresent() || !parity.valueOptional().isPresent() || !serialinterface.valueOptional().isPresent() || !stopbits.valueOptional().isPresent()) {
            this.configurationFault.setValue(true);
            throw new OpenemsModbusException(this.id() + ": Modbus-RTU is not configured completely");
        }
        SerialParameters params = new SerialParameters();
        params.setPortName(serialinterface.valueOptional().get());
        params.setBaudRate(baudrate.valueOptional().get());
        params.setDatabits(databits.valueOptional().get());
        params.setParity(parity.valueOptional().get());
        params.setStopbits(stopbits.valueOptional().get());
        params.setEncoding(Modbus.SERIAL_ENCODING_RTU);
        params.setEcho(false);
        connection = Optional.of(new SerialConnection(params));
        this.configurationFault.setValue(false);
    }
    if (!connection.get().isOpen()) {
        try {
            SerialConnection serialCon = connection.get();
            serialCon.open();
            serialCon.getModbusTransport().setTimeout(1000);
            this.connectionFault.setValue(false);
        } catch (Exception e) {
            this.connectionFault.setValue(true);
            throw new OpenemsModbusException(this.id() + ": Unable to open Modbus-RTU connection to [" + serialinterface.valueOptional().orElse("UNDEFINED") + "]: " + e.getMessage());
        }
    }
    return connection.get();
}
Also used : OpenemsModbusException(io.openems.api.exception.OpenemsModbusException) SerialConnection(com.ghgande.j2mod.modbus.net.SerialConnection) OpenemsModbusException(io.openems.api.exception.OpenemsModbusException) ConfigException(io.openems.api.exception.ConfigException) SerialParameters(com.ghgande.j2mod.modbus.util.SerialParameters)

Aggregations

SerialConnection (com.ghgande.j2mod.modbus.net.SerialConnection)1 SerialParameters (com.ghgande.j2mod.modbus.util.SerialParameters)1 ConfigException (io.openems.api.exception.ConfigException)1 OpenemsModbusException (io.openems.api.exception.OpenemsModbusException)1