Search in sources :

Example 1 with SerialParameters

use of net.wimpi.modbus.util.SerialParameters in project openhab1-addons by openhab.

the class ModbusSlaveEndpointTestCase method testEqualsDifferentSerial.

@Test
public void testEqualsDifferentSerial() {
    ModbusSerialSlaveEndpoint e1 = new ModbusSerialSlaveEndpoint(new SerialParameters("port1", 9600, SerialPort.FLOWCONTROL_NONE, SerialPort.FLOWCONTROL_NONE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE, Modbus.DEFAULT_SERIAL_ENCODING, true, 500));
    ModbusSerialSlaveEndpoint e2 = new ModbusSerialSlaveEndpoint(new SerialParameters("port2", 9600, SerialPort.FLOWCONTROL_NONE, SerialPort.FLOWCONTROL_NONE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE, Modbus.DEFAULT_SERIAL_ENCODING, true, 500));
    Assert.assertNotEquals(e1, e2);
    Assert.assertNotEquals(e1.hashCode(), e2.hashCode());
}
Also used : ModbusSerialSlaveEndpoint(org.openhab.binding.modbus.internal.pooling.ModbusSerialSlaveEndpoint) SerialParameters(net.wimpi.modbus.util.SerialParameters) Test(org.junit.Test)

Example 2 with SerialParameters

use of net.wimpi.modbus.util.SerialParameters in project openhab1-addons by openhab.

the class ModbusSlaveEndpointTestCase method testEqualsDifferentProtocol2.

@Test
public void testEqualsDifferentProtocol2() {
    ModbusTCPSlaveEndpoint e1 = new ModbusTCPSlaveEndpoint("127.0.0.1", 500);
    ModbusSerialSlaveEndpoint e2 = new ModbusSerialSlaveEndpoint(new SerialParameters());
    Assert.assertNotEquals(e1, e2);
    Assert.assertNotEquals(e1.hashCode(), e2.hashCode());
}
Also used : ModbusSerialSlaveEndpoint(org.openhab.binding.modbus.internal.pooling.ModbusSerialSlaveEndpoint) ModbusTCPSlaveEndpoint(org.openhab.binding.modbus.internal.pooling.ModbusTCPSlaveEndpoint) SerialParameters(net.wimpi.modbus.util.SerialParameters) Test(org.junit.Test)

Example 3 with SerialParameters

use of net.wimpi.modbus.util.SerialParameters in project openhab1-addons by openhab.

the class ModbusSlaveEndpointTestCase method testEqualsSameSerial3.

/**
     * even though different echo parameter & baud rate, the endpoints are considered the same due to same port
     */
@Test
public void testEqualsSameSerial3() {
    ModbusSerialSlaveEndpoint e1 = new ModbusSerialSlaveEndpoint(new SerialParameters("port1", 9600, SerialPort.FLOWCONTROL_NONE, SerialPort.FLOWCONTROL_NONE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE, Modbus.DEFAULT_SERIAL_ENCODING, true, 500));
    ModbusSerialSlaveEndpoint e2 = new ModbusSerialSlaveEndpoint(new SerialParameters("port1", 9600, SerialPort.FLOWCONTROL_NONE, SerialPort.FLOWCONTROL_NONE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE, Modbus.DEFAULT_SERIAL_ENCODING, false, 500));
    Assert.assertEquals(e1, e2);
    Assert.assertEquals(e1.hashCode(), e2.hashCode());
}
Also used : ModbusSerialSlaveEndpoint(org.openhab.binding.modbus.internal.pooling.ModbusSerialSlaveEndpoint) SerialParameters(net.wimpi.modbus.util.SerialParameters) Test(org.junit.Test)

Example 4 with SerialParameters

use of net.wimpi.modbus.util.SerialParameters in project openhab1-addons by openhab.

the class SerialFacadeTest method main.

public static void main(String[] args) {
    int inChar = -1;
    int result = 0;
    boolean finished = false;
    int slaveId = 88;
    String portname = null;
    ModbusSerialMaster msm = null;
    try {
        // 1. Setup the parameters
        if (args.length < 2) {
            printUsage();
            System.exit(1);
        } else {
            try {
                portname = args[0];
                slaveId = Integer.parseInt(args[1]);
            } catch (Exception ex) {
                ex.printStackTrace();
                printUsage();
                System.exit(1);
            }
        }
        System.out.println(" sending test messages to slave: " + slaveId);
        System.out.println("net.wimpi.modbus.debug set to: " + System.getProperty("net.wimpi.modbus.debug"));
        System.out.println("Hit enter to start and <s enter> to terminate the test.");
        inChar = System.in.read();
        if ((inChar == 's') || (inChar == 'S')) {
            System.out.println("Exiting");
            System.exit(0);
        }
        // 2. Setup serial parameters
        SerialParameters params = new SerialParameters();
        params.setPortName(portname);
        params.setBaudRate(38400);
        params.setDatabits(8);
        params.setParity("None");
        params.setStopbits(1);
        params.setEncoding("rtu");
        params.setEcho(true);
        if (Modbus.debug) {
            System.out.println("Encoding [" + params.getEncoding() + "]");
        }
        // 3. Create the master facade
        msm = new ModbusSerialMaster(params);
        msm.connect();
        do {
            if (msm.writeCoil(slaveId, 4, true) == true) {
                System.out.println("Set output 5 to true");
            } else {
                System.err.println("Error setting slave " + slaveId + " output 5");
            }
            BitVector coils = msm.readCoils(slaveId, 0, 8);
            if (coils != null) {
                System.out.print("Coils:");
                for (int i = 0; i < coils.size(); i++) {
                    System.out.print(" " + i + ": " + coils.getBit(i));
                }
                System.out.println();
                try {
                    msm.writeMultipleCoils(slaveId, 0, coils);
                } catch (ModbusException ex) {
                    System.out.println("Error writing coils: " + result);
                }
            } else {
                System.out.println("Outputs: null");
                msm.disconnect();
                System.exit(-1);
            }
            BitVector digInp = msm.readInputDiscretes(slaveId, 0, 8);
            if (digInp != null) {
                System.out.print("Digital Inputs:");
                for (int i = 0; i < digInp.size(); i++) {
                    System.out.print(" " + i + ": " + digInp.getBit(i));
                }
                System.out.println();
                System.out.println("Inputs: " + ModbusUtil.toHex(digInp.getBytes()));
            } else {
                System.out.println("Inputs: null");
                msm.disconnect();
                System.exit(-1);
            }
            InputRegister[] ai = null;
            for (int i = 1000; i < 1010; i++) {
                ai = msm.readInputRegisters(slaveId, i, 1);
                if (ai != null) {
                    System.out.print("Tag " + i + ": ");
                    for (int n = 0; n < ai.length; n++) {
                        System.out.print(" " + ai[n].getValue());
                    }
                    System.out.println();
                } else {
                    System.out.println("Tag: " + i + " null");
                    msm.disconnect();
                    System.exit(-1);
                }
            }
            Register[] regs = null;
            for (int i = 1000; i < 1005; i++) {
                regs = msm.readMultipleRegisters(slaveId, i, 1);
                if (regs != null) {
                    System.out.print("RWRegisters " + i + " length: " + regs.length);
                    for (int n = 0; n < regs.length; n++) {
                        System.out.print(" " + regs[n].getValue());
                    }
                    System.out.println();
                } else {
                    System.out.println("RWRegisters " + i + ": null");
                    msm.disconnect();
                    System.exit(-1);
                }
            }
            regs = msm.readMultipleRegisters(slaveId, 0, 10);
            System.out.println("Registers: ");
            if (regs != null) {
                System.out.print("regs :");
                for (int n = 0; n < regs.length; n++) {
                    System.out.print("  " + n + "= " + regs[n]);
                }
                System.out.println();
            } else {
                System.out.println("Registers: null");
                msm.disconnect();
                System.exit(-1);
            }
            while (System.in.available() > 0) {
                inChar = System.in.read();
                if ((inChar == 's') || (inChar == 'S')) {
                    finished = true;
                }
            }
        } while (!finished);
    } catch (Exception e) {
        System.err.println("SerialFacadeTest driver: " + e);
        e.printStackTrace();
    }
    msm.disconnect();
}
Also used : BitVector(net.wimpi.modbus.util.BitVector) InputRegister(net.wimpi.modbus.procimg.InputRegister) InputRegister(net.wimpi.modbus.procimg.InputRegister) Register(net.wimpi.modbus.procimg.Register) ModbusSerialMaster(net.wimpi.modbus.facade.ModbusSerialMaster) ModbusException(net.wimpi.modbus.ModbusException) SerialParameters(net.wimpi.modbus.util.SerialParameters) ModbusException(net.wimpi.modbus.ModbusException)

Example 5 with SerialParameters

use of net.wimpi.modbus.util.SerialParameters in project openhab1-addons by openhab.

the class ModbusBinding method updated.

@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    try {
        // remove all known items if configuration changed
        clear();
        reconstructConnectionPool();
        if (config == null) {
            logger.debug("Got null config!");
            return;
        }
        Enumeration<String> keys = config.keys();
        Map<String, EndpointPoolConfiguration> slavePoolConfigs = new HashMap<String, EndpointPoolConfiguration>();
        Map<ModbusSlaveEndpoint, EndpointPoolConfiguration> endpointPoolConfigs = new HashMap<ModbusSlaveEndpoint, EndpointPoolConfiguration>();
        while (keys.hasMoreElements()) {
            final String key = keys.nextElement();
            final String value = (String) config.get(key);
            try {
                // don't want to process here ...
                if ("service.pid".equals(key)) {
                    continue;
                }
                Matcher matcher = EXTRACT_MODBUS_CONFIG_PATTERN.matcher(key);
                if (!matcher.matches()) {
                    if ("poll".equals(key)) {
                        if (StringUtils.isNotBlank((String) config.get(key))) {
                            pollInterval = Integer.valueOf((String) config.get(key));
                        }
                    } else if ("writemultipleregisters".equals(key)) {
                        // XXX: ugly to touch base class but kept here for backwards compat
                        // FIXME: should this be deprecated as introduced as slave specific parameter?
                        ModbusSlave.setWriteMultipleRegisters(Boolean.valueOf(config.get(key).toString()));
                    } else {
                        logger.debug("given modbus-slave-config-key '{}' does not follow the expected pattern or 'serial.<slaveId>.<{}>'", key, VALID_CONFIG_KEYS);
                    }
                    continue;
                }
                matcher.reset();
                matcher.find();
                String slave = matcher.group(2);
                ModbusSlave modbusSlave = modbusSlaves.get(slave);
                EndpointPoolConfiguration endpointPoolConfig = slavePoolConfigs.get(slave);
                if (modbusSlave == null) {
                    if (matcher.group(1).equals(TCP_PREFIX)) {
                        modbusSlave = new ModbusTcpSlave(slave, connectionPool);
                    } else if (matcher.group(1).equals(UDP_PREFIX)) {
                        modbusSlave = new ModbusUdpSlave(slave, connectionPool);
                    } else if (matcher.group(1).equals(SERIAL_PREFIX)) {
                        modbusSlave = new ModbusSerialSlave(slave, connectionPool);
                    } else {
                        throw new ConfigurationException(slave, "the given slave type '" + slave + "' is unknown");
                    }
                    endpointPoolConfig = new EndpointPoolConfiguration();
                    // Do not give up if the connection attempt fails on the first time...
                    endpointPoolConfig.setConnectMaxTries(Modbus.DEFAULT_RETRIES);
                    logger.debug("modbusSlave '{}' instanciated", slave);
                    modbusSlaves.put(slave, modbusSlave);
                }
                String configKey = matcher.group(3);
                if ("connection".equals(configKey)) {
                    String[] chunks = value.split(":");
                    Iterator<String> settingIterator = stringArrayIterator(chunks);
                    if (modbusSlave instanceof ModbusIPSlave) {
                        ((ModbusIPSlave) modbusSlave).setHost(settingIterator.next());
                        //
                        // Defaults for endpoint and slave
                        //
                        modbusSlave.setRetryDelayMillis(DEFAULT_TCP_INTER_TRANSACTION_DELAY_MILLIS);
                        endpointPoolConfig.setPassivateBorrowMinMillis(DEFAULT_TCP_INTER_TRANSACTION_DELAY_MILLIS);
                        //
                        try {
                            ((ModbusIPSlave) modbusSlave).setPort(Integer.valueOf(settingIterator.next()));
                            long passivateBorrowMinMillis = Long.parseLong(settingIterator.next());
                            modbusSlave.setRetryDelayMillis(passivateBorrowMinMillis);
                            endpointPoolConfig.setPassivateBorrowMinMillis(passivateBorrowMinMillis);
                            endpointPoolConfig.setReconnectAfterMillis(Integer.parseInt(settingIterator.next()));
                            // time to wait before trying connect closed connection. Note that
                            // ModbusSlaveConnectionFactoryImpl makes sure that max{passivateBorrowMinMillis, this
                            // parameter} is waited between connection attempts
                            endpointPoolConfig.setInterConnectDelayMillis(Long.parseLong(settingIterator.next()));
                            endpointPoolConfig.setConnectMaxTries(Integer.parseInt(settingIterator.next()));
                            endpointPoolConfig.setConnectTimeoutMillis(Integer.parseInt(settingIterator.next()));
                        } catch (NoSuchElementException e) {
                        // Some of the optional parameters are missing -- it's ok!
                        }
                        if (settingIterator.hasNext()) {
                            String errMsg = String.format("%s Has too many colon (:) separated connection settings for a tcp/udp modbus slave. " + "Expecting at most 6 parameters: hostname (mandatory) and " + "optionally (in this order) port number, " + "interTransactionDelayMillis, reconnectAfterMillis," + "interConnectDelayMillis, connectMaxTries, connectTimeout.", key);
                            throw new ConfigurationException(key, errMsg);
                        }
                    } else if (modbusSlave instanceof ModbusSerialSlave) {
                        SerialParameters serialParameters = new SerialParameters();
                        serialParameters.setPortName(settingIterator.next());
                        //
                        // Defaults for endpoint and slave
                        //
                        // never "disconnect" (close/open serial
                        endpointPoolConfig.setReconnectAfterMillis(-1);
                        // port)
                        // serial connection between borrows
                        modbusSlave.setRetryDelayMillis(DEFAULT_SERIAL_INTER_TRANSACTION_DELAY_MILLIS);
                        endpointPoolConfig.setPassivateBorrowMinMillis(DEFAULT_SERIAL_INTER_TRANSACTION_DELAY_MILLIS);
                        //
                        try {
                            serialParameters.setBaudRate(settingIterator.next());
                            serialParameters.setDatabits(settingIterator.next());
                            serialParameters.setParity(settingIterator.next());
                            serialParameters.setStopbits(settingIterator.next());
                            serialParameters.setEncoding(settingIterator.next());
                            // time to wait between connection passive+borrow, i.e. time to wait between
                            // transactions
                            long passivateBorrowMinMillis = Long.parseLong(settingIterator.next());
                            modbusSlave.setRetryDelayMillis(passivateBorrowMinMillis);
                            endpointPoolConfig.setPassivateBorrowMinMillis(passivateBorrowMinMillis);
                            serialParameters.setReceiveTimeoutMillis(settingIterator.next());
                            serialParameters.setFlowControlIn(settingIterator.next());
                            serialParameters.setFlowControlOut(settingIterator.next());
                        } catch (NoSuchElementException e) {
                        // Some of the optional parameters are missing -- it's ok!
                        }
                        if (settingIterator.hasNext()) {
                            String errMsg = String.format("%s Has too many colon (:) separated connection settings for a serial modbus slave. " + "Expecting at most 9 parameters (got %d): devicePort (mandatory), " + "and 0 or more optional parameters (in this order): " + "baudRate, dataBits, parity, stopBits, " + "encoding, interTransactionWaitMillis, " + "receiveTimeoutMillis, flowControlIn, flowControlOut", key, chunks.length);
                            throw new ConfigurationException(key, errMsg);
                        }
                        ((ModbusSerialSlave) modbusSlave).setSerialParameters(serialParameters);
                    }
                } else if ("start".equals(configKey)) {
                    modbusSlave.setStart(Integer.valueOf(value));
                } else if ("length".equals(configKey)) {
                    modbusSlave.setLength(Integer.valueOf(value));
                } else if ("id".equals(configKey)) {
                    modbusSlave.setId(Integer.valueOf(value));
                } else if ("type".equals(configKey)) {
                    if (ArrayUtils.contains(ModbusBindingProvider.SLAVE_DATA_TYPES, value)) {
                        modbusSlave.setType(value);
                    } else {
                        throw new ConfigurationException(configKey, "the given slave type '" + value + "' is invalid");
                    }
                } else if ("valuetype".equals(configKey)) {
                    if (ArrayUtils.contains(ModbusBindingProvider.VALUE_TYPES, value)) {
                        modbusSlave.setValueType(value);
                    } else {
                        throw new ConfigurationException(configKey, "the given value type '" + value + "' is invalid");
                    }
                } else if ("rawdatamultiplier".equals(configKey)) {
                    modbusSlave.setRawDataMultiplier(Double.valueOf(value.toString()));
                } else if ("updateunchangeditems".equals(configKey)) {
                    modbusSlave.setUpdateUnchangedItems(Boolean.valueOf(value.toString()));
                } else if ("postundefinedonreaderror".equals(configKey)) {
                    modbusSlave.setPostUndefinedOnReadError(Boolean.valueOf(value.toString()));
                } else {
                    throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown");
                }
                modbusSlaves.put(slave, modbusSlave);
                slavePoolConfigs.put(slave, endpointPoolConfig);
            } catch (Exception e) {
                String errMsg = String.format("Exception when parsing configuration parameter %s = %s  --  %s %s", key, value, e.getClass().getName(), e.getMessage());
                logger.error(errMsg);
                throw new ConfigurationException(key, errMsg);
            }
        }
        // Finally, go through each slave definition, and combine the slave pool configurations
        for (Entry<String, EndpointPoolConfiguration> slaveEntry : slavePoolConfigs.entrySet()) {
            String slave = slaveEntry.getKey();
            EndpointPoolConfiguration poolConfiguration = slaveEntry.getValue();
            ModbusSlaveEndpoint endpoint = modbusSlaves.get(slave).getEndpoint();
            EndpointPoolConfiguration existingPoolConfiguration = endpointPoolConfigs.get(endpoint);
            // Do we have two slaves with same endpoint, but different pool configuration parameters? Warn if we do.
            if (existingPoolConfiguration != null && !existingPoolConfiguration.equals(poolConfiguration)) {
                logger.warn("Slave {} (endpoint {}) has different retry/connection delay " + "(EndpointPoolConfiguration) etc. settings. Replacing {} with {}", slave, endpoint, existingPoolConfiguration, poolConfiguration);
            }
            endpointPoolConfigs.put(endpoint, poolConfiguration);
        }
        connectionFactory.applyEndpointPoolConfigs(endpointPoolConfigs);
        logger.debug("Parsed the following slave->endpoint configurations: {}. If the endpoint is same, " + "connections are shared between the instances.", slavePoolConfigs);
        logger.debug("Parsed the following pool configurations: {}", endpointPoolConfigs);
        logger.debug("config looked good");
        setProperlyConfigured(true);
    } catch (ConfigurationException ce) {
        setProperlyConfigured(false);
        throw ce;
    }
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ModbusSlaveEndpoint(org.openhab.binding.modbus.internal.pooling.ModbusSlaveEndpoint) Matcher(java.util.regex.Matcher) ConfigurationException(org.osgi.service.cm.ConfigurationException) NoSuchElementException(java.util.NoSuchElementException) SerialParameters(net.wimpi.modbus.util.SerialParameters) EndpointPoolConfiguration(org.openhab.binding.modbus.internal.pooling.EndpointPoolConfiguration) ConfigurationException(org.osgi.service.cm.ConfigurationException) NoSuchElementException(java.util.NoSuchElementException)

Aggregations

SerialParameters (net.wimpi.modbus.util.SerialParameters)10 Test (org.junit.Test)5 ModbusSerialSlaveEndpoint (org.openhab.binding.modbus.internal.pooling.ModbusSerialSlaveEndpoint)5 ModbusSerialTransaction (net.wimpi.modbus.io.ModbusSerialTransaction)2 SerialConnection (net.wimpi.modbus.net.SerialConnection)2 BitVector (net.wimpi.modbus.util.BitVector)2 HashMap (java.util.HashMap)1 NoSuchElementException (java.util.NoSuchElementException)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 Matcher (java.util.regex.Matcher)1 ModbusException (net.wimpi.modbus.ModbusException)1 ModbusSerialMaster (net.wimpi.modbus.facade.ModbusSerialMaster)1 ReadInputDiscretesRequest (net.wimpi.modbus.msg.ReadInputDiscretesRequest)1 ReadInputDiscretesResponse (net.wimpi.modbus.msg.ReadInputDiscretesResponse)1 ReadInputRegistersRequest (net.wimpi.modbus.msg.ReadInputRegistersRequest)1 ReadInputRegistersResponse (net.wimpi.modbus.msg.ReadInputRegistersResponse)1 ModbusSerialListener (net.wimpi.modbus.net.ModbusSerialListener)1 InputRegister (net.wimpi.modbus.procimg.InputRegister)1 Register (net.wimpi.modbus.procimg.Register)1 SimpleDigitalIn (net.wimpi.modbus.procimg.SimpleDigitalIn)1