100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Improved presence detection with motion counter demo rule
Christian Bauer7fefe10672ab
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.javaindex 1d5e11f30..b207740b4 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java@@ -34,7 +34,6 @@ import org.kie.api.builder.model.KieModuleModel;import org.kie.api.builder.model.KieSessionModel;import org.kie.api.conf.EqualityBehaviorOption;import org.kie.api.conf.EventProcessingOption;-import org.kie.api.event.process.*;import org.kie.api.event.rule.ObjectDeletedEvent;import org.kie.api.event.rule.ObjectInsertedEvent;import org.kie.api.event.rule.ObjectUpdatedEvent;@@ -98,6 +97,9 @@ public class RulesEngine<T extends Ruleset> {protected Future runningFuture;protected Throwable error;final protected Map<AssetState, FactHandle> assetStates = new HashMap<>();+ // This consumer is useful in testing, as we can't have a reliable event fact+ // count from Drools session (events are expired automatically))+ protected Consumer<AssetEvent> assetEventsConsumer;protected ScheduledFuture startTimer;public RulesEngine(TimerService timerService,@@ -158,6 +160,10 @@ public class RulesEngine<T extends Ruleset> {return rulesets.isEmpty();}+ public void setAssetEventsConsumer(Consumer<AssetEvent> assetEventsConsumer) {+ this.assetEventsConsumer = assetEventsConsumer;+ }+protected void setGlobal(String identifier, Object object) {try {knowledgeSession.setGlobal(identifier, object);@@ -515,6 +521,9 @@ public class RulesEngine<T extends Ruleset> {if (factHandle != null) {scheduleExpiration(assetEvent, factHandle, expirationOffset);}+ if (assetEventsConsumer != null) {+ assetEventsConsumer.accept(assetEvent);+ }}protected synchronized FactHandle insertIntoSession(AbstractAssetUpdate update) {@@ -597,21 +606,24 @@ public class RulesEngine<T extends Ruleset> {@Overridepublic void dispatch(AttributeEvent... events) {- if (events != null) {- for (AttributeEvent event : events) {- // Set event time to current container timer- event.timestamp = timerService.getCurrentTimeMillis();- // Check if the asset ID of the event can be found in the original query- AssetQuery checkQuery = query();- checkQuery.id = event.getEntityId();- if (assetStorageService.find(checkQuery) == null) {- throw new IllegalArgumentException(- "Access to asset not allowed for this rule engine scope: " + event- );- }- LOG.fine("Dispatching on " + RulesEngine.this + ": " + event);- assetProcessingService.sendAttributeEvent(event);+ if (events == null)+ return;+ for (AttributeEvent event : events) {++ // Set event source time to current container time+ event.timestamp = timerService.getCurrentTimeMillis();++ // Check if the asset ID of the event can be found in the original query+ AssetQuery checkQuery = query();+ checkQuery.id = event.getEntityId();+ if (assetStorageService.find(checkQuery) == null) {+ throw new IllegalArgumentException(+ "Access to asset not allowed for this rule engine scope: " + event+ );}++ LOG.fine("Dispatching on " + RulesEngine.this + ": " + event);+ assetProcessingService.sendAttributeEvent(event);}}};diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.javaindex 5cfc90917..7161ae3f3 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java@@ -55,7 +55,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {// Update these numbers whenever you change a RULE_STATE flag in test datapublic static final int DEMO_RULE_STATES_APARTMENT_1 = 8;- public static final int DEMO_RULE_STATES_APARTMENT_2 = 3;+ public static final int DEMO_RULE_STATES_APARTMENT_2 = 4;public static final int DEMO_RULE_STATES_APARTMENT_3 = 2;public static final int DEMO_RULE_STATES_SMART_HOME = DEMO_RULE_STATES_APARTMENT_1 + DEMO_RULE_STATES_APARTMENT_2 + DEMO_RULE_STATES_APARTMENT_3;public static final int DEMO_RULE_STATES_CUSTOMER_A = DEMO_RULE_STATES_SMART_HOME;@@ -549,6 +549,8 @@ public class ManagerDemoSetup extends AbstractManagerSetup {new MetaItem(AssetMeta.DESCRIPTION, Json.create("Sensor that increments a counter when motion is sensed"))+ ).add(+ new MetaItem(AssetMeta.RULE_STATE, Json.create(true))).add(new MetaItem(AssetMeta.RULE_EVENT, Json.create(true)))diff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drlindex e100a3c86..42699ebdc 100644--- a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl@@ -1,5 +1,6 @@package org.openremote.test.rules;+import java.util.ArrayList;import org.openremote.model.*;import org.openremote.model.asset.*import elemental.json.Json;@@ -13,40 +14,64 @@ of a ROOM when a motion counter is incremented several times within a time windoremoved if the motion counter has not been incremented within a time window. All time windows andthe number of matches required can be configured.*/-/* TODO This needs more work-rule "Set presence detected timestamp if motion counter is incremented in time window"+rule "Set presence detected flag if motion counter is incremented in time window"when- // The motion counter in a room is incremented more than 2 times in the last 15 minutes- $roomEvent : AssetEvent(type == AssetType.ROOM, attributeName == "motionCounter", $orgMC: value.asNumber > 0)+ // A room has a motion counter+ $room : AssetState(type == AssetType.ROOM, attributeName == "motionCounter")+ // And the presence detected flag is not set already+ AssetState(id == $room.id, attributeName == "presenceDetected", !value.asBoolean)+ // And at least 5 motion counter increments have been received in the last 10 minutes+ accumulate(+ AssetEvent(id == $room.id, attributeName == "motionCounter", value.asNumber > 0) over window:time(10m);+ $count: count(1);+ $count >= 5+ )+then+ // Set the presence detected flag of the room+ assets.dispatch(+ new AttributeEvent($room.getId(), "presenceDetected", Json.create(true))+ );+end++rule "Update the presence detected timestamp if motion counter is incremented and we have already detected presence"+when+ // A room has a motion counter+ $room : AssetState(type == AssetType.ROOM, attributeName == "motionCounter")+ // And the presence detected flag is set+ AssetState(id == $room.id, attributeName == "presenceDetected", value.asBoolean)+ // And at least 5 motion counter increments have been received in the last 10 minutesaccumulate(- AssetEvent(id == $roomEvent.id, attributeName == "motionCounter", $newMC: value.asNumber > 0) over window:time(15m);+ AssetEvent(id == $room.id, attributeName == "motionCounter", value.asNumber > 0, $ts: valueTimestamp) over window:time(10m);$count: count(1),- $maxMC: max($newMC);- $maxMC > $orgMC, $count > 2+ $latestIncrementTimestamp: max($ts);+ $count >= 5)- // And the presence detected flag is not set already- AssetState(id == $roomEvent.getId(), attributeName == "presenceDetected", !value.asBoolean)+ // And the latest counter increment event is newer than the recorded last presence detected time+ AssetState(id == $room.id, attributeName == "lastPresenceDetected", $latestIncrementTimestamp > value.asNumber)then- // Set the presence detected flag and last presence detected timestamp of the room- long currentTime = drools.getWorkingMemory().getSessionClock().getCurrentTime();+ // Update the last presence detected timestamp to the latest counter increment eventassets.dispatch(- new AttributeEvent($roomEvent.getId(), "presenceDetected", Json.create(true)),- new AttributeEvent($roomEvent.getId(), "lastPresenceDetected", Json .create(currentTime))+ new AttributeEvent($room.getId(), "lastPresenceDetected", Json.create($latestIncrementTimestamp)));end+rule "Clear presence detected timestamp if motion counter was not incremented in a while"when- // The motion counter in a room as not been incremented in the last 15 minutes- $roomEvent : AssetEvent(type == AssetType.ROOM, attributeName == "motionCounter", $orgMC: value.asNumber() > 0)- not(AssetEvent(id == $roomEvent.id, attributeName == "motionCounter", value.asNumber > $orgMC, this != $roomEvent, this after[0s,15m] $roomEvent ))+ // A room has a motion counter+ $room: AssetState(type == AssetType.ROOM, attributeName == "motionCounter")// And the presence detected flag is set- AssetState(id == $roomEvent.getId(), attributeName == "presenceDetected", value.asBoolean)+ AssetState(id == $room.id, attributeName == "presenceDetected", value.asBoolean)+ // And no motion counter increments have been received in the last 10 minutes+ accumulate(+ AssetEvent(id == $room.id, attributeName == "motionCounter", value.asNumber > 0) over window:time(10m);+ $count: count(1);+ $count == 0+ )then// Clear the presence detected flag of the roomassets.dispatch(- new AttributeEvent($roomEvent.getId(), "presenceDetected", Json .create(false))+ new AttributeEvent($room.getId(), "presenceDetected", Json.create(false)));end-*/\ No newline at end of filediff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drlindex 676a64c16..23817c5db 100644--- a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drl+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drl@@ -19,14 +19,14 @@ rule "Set presence detected flag if motion sensor is triggered in time window"when// A room has a motion sensor$room : AssetState(type == AssetType.ROOM, attributeName == "motionSensor")+ // And the presence detected flag is not set already+ AssetState(id == $room.id, attributeName == "presenceDetected", !value.asBoolean)// And at least 5 motion sensor triggers have been received in the last 10 minutesaccumulate(AssetEvent(id == $room.id, attributeName == "motionSensor", value.asBoolean) over window:time(10m);$count: count(1);$count >= 5)- // And the presence detected flag is not set already- AssetState(id == $room.id, attributeName == "presenceDetected", !value.asBoolean)then// Set the presence detected flag of the roomassets.dispatch(@@ -39,11 +39,11 @@ when// The presence detected flag is set in a room$room: AssetState(type == AssetType.ROOM, attributeName == "presenceDetected", value.asBoolean)// And the motion sensor is triggered- $sensor: AssetState(id == $room.id, attributeName == "motionSensor", value.asBoolean)+ $sensorState: AssetState(id == $room.id, attributeName == "motionSensor", value.asBoolean)then// Update the last presence detected timestamp of the roomassets.dispatch(- new AttributeEvent($room.getId(), "lastPresenceDetected", Json.create($sensor.getValueTimestamp()))+ new AttributeEvent($room.getId(), "lastPresenceDetected", Json.create($sensorState.getValueTimestamp())));enddiff --git a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentPresenceDetectionTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentPresenceDetectionTest.groovyindex 9f3a6259c..a04cd8d7f 100644--- a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentPresenceDetectionTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentPresenceDetectionTest.groovy@@ -7,29 +7,23 @@ import org.openremote.manager.server.asset.AssetStorageServiceimport org.openremote.manager.server.rules.RulesEngineimport org.openremote.manager.server.rules.RulesServiceimport org.openremote.manager.server.setup.SetupService-import org.openremote.manager.server.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.server.setup.builtin.ManagerDemoSetupimport org.openremote.model.AttributeEvent-import org.openremote.model.asset.AssetState+import org.openremote.model.asset.AssetEventimport org.openremote.test.ManagerContainerTrait-import spock.lang.Ignoreimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions-import java.util.function.Consumer--import static java.util.concurrent.TimeUnit.HOURS-import static java.util.concurrent.TimeUnit.MINUTES-import static java.util.concurrent.TimeUnit.SECONDS+import static java.util.concurrent.TimeUnit.*import static org.openremote.manager.server.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_APARTMENT_1-import static org.openremote.manager.server.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_CUSTOMER_A+import static org.openremote.manager.server.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_APARTMENT_2class ApartmentPresenceDetectionTest extends Specification implements ManagerContainerTrait {- def "Set and clear presence detection timestamp depending on motion sensor"() {+ def "Detect presence with motion sensor"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 5, delay: 0.2)+ def conditions = new PollingConditions(timeout: 10, delay: 1)def serverPort = findEphemeralPort()def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)@@ -38,14 +32,6 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCondef assetStorageService = container.getService(AssetStorageService.class)RulesEngine apartment1Engine = null- and: "a mock attribute event consumer"- List<AssetState> updatesCompletedProcessing = []- Consumer<AssetState> assetProcessingCompleteConsumer = { assetUpdate ->- updatesCompletedProcessing.add(assetUpdate)- }- assetProcessingService.processors.add(assetProcessingCompleteConsumer)--expect: "the rule engines to become available and be running"conditions.eventually {apartment1Engine = rulesService.assetDeployments.get(managerDemoSetup.apartment1Id)@@ -59,8 +45,14 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerConassert !livingRoomAsset.getAttribute("presenceDetected").get().valueAsBooleanassert livingRoomAsset.getAttribute("lastPresenceDetected").get().value.getType() == JsonType.NULL- when: "several motion sensor events are triggered in the room, but not enough for presence detection"- updatesCompletedProcessing = []+ when: "we have an events consumer for collecting test data"+ List<AssetEvent> insertedAssetEvents = []+ apartment1Engine.assetEventsConsumer = { assetEvent->+ insertedAssetEvents << assetEvent+ }++ and: "several motion sensor events are triggered in the room, but not enough for presence detection"+ insertedAssetEvents = []setPseudoClocksToRealTime(container, apartment1Engine)// Send 5 triggers each 3 minutes apartfor (i in 1..5) {@@ -68,14 +60,14 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerConmanagerDemoSetup.apartment1LivingroomId, "motionSensor", Json.create(true), getClockTimeOf(apartment1Engine))assetProcessingService.sendAttributeEvent(motionSensorTrigger)- conditions.eventually {- assert updatesCompletedProcessing.findAll { it.attributeName == "motionSensor" }.size() == i+ new PollingConditions(timeout: 3, initialDelay: 0.2, delay: 0.2).eventually {+ assert insertedAssetEvents.any() { it.matches(motionSensorTrigger) }}advancePseudoClocks(3, MINUTES, container, apartment1Engine)}then: "presence should not be detected"- new PollingConditions(initialDelay: 5).eventually {+ new PollingConditions(initialDelay: 3).eventually {def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)assert !asset.getAttribute("presenceDetected").get().valueAsBooleanassert asset.getAttribute("lastPresenceDetected").get().value.getType() == JsonType.NULL@@ -90,7 +82,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon}when: "several motion sensor events are triggered in the room, fast enough for presence detection"- updatesCompletedProcessing = []+ insertedAssetEvents = []double expectedLastPresenceTimestamp = 0// Send 5 triggers each 1 minute apartfor (i in 1..5) {@@ -99,8 +91,8 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon)expectedLastPresenceTimestamp = motionSensorTrigger.timestampassetProcessingService.sendAttributeEvent(motionSensorTrigger)- conditions.eventually {- assert updatesCompletedProcessing.findAll { it.attributeName == "motionSensor" }.size() == i+ new PollingConditions(timeout: 3, initialDelay: 0.2, delay: 0.2).eventually {+ assert insertedAssetEvents.any() { it.matches(motionSensorTrigger) }}advancePseudoClocks(1, MINUTES, container, apartment1Engine)}@@ -113,7 +105,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon}when: "time moves on and we keep triggering the motion sensor in short intervals "- updatesCompletedProcessing = []+ insertedAssetEvents = []// Send 20 triggers each 90 seconds apartfor (i in 1..20) {def motionSensorTrigger = new AttributeEvent(@@ -121,10 +113,10 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon)expectedLastPresenceTimestamp = motionSensorTrigger.timestampassetProcessingService.sendAttributeEvent(motionSensorTrigger)- conditions.eventually {- assert updatesCompletedProcessing.findAll { it.attributeName == "motionSensor" }.size() == i+ new PollingConditions(timeout: 3, initialDelay: 0.2, delay: 0.2).eventually {+ assert insertedAssetEvents.any() { it.matches(motionSensorTrigger) }}- advancePseudoClocks(10, SECONDS, container, apartment1Engine)+ advancePseudoClocks(90, SECONDS, container, apartment1Engine)}then: "presence should still be detected and the timestamp updated"@@ -156,90 +148,128 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerConstopContainer(container)}- // TODO This needs more work- @Ignore- def "Set and clear presence detection timestamp depending on motion counter"() {+ def "Detect presence with motion counter"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 5, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 1)def serverPort = findEphemeralPort()def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)- def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)def rulesService = container.getService(RulesService.class)def assetProcessingService = container.getService(AssetProcessingService.class)def assetStorageService = container.getService(AssetStorageService.class)- RulesEngine customerAEngine = null+ RulesEngine apartment2Engine = nullexpect: "the rule engines to become available and be running"conditions.eventually {- customerAEngine = rulesService.tenantDeployments.get(keycloakDemoSetup.customerATenant.id)- assert customerAEngine != null- assert customerAEngine.isRunning()- assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A+ apartment2Engine = rulesService.assetDeployments.get(managerDemoSetup.apartment2Id)+ assert apartment2Engine != null+ assert apartment2Engine.isRunning()+ assert apartment2Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_2}- and: "the presence detected timestamp of the room should not be set"- def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)- assert livingRoomAsset.getAttribute("presenceDetected").get().value.getType() == JsonType.NULL+ and: "the presence detected flag and timestamp of the room should not be set"+ def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)+ assert !livingRoomAsset.getAttribute("presenceDetected").get().valueAsBoolean+ assert livingRoomAsset.getAttribute("lastPresenceDetected").get().value.getType() == JsonType.NULL- and: "the presence detected timestamp of the other room should not be set"- def otherLivingRoomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)- assert otherLivingRoomAsset.getAttribute("presenceDetected").get().value.getType() == JsonType.NULL+ when: "we have an events consumer for collecting test data"+ List<AssetEvent> insertedAssetEvents = []+ apartment2Engine.assetEventsConsumer = { assetEvent->+ insertedAssetEvents << assetEvent+ }- when: "the motion counter sensor of the room is incremented"- double expectedPresenceTimestampStart = getClockTimeOf(customerAEngine)- for (i in 0..2) {+ and: "several motion counter increments occur in the room, but not enough for presence detection"+ insertedAssetEvents = []+ setPseudoClocksToRealTime(container, apartment2Engine)+ // Send 5 triggers each 3 minutes apart+ for (i in 1..5) {def motionCounterIncrement = new AttributeEvent(- managerDemoSetup.apartment1LivingroomId, "motionCounter", Json.create(i + 1)+ managerDemoSetup.apartment2LivingroomId, "motionCounter", Json.create(i), getClockTimeOf(apartment2Engine))assetProcessingService.sendAttributeEvent(motionCounterIncrement)- conditions.eventually {- // Wait until we have the facts- assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A + 1 + i+ new PollingConditions(timeout: 3, initialDelay: 0.2, delay: 0.2).eventually {+ assert insertedAssetEvents.any() { it.matches(motionCounterIncrement) }}- withClockOf(customerAEngine) { it.advanceTime(2, MINUTES) }+ advancePseudoClocks(3, MINUTES, container, apartment2Engine)}- double expectedPresenceTimestampEnd = getClockTimeOf(customerAEngine)- then: "the presence detected timestamp of the room should be set"- conditions.eventually {+ then: "presence should not be detected"+ new PollingConditions(initialDelay: 3).eventually {def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)- def presenceDetectedTimestamp = asset.getAttribute("presenceDetected").get().value.asNumber()- assert presenceDetectedTimestamp > expectedPresenceTimestampStart && presenceDetectedTimestamp < expectedPresenceTimestampEnd+ assert !asset.getAttribute("presenceDetected").get().valueAsBoolean+ assert asset.getAttribute("lastPresenceDetected").get().value.getType() == JsonType.NULL+ }++ when: "time is advanced enough for event expiration"+ advancePseudoClocks(2, HOURS, container, apartment2Engine)++ then: "the events should have been expired and retracted automatically from the knowledge session"+ conditions.eventually {+ assert apartment2Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_2+ }++ when: "several motion counter increments occur in the room, fast enough for presence detection"+ insertedAssetEvents = []+ double expectedLastPresenceTimestamp = 0+ // Send 5 increments each 1 minute apart+ for (i in 1..5) {+ def motionCounterIncrement = new AttributeEvent(+ managerDemoSetup.apartment2LivingroomId, "motionCounter", Json.create(i), getClockTimeOf(apartment2Engine)+ )+ expectedLastPresenceTimestamp = motionCounterIncrement.timestamp+ assetProcessingService.sendAttributeEvent(motionCounterIncrement)+ new PollingConditions(timeout: 3, initialDelay: 0.2, delay: 0.2).eventually {+ assert insertedAssetEvents.any() { it.matches(motionCounterIncrement) }+ }+ advancePseudoClocks(1, MINUTES, container, apartment2Engine)+ }++ then: "presence should be detected"+ conditions.eventually {+ def asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)+ assert asset.getAttribute("presenceDetected").get().valueAsBoolean+ assert asset.getAttribute("lastPresenceDetected").get().value.asNumber() == expectedLastPresenceTimestamp}- when: "the motion counter sensor in the other room is incremented (but not enough to trigger 'detection')"- for (i in 0..2) {+ when: "time moves on and we keep incrementing the motion counter in short intervals "+ insertedAssetEvents = []+ // Send 20 increments each 90 seconds apart+ for (i in 1..20) {def motionCounterIncrement = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "motionCounter", Json.create(i + 1)+ managerDemoSetup.apartment2LivingroomId, "motionCounter", Json.create(i), getClockTimeOf(apartment2Engine))+ expectedLastPresenceTimestamp = motionCounterIncrement.timestampassetProcessingService.sendAttributeEvent(motionCounterIncrement)- conditions.eventually {- // Wait until we have the facts- assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A + 4 + i+ new PollingConditions(timeout: 3, initialDelay: 0.2, delay: 0.2).eventually {+ assert insertedAssetEvents.any() { it.matches(motionCounterIncrement) }}- withClockOf(customerAEngine) { it.advanceTime(10, MINUTES) }+ advancePseudoClocks(90, SECONDS, container, apartment2Engine)}- then: "the presence detected timestamp of the other room should NOT be set"+ then: "presence should still be detected and the timestamp updated"conditions.eventually {def asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)- assert asset.getAttribute("presenceDetected").get().value.getType() == JsonType.NULL+ assert asset.getAttribute("presenceDetected").get().valueAsBoolean+ assert asset.getAttribute("lastPresenceDetected").get().value.asNumber() == expectedLastPresenceTimestamp}- and: "meanwhile presence detected timestamp of the first room should have been cleared"+ when: "time moves on without the motion sensor being triggered"+ advancePseudoClocks(20, MINUTES, container, apartment2Engine)++ then: "presence should be gone but the last timestamp still available"conditions.eventually {- def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)- assert asset.getAttribute("presenceDetected").get().value.getType() == JsonType.NULL+ def asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)+ assert !asset.getAttribute("presenceDetected").get().valueAsBoolean+ assert asset.getAttribute("lastPresenceDetected").get().value.asNumber() == expectedLastPresenceTimestamp}- when: "time is advanced enough to trigger event expiration"- withClockOf(customerAEngine) { it.advanceTime(1, HOURS) }+ when: "time is advanced enough for event expiration"+ advancePseudoClocks(2, HOURS, container, apartment2Engine)then: "the events should have been expired and retracted automatically from the knowledge session"conditions.eventually {- assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A+ assert apartment2Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_2}cleanup: "the server should be stopped"diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.javaindex 4856589d2..0b94310a9 100644--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java@@ -246,6 +246,12 @@ public abstract class AbstractAssetUpdate {return attribute.getReference();}+ public boolean matches(AttributeEvent event) {+ return event.getAttributeRef().equals(getAttributeRef())+ && JsonUtil.equals(getValue(), event.getAttributeState().getValue())+ && getValueTimestamp() == event.getTimestamp();+ }+/*** This is here because {@link #attribute} is not always publicly accessible*/