Search in sources :

Example 1 with RuleRegistry

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

the class AutomationIntegrationJsonTest method before.

@BeforeEach
public void before() {
    logger.info("@Before.begin");
    getService(ItemRegistry.class);
    ItemProvider itemProvider = new ItemProvider() {

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

        @Override
        public Collection<Item> getAll() {
            return Set.of(new SwitchItem("myMotionItem"), new SwitchItem("myPresenceItem"), new SwitchItem("myLampItem"), new SwitchItem("myMotionItem2"), new SwitchItem("myPresenceItem2"), new SwitchItem("myLampItem2"), new SwitchItem("myMotionItem11"), new SwitchItem("myLampItem11"), new SwitchItem("myMotionItem3"), new SwitchItem("templ_MotionItem"), new SwitchItem("templ_LampItem"));
        }

        @Override
        public void removeProviderChangeListener(ProviderChangeListener<Item> listener) {
        }
    };
    registerService(itemProvider);
    registerVolatileStorageService();
    EventSubscriber ruleEventHandler = new EventSubscriber() {

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

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

        @Override
        public void receive(Event e) {
            logger.info("RuleEvent: {} --> {}", e.getTopic(), e.getPayload());
            if (e.getPayload().contains("RUNNING")) {
                ruleEvent = e;
            }
        }
    };
    registerService(ruleEventHandler);
    StorageService storageService = getService(StorageService.class);
    managedRuleProvider = getService(ManagedRuleProvider.class);
    eventPublisher = getService(EventPublisher.class);
    itemRegistry = getService(ItemRegistry.class);
    ruleRegistry = getService(RuleRegistry.class);
    ruleManager = getService(RuleManager.class);
    moduleTypeRegistry = getService(ModuleTypeRegistry.class);
    waitForAssert(() -> {
        assertThat(storageService, is(notNullValue()));
        // sometimes assert fails because EventPublisher service is null
        assertThat(eventPublisher, is(notNullValue()));
        assertThat(itemRegistry, is(notNullValue()));
        assertThat(ruleRegistry, is(notNullValue()));
        assertThat(ruleManager, is(notNullValue()));
        assertThat(managedRuleProvider, is(notNullValue()));
        assertThat(moduleTypeRegistry, is(notNullValue()));
    }, 9000, 1000);
    // start rule engine
    RuleEngineImpl ruleEngine = (RuleEngineImpl) ruleManager;
    ruleEngine.onReadyMarkerAdded(new ReadyMarker("", ""));
    waitForAssert(() -> assertTrue(ruleEngine.isStarted()));
    logger.info("@Before.finish");
}
Also used : ItemProvider(org.openhab.core.items.ItemProvider) EventSubscriber(org.openhab.core.events.EventSubscriber) EventPublisher(org.openhab.core.events.EventPublisher) ModuleTypeRegistry(org.openhab.core.automation.type.ModuleTypeRegistry) RuleEngineImpl(org.openhab.core.automation.internal.RuleEngineImpl) RuleRegistry(org.openhab.core.automation.RuleRegistry) ManagedRuleProvider(org.openhab.core.automation.ManagedRuleProvider) ItemRegistry(org.openhab.core.items.ItemRegistry) VolatileStorageService(org.openhab.core.test.storage.VolatileStorageService) StorageService(org.openhab.core.storage.StorageService) SwitchItem(org.openhab.core.library.items.SwitchItem) Item(org.openhab.core.items.Item) ProviderChangeListener(org.openhab.core.common.registry.ProviderChangeListener) RuleManager(org.openhab.core.automation.RuleManager) RuleStatusInfoEvent(org.openhab.core.automation.events.RuleStatusInfoEvent) ItemCommandEvent(org.openhab.core.items.events.ItemCommandEvent) Event(org.openhab.core.events.Event) ReadyMarker(org.openhab.core.service.ReadyMarker) SwitchItem(org.openhab.core.library.items.SwitchItem) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 2 with RuleRegistry

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

the class RunRuleModuleTest method sceneActivatedByRule.

@Test
public void sceneActivatedByRule() throws ItemNotFoundException, InterruptedException {
    final RuleRegistry ruleRegistry = getService(RuleRegistry.class);
    final RuleManager ruleEngine = getService(RuleManager.class);
    assertNotNull(ruleRegistry);
    // Scene rule
    final Rule sceneRule = createSceneRule();
    logger.info("SceneRule created: {}", sceneRule.getUID());
    ruleRegistry.add(sceneRule);
    ruleEngine.setEnabled(sceneRule.getUID(), true);
    waitForAssert(() -> {
        assertEquals(RuleStatus.IDLE, ruleEngine.getStatusInfo(sceneRule.getUID()).getStatus());
    });
    // Outer rule
    final Rule outerRule = createOuterRule();
    logger.info("SceneActivationRule created: {}", outerRule.getUID());
    ruleRegistry.add(outerRule);
    ruleEngine.setEnabled(outerRule.getUID(), true);
    waitForAssert(() -> {
        assertEquals(RuleStatus.IDLE, ruleEngine.getStatusInfo(outerRule.getUID()).getStatus());
    });
    // Test rule
    final EventPublisher eventPublisher = getService(EventPublisher.class);
    assertNotNull(eventPublisher);
    final ItemRegistry itemRegistry = getService(ItemRegistry.class);
    assertNotNull(itemRegistry);
    final Queue<Event> events = new LinkedList<>();
    subscribeToEvents(ItemCommandEvent.TYPE, events);
    // trigger rule by switching triggerItem ON
    eventPublisher.post(ItemEventFactory.createStateEvent("ruleTrigger", OnOffType.ON));
    waitForAssert(() -> {
        assertFalse(events.isEmpty());
        ItemCommandEvent event = (ItemCommandEvent) events.remove();
        assertEquals("openhab/items/switch3/command", event.getTopic());
        assertEquals(OnOffType.ON, event.getItemCommand());
    });
}
Also used : EventPublisher(org.openhab.core.events.EventPublisher) ItemCommandEvent(org.openhab.core.items.events.ItemCommandEvent) RuleRegistry(org.openhab.core.automation.RuleRegistry) RuleManager(org.openhab.core.automation.RuleManager) ItemCommandEvent(org.openhab.core.items.events.ItemCommandEvent) Event(org.openhab.core.events.Event) Rule(org.openhab.core.automation.Rule) ItemRegistry(org.openhab.core.items.ItemRegistry) LinkedList(java.util.LinkedList) Test(org.junit.jupiter.api.Test) JavaOSGiTest(org.openhab.core.test.java.JavaOSGiTest)

Example 3 with RuleRegistry

use of org.openhab.core.automation.RuleRegistry 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 4 with RuleRegistry

use of org.openhab.core.automation.RuleRegistry 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 5 with RuleRegistry

use of org.openhab.core.automation.RuleRegistry 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)

Aggregations

RuleRegistry (org.openhab.core.automation.RuleRegistry)13 RuleManager (org.openhab.core.automation.RuleManager)11 EventPublisher (org.openhab.core.events.EventPublisher)10 Rule (org.openhab.core.automation.Rule)8 Event (org.openhab.core.events.Event)8 ItemCommandEvent (org.openhab.core.items.events.ItemCommandEvent)8 JavaOSGiTest (org.openhab.core.test.java.JavaOSGiTest)8 BeforeEach (org.junit.jupiter.api.BeforeEach)7 Test (org.junit.jupiter.api.Test)7 SwitchItem (org.openhab.core.library.items.SwitchItem)7 RuleStatusInfoEvent (org.openhab.core.automation.events.RuleStatusInfoEvent)6 RuleEngineImpl (org.openhab.core.automation.internal.RuleEngineImpl)6 Configuration (org.openhab.core.config.core.Configuration)6 Item (org.openhab.core.items.Item)6 ItemProvider (org.openhab.core.items.ItemProvider)6 ItemRegistry (org.openhab.core.items.ItemRegistry)6 ReadyMarker (org.openhab.core.service.ReadyMarker)6 ProviderChangeListener (org.openhab.core.common.registry.ProviderChangeListener)5 Random (java.util.Random)4 Action (org.openhab.core.automation.Action)4