Search in sources :

Example 21 with Rule

use of org.openhab.core.automation.Rule in project openhab-core by openhab.

the class ScriptRuleOSGiTest method testPredefinedRule.

// ignore - wip @Test
public void testPredefinedRule() throws ItemNotFoundException {
    EventPublisher eventPublisher = getService(EventPublisher.class);
    ItemRegistry itemRegistry = getService(ItemRegistry.class);
    RuleRegistry ruleRegistry = getService(RuleRegistry.class);
    RuleManager ruleEngine = getService(RuleManager.class);
    // WAIT until Rule modules types are parsed and the rule becomes IDLE
    waitForAssert(() -> {
        assertThat(ruleRegistry.getAll().isEmpty(), is(false));
        Rule rule2 = ruleRegistry.get("javascript.rule1");
        assertThat(rule2, is(notNullValue()));
        RuleStatusInfo ruleStatus2 = ruleEngine.getStatusInfo(rule2.getUID());
        assertThat(ruleStatus2, is(notNullValue()));
        assertThat(ruleStatus2.getStatus(), is(RuleStatus.IDLE));
    }, 5000, 200);
    Rule rule = ruleRegistry.get("javascript.rule1");
    assertThat(rule, is(notNullValue()));
    assertThat(rule.getName(), is("DemoScriptRule"));
    Optional<? extends Trigger> trigger = rule.getTriggers().stream().filter(t -> "trigger".equals(t.getId())).findFirst();
    assertThat(trigger.isPresent(), is(true));
    assertThat(trigger.get().getTypeUID(), is("core.GenericEventTrigger"));
    assertThat(trigger.get().getConfiguration().get("eventSource"), is("MyTrigger"));
    assertThat(trigger.get().getConfiguration().get("eventTopic"), is("openhab/items/MyTrigger/state"));
    assertThat(trigger.get().getConfiguration().get("eventTypes"), is("ItemStateEvent"));
    Optional<? extends Condition> condition1 = rule.getConditions().stream().filter(c -> "condition".equals(c.getId())).findFirst();
    assertThat(condition1.isPresent(), is(true));
    assertThat(condition1.get().getTypeUID(), is("script.ScriptCondition"));
    assertThat(condition1.get().getConfiguration().get("type"), is("application/javascript"));
    assertThat(condition1.get().getConfiguration().get("script"), is("event.itemState==ON"));
    Optional<? extends Action> action = rule.getActions().stream().filter(a -> "action".equals(a.getId())).findFirst();
    assertThat(action.isPresent(), is(true));
    assertThat(action.get().getTypeUID(), is("script.ScriptAction"));
    assertThat(action.get().getConfiguration().get("type"), is("application/javascript"));
    assertThat(action.get().getConfiguration().get("script"), is("print(items.MyTrigger), print(things.getAll()), print(ctx.get('trigger.event')), events.sendCommand('ScriptItem', 'ON')"));
    RuleStatusInfo ruleStatus = ruleEngine.getStatusInfo(rule.getUID());
    assertThat(ruleStatus.getStatus(), is(RuleStatus.IDLE));
    SwitchItem myTriggerItem = (SwitchItem) itemRegistry.getItem("MyTrigger");
    logger.info("Triggering item: {}", myTriggerItem.getName());
    eventPublisher.post(ItemEventFactory.createStateEvent("MyTrigger", OnOffType.ON));
    waitForAssert(() -> {
        assertThat(receivedEvent, notNullValue());
    });
    assertThat(receivedEvent.getItemName(), is(equalTo("ScriptItem")));
    assertThat(receivedEvent.getItemCommand(), is(OnOffType.ON));
}
Also used : ItemEventFactory(org.openhab.core.items.events.ItemEventFactory) VolatileStorageService(org.openhab.core.test.storage.VolatileStorageService) CoreMatchers(org.hamcrest.CoreMatchers) BeforeEach(org.junit.jupiter.api.BeforeEach) EventSubscriber(org.openhab.core.events.EventSubscriber) RuleRegistry(org.openhab.core.automation.RuleRegistry) SwitchItem(org.openhab.core.library.items.SwitchItem) RuleManager(org.openhab.core.automation.RuleManager) LoggerFactory(org.slf4j.LoggerFactory) OnOffType(org.openhab.core.library.types.OnOffType) Trigger(org.openhab.core.automation.Trigger) Nullable(org.eclipse.jdt.annotation.Nullable) EventFilter(org.openhab.core.events.EventFilter) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) EventPublisher(org.openhab.core.events.EventPublisher) Condition(org.openhab.core.automation.Condition) ItemCommandEvent(org.openhab.core.items.events.ItemCommandEvent) RuleStatusInfo(org.openhab.core.automation.RuleStatusInfo) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) Logger(org.slf4j.Logger) ItemProvider(org.openhab.core.items.ItemProvider) Collection(java.util.Collection) Action(org.openhab.core.automation.Action) Event(org.openhab.core.events.Event) ItemNotFoundException(org.openhab.core.items.ItemNotFoundException) Set(java.util.Set) Rule(org.openhab.core.automation.Rule) Item(org.openhab.core.items.Item) ItemRegistry(org.openhab.core.items.ItemRegistry) RuleStatus(org.openhab.core.automation.RuleStatus) List(java.util.List) JavaOSGiTest(org.openhab.core.test.java.JavaOSGiTest) Optional(java.util.Optional) ProviderChangeListener(org.openhab.core.common.registry.ProviderChangeListener) RuleStatusInfo(org.openhab.core.automation.RuleStatusInfo) EventPublisher(org.openhab.core.events.EventPublisher) RuleRegistry(org.openhab.core.automation.RuleRegistry) RuleManager(org.openhab.core.automation.RuleManager) Rule(org.openhab.core.automation.Rule) ItemRegistry(org.openhab.core.items.ItemRegistry) SwitchItem(org.openhab.core.library.items.SwitchItem)

Example 22 with Rule

use of org.openhab.core.automation.Rule in project openhab-core by openhab.

the class AutomationIntegrationTest method testChainOfCompositeModules.

@Test
public void testChainOfCompositeModules() throws ItemNotFoundException {
    Configuration triggerConfig = new Configuration(Map.of("itemName", "myMotionItem4"));
    Map<String, Object> params = new HashMap<>();
    params.put("itemName", "myLampItem4");
    params.put("command", "ON");
    Configuration actionConfig = new Configuration(params);
    List<Trigger> triggers = List.of(ModuleBuilder.createTrigger().withId("ItemStateChangeTrigger4").withTypeUID("core.ItemStateChangeTrigger").withConfiguration(triggerConfig).build());
    List<Action> actions = List.of(ModuleBuilder.createAction().withId("ItemPostCommandAction4").withTypeUID("core.ItemCommandAction").withConfiguration(actionConfig).build());
    Rule rule = RuleBuilder.create("myRule21" + new Random().nextInt() + "_COMPOSITE").withTriggers(triggers).withActions(actions).withName("RuleByJAVA_API_ChainedComposite").build();
    logger.info("Rule created: {}", rule.getUID());
    RuleRegistry ruleRegistry = getService(RuleRegistry.class);
    ruleRegistry.add(rule);
    // TEST RULE
    waitForAssert(() -> {
        assertThat(ruleEngine.getStatusInfo(rule.getUID()).getStatus(), is(RuleStatus.IDLE));
    });
    EventPublisher eventPublisher = getService(EventPublisher.class);
    // prepare the presenceItems state to be on to match the second condition of the rule
    eventPublisher.post(ItemEventFactory.createStateEvent("myPresenceItem4", OnOffType.ON));
    EventSubscriber itemEventHandler = new EventSubscriber() {

        @Override
        public Set<String> getSubscribedEventTypes() {
            return Set.of(ItemCommandEvent.TYPE);
        }

        @Override
        @Nullable
        public EventFilter getEventFilter() {
            return null;
        }

        @Override
        public void receive(Event e) {
            logger.info("Event: {}", e.getTopic());
            if (e.getTopic().contains("myLampItem4")) {
                itemEvent = e;
            }
        }
    };
    registerService(itemEventHandler);
    // causing the event to trigger the rule
    eventPublisher.post(ItemEventFactory.createStateEvent("myMotionItem4", OnOffType.ON));
    waitForAssert(() -> {
        assertThat(itemEvent, is(notNullValue()));
    }, 5000, 100);
    assertThat(itemEvent.getTopic(), is(equalTo("openhab/items/myLampItem4/command")));
    assertThat(((ItemCommandEvent) itemEvent).getItemCommand(), is(OnOffType.ON));
}
Also used : EventSubscriber(org.openhab.core.events.EventSubscriber) Action(org.openhab.core.automation.Action) Configuration(org.openhab.core.config.core.Configuration) EventPublisher(org.openhab.core.events.EventPublisher) HashMap(java.util.HashMap) RuleRegistry(org.openhab.core.automation.RuleRegistry) Trigger(org.openhab.core.automation.Trigger) Random(java.util.Random) RuleRemovedEvent(org.openhab.core.automation.events.RuleRemovedEvent) RuleAddedEvent(org.openhab.core.automation.events.RuleAddedEvent) RuleStatusInfoEvent(org.openhab.core.automation.events.RuleStatusInfoEvent) ItemCommandEvent(org.openhab.core.items.events.ItemCommandEvent) Event(org.openhab.core.events.Event) RuleUpdatedEvent(org.openhab.core.automation.events.RuleUpdatedEvent) Rule(org.openhab.core.automation.Rule) Test(org.junit.jupiter.api.Test) JavaOSGiTest(org.openhab.core.test.java.JavaOSGiTest)

Example 23 with Rule

use of org.openhab.core.automation.Rule in project openhab-core by openhab.

the class AutomationIntegrationTest method assertThatARuleCanBeAddedByARuleProvider.

@Test
public void assertThatARuleCanBeAddedByARuleProvider() {
    logger.info("assert that a rule can be added by a ruleProvider");
    Rule rule = createSimpleRule();
    RuleProvider ruleProvider = new RuleProvider() {

        @Override
        public void addProviderChangeListener(ProviderChangeListener<Rule> listener) {
        }

        @Override
        public Collection<Rule> getAll() {
            return Set.of(rule);
        }

        @Override
        public void removeProviderChangeListener(ProviderChangeListener<Rule> listener) {
        }
    };
    registerService(ruleProvider);
    assertThat(ruleRegistry.get(rule.getUID()), is(notNullValue()));
    unregisterService(ruleProvider);
    assertThat(ruleRegistry.get(rule.getUID()), is(nullValue()));
    Rule rule2 = createSimpleRule();
    assertThat(ruleRegistry.get(rule2.getUID()), is(nullValue()));
    managedRuleProvider.add(rule2);
    assertThat(ruleRegistry.get(rule2.getUID()), is(notNullValue()));
    managedRuleProvider.remove(rule2.getUID());
    assertThat(ruleRegistry.get(rule2.getUID()), is(nullValue()));
}
Also used : ProviderChangeListener(org.openhab.core.common.registry.ProviderChangeListener) Rule(org.openhab.core.automation.Rule) ManagedRuleProvider(org.openhab.core.automation.ManagedRuleProvider) RuleProvider(org.openhab.core.automation.RuleProvider) Test(org.junit.jupiter.api.Test) JavaOSGiTest(org.openhab.core.test.java.JavaOSGiTest)

Example 24 with Rule

use of org.openhab.core.automation.Rule in project openhab-core by openhab.

the class AutomationIntegrationTest method assertThatARuleBasedOnACompositeModuleIsInitializedAndExecutedCorrectly.

@Test
public void assertThatARuleBasedOnACompositeModuleIsInitializedAndExecutedCorrectly() {
    Map<String, Object> params = new HashMap<>();
    params.put("itemName", "myMotionItem3");
    Configuration triggerConfig = new Configuration(params);
    params = new HashMap<>();
    params.put("itemName", "myLampItem3");
    params.put("command", "ON");
    Configuration actionConfig = new Configuration(params);
    List<Trigger> triggers = List.of(ModuleBuilder.createTrigger().withId("ItemStateChangeTrigger3").withTypeUID("core.ItemStateChangeTrigger").withConfiguration(triggerConfig).build());
    List<Action> actions = List.of(ModuleBuilder.createAction().withId("ItemPostCommandAction3").withTypeUID("core.ItemCommandAction").withConfiguration(actionConfig).build());
    Rule rule = RuleBuilder.create("myRule21" + new Random().nextInt() + "_COMPOSITE").withTriggers(triggers).withActions(actions).withName("RuleByJAVA_API_WIthCompositeTrigger").build();
    logger.info("Rule created: {}", rule.getUID());
    RuleRegistry ruleRegistry = getService(RuleRegistry.class);
    ruleRegistry.add(rule);
    // TEST RULE
    waitForAssert(() -> {
        assertThat(ruleEngine.getStatusInfo(rule.getUID()).getStatus(), is(RuleStatus.IDLE));
    });
    EventPublisher eventPublisher = getService(EventPublisher.class);
    eventPublisher.post(ItemEventFactory.createStateEvent("myPresenceItem3", OnOffType.ON));
    EventSubscriber itemEventHandler = new EventSubscriber() {

        @Override
        public Set<String> getSubscribedEventTypes() {
            return Set.of(ItemCommandEvent.TYPE);
        }

        @Override
        @Nullable
        public EventFilter getEventFilter() {
            return null;
        }

        @Override
        public void receive(Event e) {
            logger.info("Event: {}", e.getTopic());
            if (e.getTopic().contains("myLampItem3")) {
                itemEvent = e;
            }
        }
    };
    registerService(itemEventHandler);
    eventPublisher.post(ItemEventFactory.createStateEvent("myMotionItem3", OnOffType.ON));
    waitForAssert(() -> {
        assertThat(itemEvent, is(notNullValue()));
    }, 3000, 100);
    assertThat(itemEvent.getTopic(), is(equalTo("openhab/items/myLampItem3/command")));
    assertThat(((ItemCommandEvent) itemEvent).getItemCommand(), is(OnOffType.ON));
}
Also used : EventSubscriber(org.openhab.core.events.EventSubscriber) Action(org.openhab.core.automation.Action) Configuration(org.openhab.core.config.core.Configuration) EventPublisher(org.openhab.core.events.EventPublisher) HashMap(java.util.HashMap) RuleRegistry(org.openhab.core.automation.RuleRegistry) Trigger(org.openhab.core.automation.Trigger) Random(java.util.Random) RuleRemovedEvent(org.openhab.core.automation.events.RuleRemovedEvent) RuleAddedEvent(org.openhab.core.automation.events.RuleAddedEvent) RuleStatusInfoEvent(org.openhab.core.automation.events.RuleStatusInfoEvent) ItemCommandEvent(org.openhab.core.items.events.ItemCommandEvent) Event(org.openhab.core.events.Event) RuleUpdatedEvent(org.openhab.core.automation.events.RuleUpdatedEvent) Rule(org.openhab.core.automation.Rule) Test(org.junit.jupiter.api.Test) JavaOSGiTest(org.openhab.core.test.java.JavaOSGiTest)

Example 25 with Rule

use of org.openhab.core.automation.Rule in project openhab-core by openhab.

the class AutomationIntegrationTest method assertThatARuleCanBeAddedUpdatedAndRemovedByTheApi.

@Test
public void assertThatARuleCanBeAddedUpdatedAndRemovedByTheApi() {
    logger.info("assert that a rule can be added, updated and removed by the api");
    EventSubscriber ruleEventHandler = new EventSubscriber() {

        @Override
        public Set<String> getSubscribedEventTypes() {
            return Stream.of(RuleAddedEvent.TYPE, RuleRemovedEvent.TYPE, RuleUpdatedEvent.TYPE).collect(toSet());
        }

        @Override
        @Nullable
        public EventFilter getEventFilter() {
            return null;
        }

        @Override
        public void receive(Event e) {
            logger.info("RuleEvent: {}", e.getTopic());
            ruleEvent = e;
        }
    };
    registerService(ruleEventHandler);
    // ADD
    Rule rule = createSimpleRule();
    ruleRegistry.add(rule);
    waitForAssert(() -> {
        assertThat(ruleEvent, is(notNullValue()));
        assertThat(ruleEvent, is(instanceOf(RuleAddedEvent.class)));
        RuleAddedEvent ruleAddedEvent = (RuleAddedEvent) ruleEvent;
        assertThat(ruleAddedEvent.getRule().uid, is(rule.getUID()));
    }, 5000, 500);
    Rule ruleAdded = ruleRegistry.get(rule.getUID());
    assertThat(ruleAdded, is(notNullValue()));
    assertThat(ruleEngine.getStatusInfo(rule.getUID()).getStatus(), is(RuleStatus.IDLE));
    // UPDATE
    ruleEvent = null;
    if (ruleAdded == null) {
        throw new AssertionError("ruleAdded is null");
    }
    Rule updatedRule = RuleBuilder.create(ruleAdded).withDescription("TestDescription").build();
    Rule oldRule = ruleRegistry.update(updatedRule);
    waitForAssert(() -> {
        assertThat(ruleEvent, is(notNullValue()));
        assertThat(ruleEvent, is(instanceOf(RuleUpdatedEvent.class)));
        RuleUpdatedEvent ruEvent = (RuleUpdatedEvent) ruleEvent;
        assertThat(ruEvent.getRule().uid, is(rule.getUID()));
        assertThat(ruEvent.getOldRule().uid, is(rule.getUID()));
        assertThat(ruEvent.getRule().description, is("TestDescription"));
        assertThat(ruEvent.getOldRule().description, is(nullValue()));
    });
    assertThat(oldRule, is(notNullValue()));
    assertThat(oldRule, is(rule));
    // REMOVE
    ruleEvent = null;
    Rule removed = ruleRegistry.remove(rule.getUID());
    waitForAssert(() -> {
        assertThat(ruleEvent, is(notNullValue()));
        assertThat(ruleEvent, is(instanceOf(RuleRemovedEvent.class)));
        RuleRemovedEvent reEvent = (RuleRemovedEvent) ruleEvent;
        assertThat(reEvent.getRule().uid, is(removed.getUID()));
    });
    assertThat(removed, is(notNullValue()));
    assertThat(removed, is(ruleAdded));
    assertThat(ruleRegistry.get(removed.getUID()), is(nullValue()));
}
Also used : EventSubscriber(org.openhab.core.events.EventSubscriber) RuleRemovedEvent(org.openhab.core.automation.events.RuleRemovedEvent) RuleRemovedEvent(org.openhab.core.automation.events.RuleRemovedEvent) RuleAddedEvent(org.openhab.core.automation.events.RuleAddedEvent) RuleStatusInfoEvent(org.openhab.core.automation.events.RuleStatusInfoEvent) ItemCommandEvent(org.openhab.core.items.events.ItemCommandEvent) Event(org.openhab.core.events.Event) RuleUpdatedEvent(org.openhab.core.automation.events.RuleUpdatedEvent) RuleAddedEvent(org.openhab.core.automation.events.RuleAddedEvent) RuleUpdatedEvent(org.openhab.core.automation.events.RuleUpdatedEvent) Rule(org.openhab.core.automation.Rule) Test(org.junit.jupiter.api.Test) JavaOSGiTest(org.openhab.core.test.java.JavaOSGiTest)

Aggregations

Rule (org.openhab.core.automation.Rule)76 Test (org.junit.jupiter.api.Test)47 JavaOSGiTest (org.openhab.core.test.java.JavaOSGiTest)36 Configuration (org.openhab.core.config.core.Configuration)27 Trigger (org.openhab.core.automation.Trigger)23 Action (org.openhab.core.automation.Action)21 Event (org.openhab.core.events.Event)19 ItemCommandEvent (org.openhab.core.items.events.ItemCommandEvent)19 EventSubscriber (org.openhab.core.events.EventSubscriber)16 RuleStatusInfoEvent (org.openhab.core.automation.events.RuleStatusInfoEvent)15 RuleRegistry (org.openhab.core.automation.RuleRegistry)14 HashMap (java.util.HashMap)13 Random (java.util.Random)13 EventPublisher (org.openhab.core.events.EventPublisher)13 ArrayList (java.util.ArrayList)12 Response (javax.ws.rs.core.Response)12 Operation (io.swagger.v3.oas.annotations.Operation)10 Path (javax.ws.rs.Path)10 RuleManager (org.openhab.core.automation.RuleManager)10 RuleAddedEvent (org.openhab.core.automation.events.RuleAddedEvent)10