Search in sources :

Example 1 with Action

use of org.eclipse.smarthome.automation.Action in project smarthome by eclipse.

the class ReferenceResolverUtilTest method testModuleInputResolving.

@Test
public void testModuleInputResolving() {
    // test Composite child Module(condition) context
    Module condition = new Condition(null, null, null, compositeChildModuleInputsReferences);
    Map<String, Object> conditionContext = ReferenceResolverUtil.getCompositeChildContext(condition, context);
    Assert.assertEquals(conditionContext, expectedCompositeChildModuleContext);
    // test Composite child Module(action) context
    Module action = new Action(null, null, null, compositeChildModuleInputsReferences);
    Map<String, Object> actionContext = ReferenceResolverUtil.getCompositeChildContext(action, context);
    Assert.assertEquals(actionContext, expectedCompositeChildModuleContext);
}
Also used : Condition(org.eclipse.smarthome.automation.Condition) Action(org.eclipse.smarthome.automation.Action) Module(org.eclipse.smarthome.automation.Module) Test(org.junit.Test)

Example 2 with Action

use of org.eclipse.smarthome.automation.Action in project smarthome by eclipse.

the class RuleEngineTest method testRuleActions.

/**
 * test rule actions
 */
@Test
public void testRuleActions() {
    RuleEngine ruleEngine = createRuleEngine();
    Rule rule1 = createRule();
    List<Action> actions = rule1.getActions();
    ruleEngine.addRule(rule1, true);
    RuntimeRule rule1Get = ruleEngine.getRuntimeRule("rule1");
    List<Action> actionsGet = rule1Get.getActions();
    Assert.assertNotNull("Null actions list", actionsGet);
    Assert.assertEquals("Empty actions list", 1, actionsGet.size());
    Assert.assertEquals("Returned actions list should not be a copy", actionsGet, rule1Get.getActions());
    actions.add(new Action("actionId2", "typeUID2", null, null));
    ruleEngine.updateRule(rule1, true);
    rule1Get = ruleEngine.getRuntimeRule("rule1");
    List<Action> actionsGet2 = rule1Get.getActions();
    Assert.assertNotNull("Null actions list", actionsGet2);
    Assert.assertEquals("Action was not added to the rule's list of actions", 2, actionsGet2.size());
    Assert.assertNotNull("Rule action with wrong id is returned", rule1Get.getModule("actionId2"));
    actions.add(new Action("actionId3", "typeUID3", null, null));
    // ruleEngine.update will update the RuntimeRule.moduleMap with the new
    ruleEngine.updateRule(rule1, true);
    // module
    rule1Get = ruleEngine.getRuntimeRule("rule1");
    List<Action> actionsGet3 = rule1Get.getActions();
    Assert.assertNotNull("Null actions list", actionsGet3);
    Assert.assertEquals("Action was not added to the rule's list of actions", 3, actionsGet3.size());
    Assert.assertNotNull("Rule modules map was not updated", ruleEngine.getRuntimeRule("rule1").getModule("actionId3"));
}
Also used : Action(org.eclipse.smarthome.automation.Action) Rule(org.eclipse.smarthome.automation.Rule) Test(org.junit.Test)

Example 3 with Action

use of org.eclipse.smarthome.automation.Action in project smarthome by eclipse.

the class RuleEngine method autoMapConnections.

/**
 * The auto mapping tries to link not connected module inputs to output of other modules. The auto mapping will link
 * input to output only when following criteria are done: 1) input must not be connected. The auto mapping will not
 * overwrite explicit connections done by the user. 2) input tags must be subset of the output tags. 3) condition
 * inputs can be connected only to triggers' outputs 4) action outputs can be connected to both conditions and
 * actions
 * outputs 5) There is only one output, based on previous criteria, where the input can connect to. If more then one
 * candidate outputs exists for connection, this is a conflict and the auto mapping leaves the input unconnected.
 * Auto
 * mapping is always applied when the rule is added or updated. It changes initial value of inputs of conditions and
 * actions participating in the rule. If an "auto map" connection has to be removed, the tags of corresponding
 * input/output have to be changed.
 *
 * @param r updated rule
 */
private void autoMapConnections(RuntimeRule r) {
    Map<Set<String>, OutputRef> triggerOutputTags = new HashMap<Set<String>, OutputRef>(11);
    for (Trigger t : r.getTriggers()) {
        TriggerType tt = (TriggerType) mtRegistry.get(t.getTypeUID());
        if (tt != null) {
            initTagsMap(t.getId(), tt.getOutputs(), triggerOutputTags);
        }
    }
    Map<Set<String>, OutputRef> actionOutputTags = new HashMap<Set<String>, OutputRef>(11);
    for (Action a : r.getActions()) {
        ActionType at = (ActionType) mtRegistry.get(a.getTypeUID());
        if (at != null) {
            initTagsMap(a.getId(), at.getOutputs(), actionOutputTags);
        }
    }
    // auto mapping of conditions
    if (!triggerOutputTags.isEmpty()) {
        for (Condition c : r.getConditions()) {
            boolean isConnectionChanged = false;
            ConditionType ct = (ConditionType) mtRegistry.get(c.getTypeUID());
            if (ct != null) {
                Set<Connection> connections = ((RuntimeCondition) c).getConnections();
                for (Input input : ct.getInputs()) {
                    if (isConnected(input, connections)) {
                        // the input is already connected. Skip it.
                        continue;
                    }
                    if (addAutoMapConnections(input, triggerOutputTags, connections)) {
                        isConnectionChanged = true;
                    }
                }
                if (isConnectionChanged) {
                    // update condition inputs
                    connections = ((RuntimeCondition) c).getConnections();
                    Map<String, String> connectionMap = getConnectionMap(connections);
                    c.setInputs(connectionMap);
                }
            }
        }
    }
    // auto mapping of actions
    if (!triggerOutputTags.isEmpty() || !actionOutputTags.isEmpty()) {
        for (Action a : r.getActions()) {
            boolean isConnectionChanged = false;
            ActionType at = (ActionType) mtRegistry.get(a.getTypeUID());
            if (at != null) {
                Set<Connection> connections = ((RuntimeAction) a).getConnections();
                for (Input input : at.getInputs()) {
                    if (isConnected(input, connections)) {
                        // the input is already connected. Skip it.
                        continue;
                    }
                    if (addAutoMapConnections(input, triggerOutputTags, connections)) {
                        isConnectionChanged = true;
                    }
                    if (addAutoMapConnections(input, actionOutputTags, connections)) {
                        isConnectionChanged = true;
                    }
                }
                if (isConnectionChanged) {
                    // update condition inputs
                    connections = ((RuntimeAction) a).getConnections();
                    Map<String, String> connectionMap = getConnectionMap(connections);
                    a.setInputs(connectionMap);
                }
            }
        }
    }
}
Also used : Condition(org.eclipse.smarthome.automation.Condition) CompositeTriggerType(org.eclipse.smarthome.automation.type.CompositeTriggerType) TriggerType(org.eclipse.smarthome.automation.type.TriggerType) Action(org.eclipse.smarthome.automation.Action) Set(java.util.Set) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) HashSet(java.util.HashSet) CompositeActionType(org.eclipse.smarthome.automation.type.CompositeActionType) ActionType(org.eclipse.smarthome.automation.type.ActionType) HashMap(java.util.HashMap) Input(org.eclipse.smarthome.automation.type.Input) Trigger(org.eclipse.smarthome.automation.Trigger) CompositeConditionType(org.eclipse.smarthome.automation.type.CompositeConditionType) ConditionType(org.eclipse.smarthome.automation.type.ConditionType)

Example 4 with Action

use of org.eclipse.smarthome.automation.Action in project smarthome by eclipse.

the class RuleEngine method executeActions.

/**
 * This method evaluates actions of the {@link Rule} and set their {@link Output}s when they exists.
 *
 * @param rule executed rule.
 */
private void executeActions(Rule rule, boolean stopOnFirstFail) {
    List<Action> actions = ((RuntimeRule) rule).getActions();
    if (actions.size() == 0) {
        return;
    }
    RuleStatus ruleStatus = null;
    for (Iterator<Action> it = actions.iterator(); it.hasNext(); ) {
        ruleStatus = getRuleStatus(rule.getUID());
        if (ruleStatus != RuleStatus.RUNNING) {
            return;
        }
        RuntimeAction action = (RuntimeAction) it.next();
        ActionHandler aHandler = action.getModuleHandler();
        String rUID = rule.getUID();
        Map<String, Object> context = getContext(rUID, action.getConnections());
        try {
            Map<String, ?> outputs = aHandler.execute(Collections.unmodifiableMap(context));
            if (outputs != null) {
                context = getContext(rUID);
                updateContext(rUID, action.getId(), outputs);
            }
        } catch (Throwable t) {
            String errMessage = "Failed to execute action '" + action.getId() + "': " + t.getMessage();
            if (stopOnFirstFail) {
                RuntimeException re = new RuntimeException(errMessage, t);
                throw re;
            } else {
                logger.warn("Error message: {}", errMessage);
            }
        }
    }
}
Also used : Action(org.eclipse.smarthome.automation.Action) RuleStatus(org.eclipse.smarthome.automation.RuleStatus) ActionHandler(org.eclipse.smarthome.automation.handler.ActionHandler)

Example 5 with Action

use of org.eclipse.smarthome.automation.Action in project smarthome by eclipse.

the class RunRuleModuleTest method createSceneRule.

private Rule createSceneRule() {
    final Configuration sceneRuleAction1Config = new Configuration(Collections.unmodifiableMap(Stream.of(new SimpleEntry<>("itemName", "switch1"), new SimpleEntry<>("command", "ON")).collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()))));
    final Configuration sceneRuleAction2Config = new Configuration(Collections.unmodifiableMap(Stream.of(new SimpleEntry<>("itemName", "switch2"), new SimpleEntry<>("command", "ON")).collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()))));
    final Configuration sceneRuleAction3Config = new Configuration(Collections.unmodifiableMap(Stream.of(new SimpleEntry<>("itemName", "switch3"), new SimpleEntry<>("command", "ON")).collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()))));
    final Rule sceneRule = new Rule("exampleSceneRule");
    sceneRule.setActions(Arrays.asList(new Action[] { new Action("sceneItemPostCommandAction1", "core.ItemCommandAction", sceneRuleAction1Config, null), new Action("sceneItemPostCommandAction2", "core.ItemCommandAction", sceneRuleAction2Config, null), new Action("sceneItemPostCommandAction3", "core.ItemCommandAction", sceneRuleAction3Config, null) }));
    sceneRule.setName("Example Scene");
    return sceneRule;
}
Also used : Trigger(org.eclipse.smarthome.automation.Trigger) SwitchItem(org.eclipse.smarthome.core.library.items.SwitchItem) Arrays(java.util.Arrays) ProviderChangeListener(org.eclipse.smarthome.core.common.registry.ProviderChangeListener) ItemCommandEvent(org.eclipse.smarthome.core.items.events.ItemCommandEvent) LoggerFactory(org.slf4j.LoggerFactory) OnOffType(org.eclipse.smarthome.core.library.types.OnOffType) ItemProvider(org.eclipse.smarthome.core.items.ItemProvider) EventFilter(org.eclipse.smarthome.core.events.EventFilter) EventSubscriber(org.eclipse.smarthome.core.events.EventSubscriber) LinkedList(java.util.LinkedList) SimpleEntry(java.util.AbstractMap.SimpleEntry) Configuration(org.eclipse.smarthome.config.core.Configuration) RuleRegistry(org.eclipse.smarthome.automation.RuleRegistry) Before(org.junit.Before) RuleStatus(org.eclipse.smarthome.automation.RuleStatus) JavaOSGiTest(org.eclipse.smarthome.test.java.JavaOSGiTest) VolatileStorageService(org.eclipse.smarthome.test.storage.VolatileStorageService) Logger(org.slf4j.Logger) ItemEventFactory(org.eclipse.smarthome.core.items.events.ItemEventFactory) Collection(java.util.Collection) Set(java.util.Set) EventPublisher(org.eclipse.smarthome.core.events.EventPublisher) Test(org.junit.Test) Rule(org.eclipse.smarthome.automation.Rule) ItemNotFoundException(org.eclipse.smarthome.core.items.ItemNotFoundException) Collectors(java.util.stream.Collectors) Item(org.eclipse.smarthome.core.items.Item) ItemRegistry(org.eclipse.smarthome.core.items.ItemRegistry) Stream(java.util.stream.Stream) Action(org.eclipse.smarthome.automation.Action) Queue(java.util.Queue) Assert(org.junit.Assert) Event(org.eclipse.smarthome.core.events.Event) Collections(java.util.Collections) Action(org.eclipse.smarthome.automation.Action) Configuration(org.eclipse.smarthome.config.core.Configuration) SimpleEntry(java.util.AbstractMap.SimpleEntry) Rule(org.eclipse.smarthome.automation.Rule)

Aggregations

Action (org.eclipse.smarthome.automation.Action)28 Trigger (org.eclipse.smarthome.automation.Trigger)15 Configuration (org.eclipse.smarthome.config.core.Configuration)15 Condition (org.eclipse.smarthome.automation.Condition)9 Rule (org.eclipse.smarthome.automation.Rule)9 ArrayList (java.util.ArrayList)8 Test (org.junit.Test)8 HashMap (java.util.HashMap)6 Set (java.util.Set)5 RuleRegistry (org.eclipse.smarthome.automation.RuleRegistry)5 EventPublisher (org.eclipse.smarthome.core.events.EventPublisher)5 JavaOSGiTest (org.eclipse.smarthome.test.java.JavaOSGiTest)5 LinkedList (java.util.LinkedList)4 Event (org.eclipse.smarthome.core.events.Event)4 HashSet (java.util.HashSet)3 RuleStatus (org.eclipse.smarthome.automation.RuleStatus)3 ActionHandler (org.eclipse.smarthome.automation.handler.ActionHandler)3 ActionType (org.eclipse.smarthome.automation.type.ActionType)3 CompositeActionType (org.eclipse.smarthome.automation.type.CompositeActionType)3 ConfigDescriptionParameter (org.eclipse.smarthome.config.core.ConfigDescriptionParameter)3