Search in sources :

Example 21 with Event

use of org.openhab.core.events.Event in project openhab-core by openhab.

the class AutomationIntegrationJsonTest method assertThatARuleFromJsonFileIsAddedAutomaticallyAndTheRuntimeRuleHasResolvedModuleReferences.

@Test
public void assertThatARuleFromJsonFileIsAddedAutomaticallyAndTheRuntimeRuleHasResolvedModuleReferences() {
    logger.info("assert that a rule from json file is added automatically and the runtime rule has resolved module references");
    // WAIT until Rule modules types are parsed and the rule becomes IDLE
    waitForAssert(() -> {
        assertThat(ruleRegistry.getAll().isEmpty(), is(false));
        Optional<Rule> rule2 = ruleRegistry.stream().filter(RulePredicates.hasAllTags("jsonTest", "references")).findFirst();
        assertThat(rule2.isPresent(), is(true));
        RuleStatusInfo ruleStatus2 = ruleManager.getStatusInfo(rule2.get().getUID());
        assertThat(ruleStatus2.getStatus(), is(RuleStatus.IDLE));
    }, 10000, 200);
    Optional<Rule> optionalRule = ruleRegistry.stream().filter(RulePredicates.hasAllTags("jsonTest", "references")).findFirst();
    assertThat(optionalRule.isPresent(), is(true));
    Rule rule = optionalRule.get();
    assertThat(rule.getName(), is("ItemSampleRuleWithReferences"));
    assertTrue(rule.getTags().contains("sample"));
    assertTrue(rule.getTags().contains("item"));
    assertTrue(rule.getTags().contains("rule"));
    assertTrue(rule.getTags().contains("references"));
    Optional<? extends Trigger> trigger = rule.getTriggers().stream().filter(t -> "ItemStateChangeTriggerID".equals(t.getId())).findFirst();
    assertThat(trigger.isPresent(), is(true));
    assertThat(trigger.get().getTypeUID(), is("core.GenericEventTrigger"));
    assertThat(trigger.get().getConfiguration().get("eventTopic"), is("openhab/items/*"));
    assertThat(trigger.get().getConfiguration().get("eventTypes"), is("ItemStateEvent"));
    Optional<? extends Action> action = rule.getActions().stream().filter(a -> "ItemPostCommandActionID".equals(a.getId())).findFirst();
    assertThat(action.isPresent(), is(true));
    assertThat(action.get().getTypeUID(), is("core.ItemCommandAction"));
    assertThat(action.get().getConfiguration().get("command"), is("ON"));
    RuleStatusInfo ruleStatus = ruleManager.getStatusInfo(rule.getUID());
    assertThat(ruleStatus.getStatus(), is(RuleStatus.IDLE));
    // run the rule to check if the runtime rule has resolved module references and is executed successfully
    EventPublisher eventPublisher = getService(EventPublisher.class);
    @NonNullByDefault 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("myLampItem")) {
                itemEvent = e;
            }
        }
    };
    registerService(itemEventHandler);
    eventPublisher.post(ItemEventFactory.createStateEvent("myMotionItem", OnOffType.ON));
    waitForAssert(() -> {
        assertThat(itemEvent, is(notNullValue()));
    }, 3000, 100);
    assertThat(itemEvent.getTopic(), is(equalTo("openhab/items/myLampItem/command")));
    assertThat(((ItemCommandEvent) itemEvent).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) TriggerType(org.openhab.core.automation.type.TriggerType) 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) RuleEngineImpl(org.openhab.core.automation.internal.RuleEngineImpl) Input(org.openhab.core.automation.type.Input) ManagedRuleProvider(org.openhab.core.automation.ManagedRuleProvider) StorageService(org.openhab.core.storage.StorageService) RulePredicates(org.openhab.core.automation.RulePredicates) Nullable(org.eclipse.jdt.annotation.Nullable) EventFilter(org.openhab.core.events.EventFilter) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) RuleStatusInfoEvent(org.openhab.core.automation.events.RuleStatusInfoEvent) EventPublisher(org.openhab.core.events.EventPublisher) 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) UnDefType(org.openhab.core.types.UnDefType) ItemNotFoundException(org.openhab.core.items.ItemNotFoundException) Set(java.util.Set) ConfigDescriptionParameter(org.openhab.core.config.core.ConfigDescriptionParameter) ReadyMarker(org.openhab.core.service.ReadyMarker) Rule(org.openhab.core.automation.Rule) Item(org.openhab.core.items.Item) Test(org.junit.jupiter.api.Test) ItemRegistry(org.openhab.core.items.ItemRegistry) RuleStatus(org.openhab.core.automation.RuleStatus) AfterEach(org.junit.jupiter.api.AfterEach) Output(org.openhab.core.automation.type.Output) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) ActionType(org.openhab.core.automation.type.ActionType) JavaOSGiTest(org.openhab.core.test.java.JavaOSGiTest) Optional(java.util.Optional) ProviderChangeListener(org.openhab.core.common.registry.ProviderChangeListener) ModuleTypeRegistry(org.openhab.core.automation.type.ModuleTypeRegistry) EventSubscriber(org.openhab.core.events.EventSubscriber) RuleStatusInfo(org.openhab.core.automation.RuleStatusInfo) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) EventPublisher(org.openhab.core.events.EventPublisher) RuleStatusInfoEvent(org.openhab.core.automation.events.RuleStatusInfoEvent) ItemCommandEvent(org.openhab.core.items.events.ItemCommandEvent) Event(org.openhab.core.events.Event) Rule(org.openhab.core.automation.Rule) Test(org.junit.jupiter.api.Test) JavaOSGiTest(org.openhab.core.test.java.JavaOSGiTest)

Example 22 with Event

use of org.openhab.core.events.Event 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 23 with Event

use of org.openhab.core.events.Event 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 24 with Event

use of org.openhab.core.events.Event in project openhab-core by openhab.

the class RunRuleModuleTest method subscribeToEvents.

private void subscribeToEvents(String eventType, final Queue<Event> events) {
    EventSubscriber eventSubscriber = new EventSubscriber() {

        @Override
        public void receive(final Event event) {
            logger.info("Event: {}", event.getTopic());
            events.add(event);
        }

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

        @Override
        @Nullable
        public EventFilter getEventFilter() {
            return null;
        }
    };
    ServiceReference<?> subscriberReference = registerService(eventSubscriber).getReference();
    assertNotNull(getServices(EventSubscriber.class, (reference) -> reference.equals(subscriberReference)));
}
Also used : ItemEventFactory(org.openhab.core.items.events.ItemEventFactory) VolatileStorageService(org.openhab.core.test.storage.VolatileStorageService) 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) RuleBuilder(org.openhab.core.automation.util.RuleBuilder) LoggerFactory(org.slf4j.LoggerFactory) OnOffType(org.openhab.core.library.types.OnOffType) Checks.requireNonNull(org.eclipse.jdt.annotation.Checks.requireNonNull) RuleEngineImpl(org.openhab.core.automation.internal.RuleEngineImpl) ArrayList(java.util.ArrayList) Nullable(org.eclipse.jdt.annotation.Nullable) Configuration(org.openhab.core.config.core.Configuration) Map(java.util.Map) ModuleBuilder(org.openhab.core.automation.util.ModuleBuilder) EventFilter(org.openhab.core.events.EventFilter) Map.entry(java.util.Map.entry) LinkedList(java.util.LinkedList) EventPublisher(org.openhab.core.events.EventPublisher) ServiceReference(org.osgi.framework.ServiceReference) ItemCommandEvent(org.openhab.core.items.events.ItemCommandEvent) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) Logger(org.slf4j.Logger) ItemProvider(org.openhab.core.items.ItemProvider) Collection(java.util.Collection) Event(org.openhab.core.events.Event) ItemNotFoundException(org.openhab.core.items.ItemNotFoundException) Set(java.util.Set) ReadyMarker(org.openhab.core.service.ReadyMarker) Rule(org.openhab.core.automation.Rule) Item(org.openhab.core.items.Item) Test(org.junit.jupiter.api.Test) ItemRegistry(org.openhab.core.items.ItemRegistry) RuleStatus(org.openhab.core.automation.RuleStatus) List(java.util.List) JavaOSGiTest(org.openhab.core.test.java.JavaOSGiTest) Assertions(org.junit.jupiter.api.Assertions) ProviderChangeListener(org.openhab.core.common.registry.ProviderChangeListener) Queue(java.util.Queue) EventSubscriber(org.openhab.core.events.EventSubscriber) ItemCommandEvent(org.openhab.core.items.events.ItemCommandEvent) Event(org.openhab.core.events.Event)

Example 25 with Event

use of org.openhab.core.events.Event 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)

Aggregations

Event (org.openhab.core.events.Event)120 Test (org.junit.jupiter.api.Test)93 JavaOSGiTest (org.openhab.core.test.java.JavaOSGiTest)58 EventSubscriber (org.openhab.core.events.EventSubscriber)46 ItemCommandEvent (org.openhab.core.items.events.ItemCommandEvent)38 Nullable (org.eclipse.jdt.annotation.Nullable)28 SwitchItem (org.openhab.core.library.items.SwitchItem)28 EventPublisher (org.openhab.core.events.EventPublisher)27 NonNullByDefault (org.eclipse.jdt.annotation.NonNullByDefault)25 BeforeEach (org.junit.jupiter.api.BeforeEach)22 Item (org.openhab.core.items.Item)22 Set (java.util.Set)21 Rule (org.openhab.core.automation.Rule)20 RuleStatusInfoEvent (org.openhab.core.automation.events.RuleStatusInfoEvent)20 EventFilter (org.openhab.core.events.EventFilter)20 NumberItem (org.openhab.core.library.items.NumberItem)18 LinkedList (java.util.LinkedList)17 List (java.util.List)17 ArrayList (java.util.ArrayList)16 Configuration (org.openhab.core.config.core.Configuration)16