Search in sources :

Example 46 with Command

use of org.openhab.core.types.Command in project openhab1-addons by openhab.

the class SonosGenericBindingProvider method getCommands.

@Override
public List<Command> getCommands(String anItem, String sonosCommand) {
    List<Command> commands = new ArrayList<Command>();
    SonosBindingConfig aConfig = (SonosBindingConfig) bindingConfigs.get(anItem);
    for (Command aCommand : aConfig.keySet()) {
        SonosBindingConfigElement anElement = aConfig.get(aCommand);
        if (anElement.getSonosCommand().equals(sonosCommand)) {
            commands.add(aCommand);
        }
    }
    return commands;
}
Also used : Command(org.openhab.core.types.Command) ArrayList(java.util.ArrayList)

Example 47 with Command

use of org.openhab.core.types.Command in project openhab1-addons by openhab.

the class SonosGenericBindingProvider method parseBindingConfig.

private void parseBindingConfig(SonosBindingConfig config, Item item, String bindingConfig) throws BindingConfigParseException {
    String sonosID = null;
    String commandAsString = null;
    String sonosCommand = null;
    if (bindingConfig != null) {
        Matcher actionMatcher = ACTION_CONFIG_PATTERN.matcher(bindingConfig);
        Matcher statusMatcher = STATUS_CONFIG_PATTERN.matcher(bindingConfig);
        if (!actionMatcher.matches() && !statusMatcher.matches()) {
            throw new BindingConfigParseException("Sonos binding configuration must consist of either two [config=" + statusMatcher + "] or three parts [config=" + actionMatcher + "]");
        } else {
            if (actionMatcher.matches()) {
                commandAsString = actionMatcher.group(1);
                sonosID = actionMatcher.group(2);
                sonosCommand = actionMatcher.group(3);
            } else if (statusMatcher.matches()) {
                commandAsString = null;
                sonosID = statusMatcher.group(1);
                sonosCommand = statusMatcher.group(2);
            }
            SonosBindingConfigElement newElement = new SonosBindingConfigElement(sonosCommand, sonosID, item.getAcceptedDataTypes());
            Command command = null;
            if (commandAsString == null) {
                command = createCommandFromString(null, Integer.toString(counter));
                counter++;
                config.put(command, newElement);
            } else {
                command = createCommandFromString(item, commandAsString);
                config.put(command, newElement);
            }
        }
    } else {
        return;
    }
}
Also used : Matcher(java.util.regex.Matcher) Command(org.openhab.core.types.Command) BindingConfigParseException(org.openhab.model.item.binding.BindingConfigParseException)

Example 48 with Command

use of org.openhab.core.types.Command in project openhab1-addons by openhab.

the class IhcBinding method updateResource.

/**
     * Update resource value to IHC controller.
     */
private void updateResource(String itemName, Type type, boolean updateOnlyExclusiveOutBinding) {
    if (itemName != null) {
        Command cmd = null;
        try {
            cmd = (Command) type;
        } catch (Exception e) {
        }
        IhcBindingProvider provider = findFirstMatchingBindingProvider(itemName, cmd);
        if (provider == null) {
            // command not configured, skip
            return;
        }
        if (updateOnlyExclusiveOutBinding && provider.hasInBinding(itemName)) {
            logger.trace("Ignore in binding update for item '{}'", itemName);
            return;
        }
        logger.debug("Received update/command (item='{}', state='{}', class='{}')", new Object[] { itemName, type.toString(), type.getClass().toString() });
        if (ihc == null) {
            logger.warn("Controller is not initialized, abort resource value update for item '{}'!", itemName);
            return;
        }
        if (ihc.getConnectionState() != ConnectionState.CONNECTED) {
            logger.warn("Connection to controller is not ok, abort resource value update for item '{}'!", itemName);
            return;
        }
        try {
            int resourceId = provider.getResourceId(itemName, (Command) type);
            logger.trace("found resourceId {} (item='{}', state='{}', class='{}')", new Object[] { new Integer(resourceId).toString(), itemName, type.toString(), type.getClass().toString() });
            if (resourceId > 0) {
                WSResourceValue value = ihc.getResourceValueInformation(resourceId);
                ArrayList<IhcEnumValue> enumValues = null;
                if (value instanceof WSEnumValue) {
                    enumValues = ihc.getEnumValues(((WSEnumValue) value).getDefinitionTypeID());
                }
                // check if configuration has a custom value defined
                // (0->OFF, 1->ON, >1->trigger)
                // if that is the case, the type will be overridden with a
                // new type
                Integer val = provider.getValue(itemName, (Command) type);
                boolean trigger = false;
                if (val != null) {
                    if (val == 0) {
                        type = OnOffType.OFF;
                    } else if (val == 1) {
                        type = OnOffType.ON;
                    } else {
                        trigger = true;
                    }
                } else {
                // the original type is kept
                }
                if (!trigger) {
                    value = IhcDataConverter.convertCommandToResourceValue(type, value, enumValues);
                    boolean result = updateResource(value);
                    if (result == true) {
                        logger.debug("Item updated '{}' succesfully sent", itemName);
                    } else {
                        logger.error("Item '{}' update failed", itemName);
                    }
                } else {
                    value = IhcDataConverter.convertCommandToResourceValue(OnOffType.ON, value, enumValues);
                    boolean result = updateResource(value);
                    if (result == true) {
                        logger.debug("Item '{}' trigger started", itemName);
                        Thread.sleep(val);
                        value = IhcDataConverter.convertCommandToResourceValue(OnOffType.OFF, value, enumValues);
                        result = updateResource(value);
                        if (result == true) {
                            logger.debug("Item '{}' trigger completed", itemName);
                        } else {
                            logger.error("Item '{}' trigger stop failed", itemName);
                        }
                    } else {
                        logger.error("Item '{}' update failed", itemName);
                    }
                }
            } else {
                logger.error("resourceId invalid");
            }
        } catch (IhcExecption e) {
            logger.error("Can't update Item '{}' value ", itemName, e);
        } catch (Exception e) {
            logger.error("Error occured during item update", e);
        }
    }
}
Also used : IhcEnumValue(org.openhab.binding.ihc.ws.IhcEnumValue) IhcBindingProvider(org.openhab.binding.ihc.IhcBindingProvider) WSResourceValue(org.openhab.binding.ihc.ws.datatypes.WSResourceValue) IhcExecption(org.openhab.binding.ihc.ws.IhcExecption) Command(org.openhab.core.types.Command) WSEnumValue(org.openhab.binding.ihc.ws.datatypes.WSEnumValue) ConfigurationException(org.osgi.service.cm.ConfigurationException)

Example 49 with Command

use of org.openhab.core.types.Command in project openhab1-addons by openhab.

the class HttpGenericBindingProvider method parseOutBindingConfig.

/**
     * Parses an http-out configuration by using the regular expression
     * <code>(.*?):([A-Z]*):(.*)</code>. Where the groups should contain the
     * following content:
     * <ul>
     * <li>1 - command</li>
     * <li>2 - http method</li>
     * <li>3 - url</li>
     * <li>4 - post body</li>
     * </ul>
     *
     * @param item
     * @param bindingConfig the config string to parse
     * @param config
     * @return the filled {@link HttpBindingConfig}
     *
     * @throws BindingConfigParseException if the regular expression doesn't match
     *             the given <code>bindingConfig</code>
     */
protected HttpBindingConfig parseOutBindingConfig(Item item, String bindingConfig, HttpBindingConfig config) throws BindingConfigParseException {
    logger.debug("parsing this as an http out binding: {}", bindingConfig);
    Matcher matcher = OUT_BINDING_PATTERN.matcher(bindingConfig);
    if (!matcher.matches()) {
        throw new BindingConfigParseException("bindingConfig '" + bindingConfig + "' doesn't contain a valid out-binding-configuration. A valid configuration is matched by the RegExp '" + OUT_BINDING_PATTERN + "'");
    }
    matcher.reset();
    HttpBindingConfigElement configElement;
    while (matcher.find()) {
        configElement = new HttpBindingConfigElement();
        Command command = createCommandFromString(item, matcher.group(1));
        configElement.httpMethod = matcher.group(2);
        String lastPart = matcher.group(3).replaceAll("\\\\\"", "");
        logger.debug("URL portion of binding config to be processed: {}", lastPart);
        Matcher urlMatcher = URL_PARSING_PATTERN.matcher(lastPart);
        urlMatcher.find();
        if (logger.isDebugEnabled()) {
            for (int i = 0; i <= urlMatcher.groupCount(); i++) {
                logger.debug("Group {}: {}", i, urlMatcher.group(i));
            }
        }
        if (urlMatcher.group(1).endsWith("}")) {
            String g1 = urlMatcher.group(1);
            int beginIdx = g1.indexOf("{");
            int endIdx = g1.indexOf("}");
            configElement.url = g1.substring(0, beginIdx);
            configElement.headers = parseHttpHeaders(g1.substring(beginIdx + 1, endIdx));
        } else {
            configElement.url = urlMatcher.group(1);
        }
        if (configElement.httpMethod.equals("POST") && urlMatcher.group(11) != null) {
            configElement.body = urlMatcher.group(11).substring(1);
        }
        config.put(command, configElement);
    }
    return config;
}
Also used : Matcher(java.util.regex.Matcher) Command(org.openhab.core.types.Command) BindingConfigParseException(org.openhab.model.item.binding.BindingConfigParseException)

Example 50 with Command

use of org.openhab.core.types.Command in project openhab1-addons by openhab.

the class IhcGenericBindingProvider method processBindingConfiguration.

/**
     * {@inheritDoc}
     */
@Override
public void processBindingConfiguration(String context, Item item, String bindingConfig) throws BindingConfigParseException {
    super.processBindingConfiguration(context, item, bindingConfig);
    IhcBindingConfig config = new IhcBindingConfig();
    config.itemType = item.getClass();
    config.outCommandMap = new HashMap<Command, IhcOutCommandConfig>();
    String[] splittedCommands = bindingConfig.split(",");
    for (String split : splittedCommands) {
        if (split.startsWith(">")) {
            try {
                // out binding
                String resourceCommand = split.substring(1);
                Matcher m = commandPattern.matcher(resourceCommand);
                IhcOutCommandConfig outConfig = new IhcOutCommandConfig();
                if (!m.matches()) {
                    if (splittedCommands.length < 2) {
                        // assume old style out command
                        // wildcard
                        outConfig.command = null;
                        outConfig.resourceId = getResourceIdFromString(resourceCommand);
                    } else {
                        throw new BindingConfigParseException("Item '" + item.getName() + "' has invalid out binding config");
                    }
                } else {
                    // new style out binding
                    Command command = TypeParser.parseCommand(item.getAcceptedCommandTypes(), m.group(1));
                    if (command == null && !m.group(1).equals("*")) {
                        throw new BindingConfigParseException("Item '" + item.getName() + " invalid Command: " + m.group(1));
                    }
                    outConfig.command = command;
                    outConfig.resourceId = getResourceIdFromString(m.group(2));
                    if (m.groupCount() == 3 && m.group(3) != null) {
                        outConfig.value = Integer.parseInt(m.group(3));
                        if (outConfig.value > 2000) {
                            throw new BindingConfigParseException("Item '" + item.getName() + "' exceeds maximum value of 2000 ms for trigger command");
                        }
                    }
                }
                config.outCommandMap.put(outConfig.command, outConfig);
            } catch (Exception e) {
                logger.warn("Error in output config for item: " + item.getName(), e);
            }
        } else if (split.startsWith("<")) {
            if (config.resourceId < 1) {
                config.resourceId = getResourceIdFromString(split.substring(1));
            } else {
                throw new BindingConfigParseException("Multiple In-Bindings found, only one In-Binding allowed.");
            }
        } else {
            if (splittedCommands.length < 2) {
                String[] configParts = bindingConfig.trim().split(":");
                if (configParts.length > 2) {
                    throw new BindingConfigParseException("IHC / ELKO LS binding must contain of max two two parts separated by ':'");
                }
                String resourceId = configParts[0];
                config.resourceId = getResourceIdFromString(resourceId);
                IhcOutCommandConfig outConfig = new IhcOutCommandConfig();
                // wildcard
                outConfig.command = null;
                outConfig.resourceId = config.resourceId;
                config.outCommandMap.put(null, outConfig);
                if (configParts.length == 2) {
                    config.refreshInterval = Integer.parseInt(configParts[1]);
                }
            } else {
                throw new BindingConfigParseException("Only a sum of out bindings (+In-Only Binding) or a normal binding is supported.");
            }
        }
    }
    addBindingConfig(item, config);
}
Also used : Command(org.openhab.core.types.Command) Matcher(java.util.regex.Matcher) BindingConfigParseException(org.openhab.model.item.binding.BindingConfigParseException) BindingConfigParseException(org.openhab.model.item.binding.BindingConfigParseException)

Aggregations

Command (org.openhab.core.types.Command)61 ArrayList (java.util.ArrayList)20 BindingConfigParseException (org.openhab.model.item.binding.BindingConfigParseException)14 State (org.openhab.core.types.State)12 Matcher (java.util.regex.Matcher)10 DecimalType (org.openhab.core.library.types.DecimalType)8 Test (org.junit.Test)7 InetSocketAddress (java.net.InetSocketAddress)6 NikobusCommand (org.openhab.binding.nikobus.internal.core.NikobusCommand)6 SchedulerException (org.quartz.SchedulerException)6 StringType (org.openhab.core.library.types.StringType)5 JobDataMap (org.quartz.JobDataMap)5 JobDetail (org.quartz.JobDetail)5 Scheduler (org.quartz.Scheduler)5 Trigger (org.quartz.Trigger)5 TriggerBuilder.newTrigger (org.quartz.TriggerBuilder.newTrigger)5 IOException (java.io.IOException)4 SocketChannel (java.nio.channels.SocketChannel)4 IllegalClassException (org.apache.commons.lang.IllegalClassException)4 PercentType (org.openhab.core.library.types.PercentType)4