Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Work on presence detection rules

Christian Bauer2805ec012948
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.java
index 9002831b5..f8dcef093 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
@@ -558,6 +558,13 @@ public class RulesEngine<T extends Ruleset> {
}
FactHandle fh = knowledgeSession.insert(update);
LOG.fine("On " + this + ", fact count after insert: " + knowledgeSession.getFactCount());
+ /* TODO Not synchronous with actual session state due to active mode, and a bit too much output?
+ if (LOG.isLoggable(Level.FINEST)) {
+ for (FactHandle factHandle : knowledgeSession.getFactHandles()) {
+ LOG.fine("Fact: " + knowledgeSession.getObject(factHandle));
+ }
+ }
+ */
return fh;
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractManagerSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractManagerSetup.java
index 3f37115df..15974fa26 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractManagerSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractManagerSetup.java
@@ -122,25 +122,35 @@ public abstract class AbstractManagerSetup implements Setup {
new MetaItem(READ_ONLY, Values.create(true)),
new MetaItem(RULE_STATE, Values.create(true)),
new MetaItem(RULE_EVENT, Values.create(true)),
+ new MetaItem(RULE_EVENT_EXPIRES, Values.create("1h")),
new MetaItem(STORE_DATA_POINTS, Values.create(true))
).addMeta(shouldBeLinked ? agentLinker.get() : null),
- new AssetAttribute("presenceDetected", AttributeType.BOOLEAN)
+ new AssetAttribute("motionDetected", AttributeType.BOOLEAN)
.setMeta(
- new MetaItem(LABEL, Values.create("Presence Detected")),
- new MetaItem(DESCRIPTION, Values.create("Someone is currently present in the room")),
+ new MetaItem(LABEL, Values.create("Motion Detected")),
+ new MetaItem(DESCRIPTION, Values.create("Someone is moving around in the room")),
new MetaItem(RULE_STATE, Values.create(true)),
new MetaItem(PROTECTED, Values.create(true)),
new MetaItem(READ_ONLY, Values.create(true)),
new MetaItem(SHOW_ON_DASHBOARD, Values.create(true))
),
- new AssetAttribute("lastPresenceDetected", TIMESTAMP_MILLIS)
+ new AssetAttribute("lastMotionDetected", TIMESTAMP_MILLIS)
.setMeta(
- new MetaItem(LABEL, Values.create("Last Presence")),
+ new MetaItem(LABEL, Values.create("Last time someone moved in the room")),
new MetaItem(RULE_STATE, Values.create(true)),
new MetaItem(PROTECTED, Values.create(true)),
new MetaItem(READ_ONLY, Values.create(true))
+ ),
+ new AssetAttribute("presenceDetected", AttributeType.BOOLEAN)
+ .setMeta(
+ new MetaItem(LABEL, Values.create("Presence Detected")),
+ new MetaItem(DESCRIPTION, Values.create("Someone is present in the room")),
+ new MetaItem(RULE_STATE, Values.create(true)),
+ new MetaItem(PROTECTED, Values.create(true)),
+ new MetaItem(READ_ONLY, Values.create(true)),
+ new MetaItem(SHOW_ON_DASHBOARD, Values.create(true))
)
- );
+ );
}
protected void addDemoApartmentRoomCO2Sensor(ServerAsset room, boolean shouldBeLinked, Supplier<MetaItem[]> agentLinker) {
@@ -149,6 +159,8 @@ public abstract class AbstractManagerSetup implements Setup {
.setMeta(
new MetaItem(LABEL, Values.create("CO2 Level")),
new MetaItem(RULE_STATE, Values.create(true)),
+ new MetaItem(RULE_EVENT, Values.create(true)),
+ new MetaItem(RULE_EVENT_EXPIRES, Values.create("16m")),
new MetaItem(PROTECTED, Values.create(true)),
new MetaItem(READ_ONLY, Values.create(true)),
new MetaItem(STORE_DATA_POINTS, Values.create(true)),
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.java
index a1535cdd5..eb796bd11 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
@@ -53,7 +53,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
final protected boolean importDemoScenes;
// Update these numbers whenever you change a RULE_STATE flag in test data
- public static final int DEMO_RULE_STATES_APARTMENT_1 = 11;
+ public static final int DEMO_RULE_STATES_APARTMENT_1 = 12;
public static final int DEMO_RULE_STATES_APARTMENT_2 = 9;
public static final int DEMO_RULE_STATES_APARTMENT_3 = 0;
public static final int DEMO_RULE_STATES_SMART_HOME = DEMO_RULE_STATES_APARTMENT_1 + DEMO_RULE_STATES_APARTMENT_2 + DEMO_RULE_STATES_APARTMENT_3;
diff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl
index 6fd2a524d..1f474e152 100644
--- a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl
+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl
@@ -10,65 +10,99 @@ global java.util.logging.Logger LOG;
global org.openremote.model.rules.Assets assets;
/*
-Calculate and set the "presenceDetected" flag and the "lastPresenceDetected" timestamp attributes
-of a ROOM when a motion counter is incremented several times within a time window. The flag will be
-removed if the motion counter has not been incremented within a time window. All time windows and
-the number of matches required can be configured.
+Uses 'motionCount' and optional 'co2Level' of a room asset to set the 'motionDetected',
+'lastMotionDetected', and 'presenceDetected' attributes of the room. Motion detection
+is based on multiple increments of the motion counter over a time window. Presence
+detection is based on motion detection, and increasing CO2 level over a time window.
*/
-rule "Set presence detected flag if motion counter is incremented in time window"
+rule "Set motion detected flag of room when motion counter increments"
when
- // A room has a motion counter
- $room : AssetState(type == AssetType.ROOM, attributeName == "motionCount")
- // And the presence detected flag is not set already
- AssetState(id == $room.id, attributeName == "presenceDetected", valueAsBoolean != true)
- // And at least 5 motion counter increments have been received in the last 10 minutes
+ // A room were the motion detected flag is not set
+ $room: AssetState(type == AssetType.ROOM, attributeName == "motionDetected", valueFalse)
+ // And the motion counter incremented at least 3 times in the last 2 minutes
accumulate(
- AssetEvent(id == $room.id, attributeName == "motionCount", valueAsNumber > 0) over window:time(10m);
- $count: count(1);
- $count >= 5
+ AssetEvent(id == $room.id, attributeName == "motionCount", valueGreaterThanOldValue) over window:time(2m);
+ $motionIncrements: count(1);
+ $motionIncrements >= 3
)
then
- // Set the presence detected flag of the room
+ // Set the motion detected flag of the room
assets.dispatch(
- new AttributeEvent($room.getId(), "presenceDetected", Values.create(true))
+ new AttributeEvent($room.getId(), "motionDetected", Values.create(true))
+ );
+end
+
+
+rule "Update the motion detected timestamp when motion counter increments"
+when
+ // A room were the motion detected flag is set
+ $room : AssetState(type == AssetType.ROOM, attributeName == "motionDetected", valueTrue)
+ // And the motion counter increments
+ AssetState(id == $room.id, attributeName == "motionCount", valueGreaterThanOldValue, $lastIncrementTimestamp: valueTimestamp)
+ // And the last counter increment event is newer than\ the recorded last detected time
+ AssetState(id == $room.id, attributeName == "lastMotionDetected", isValueLessThan($lastIncrementTimestamp))
+then
+ // Update the last presence detected timestamp to the latest counter increment event
+ assets.dispatch(
+ new AttributeEvent($room.getId(), "lastMotionDetected", Values.create($lastIncrementTimestamp))
);
end
-rule "Update the presence detected timestamp if motion counter is incremented and we have already detected presence"
+
+rule "Clear motion detected flag of a room if the motion counter doesn't increment"
when
- // A room has a motion counter
- $room : AssetState(type == AssetType.ROOM, attributeName == "motionCount")
- // And the presence detected flag is set
- AssetState(id == $room.id, attributeName == "presenceDetected", valueAsBoolean == true)
- // And at least 5 motion counter increments have been received in the last 10 minutes
+ // A room were the motion detected flag is set
+ $room: AssetState(type == AssetType.ROOM, attributeName == "motionDetected", valueTrue)
+ // And the room has a motion counter
+ AssetState(id == $room.id, attributeName == "motionCount")
+ // And the motion counter was not incremented in the last 15 minutes
accumulate(
- AssetEvent(id == $room.id, attributeName == "motionCount", valueAsNumber > 0, $ts: valueTimestamp) over window:time(10m);
- $count: count(1),
- $latestIncrementTimestamp: max($ts);
- $count >= 5
+ AssetEvent(id == $room.id, attributeName == "motionCount", valueGreaterThanOldValue) over window:time(15m);
+ $countMotion: count(1);
+ $countMotion == 0
)
- // And the latest counter increment event is newer than the recorded last presence detected time
- AssetState(id == $room.id, attributeName == "lastPresenceDetected", valueAsNumber == null || $latestIncrementTimestamp > valueAsNumber)
then
- // Update the last presence detected timestamp to the latest counter increment event
+ // Clear the motion detected flag of the room
assets.dispatch(
- new AttributeEvent($room.getId(), "lastPresenceDetected", Values.create($latestIncrementTimestamp))
+ new AttributeEvent($room.getId(), "motionDetected", Values.create(false))
+ );
+end
+
+
+rule "Set presence detected flag of room when motion is detected and confirmed with CO2 level rising"
+when
+ // A room were the presence detected flag is not set
+ $room: AssetState(type == AssetType.ROOM, attributeName == "presenceDetected", valueFalse)
+ // And the motion detected flag is set
+ AssetState(id == $room.id, attributeName == "motionDetected", valueTrue)
+ // And the CO2 level increased at least 2 times in the last 11 minutes
+ accumulate(
+ AssetEvent(id == $room.id, attributeName == "co2Level", valueGreaterThanOldValue) over window:time(11m);
+ $countCO2: count(1);
+ $countCO2 >= 2
+ )
+then
+ // Set the presence detected flag of the room
+ assets.dispatch(
+ new AttributeEvent($room.getId(), "presenceDetected", Values.create(true))
);
end
-rule "Clear presence detected timestamp if motion counter was not incremented in a while"
+rule "Clear presence detected flag of a room if no motion or CO2 increase was sensed in a while"
when
- // A room has a motion counter
- $room: AssetState(type == AssetType.ROOM, attributeName == "motionCount")
- // And the presence detected flag is set
- AssetState(id == $room.id, attributeName == "presenceDetected", valueAsBoolean == true)
- // And no motion counter increments have been received in the last 10 minutes
+ // A room weare the presence detected flag is set
+ $room: AssetState(type == AssetType.ROOM, attributeName == "presenceDetected", valueTrue)
+ // And the motion detected flag is not set
+ AssetState(id == $room.id, attributeName == "motionDetected", valueFalse)
+ // And the room has a CO2 sensor
+ AssetState(id == $room.id, attributeName == "co2Level")
+ // And the CO2 level was not increased in the last 11 minutes
accumulate(
- AssetEvent(id == $room.id, attributeName == "motionCount", valueAsNumber > 0) over window:time(10m);
- $count: count(1);
- $count == 0
+ AssetEvent(id == $room.id, attributeName == "co2Level", valueGreaterThanOldValue) over window:time(11m);
+ $countCO2: count(1);
+ $countCO2 == 0
)
then
// Clear the presence detected flag of the room
diff --git a/manager/test/src/main/groovy/org/openremote/test/ClientEventService.groovy b/manager/test/src/main/groovy/org/openremote/test/ClientEventService.groovy
index 34c8bdde0..c6eb87201 100644
--- a/manager/test/src/main/groovy/org/openremote/test/ClientEventService.groovy
+++ b/manager/test/src/main/groovy/org/openremote/test/ClientEventService.groovy
@@ -20,9 +20,7 @@
package org.openremote.test
import com.fasterxml.jackson.databind.ObjectMapper
-import org.openremote.manager.client.event.ShowFailureEvent
import org.openremote.manager.client.event.SubscriptionFailureEvent
-import org.openremote.manager.client.i18n.ManagerMessages
import org.openremote.manager.client.service.EventService
import org.openremote.model.event.bus.EventBus
import org.openremote.model.event.shared.*
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
index 1aadbeb0a..348de9461 100644
--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
@@ -582,7 +582,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
apartment1Livingroom.id == managerDemoSetup.apartment1LivingroomId
apartment1Livingroom.name == "Living Room"
def protectedAttributes = apartment1Livingroom.getAttributesList()
- protectedAttributes.size() == 6
+ protectedAttributes.size() == 7
def currentTemperature = apartment1Livingroom.getAttribute("currentTemperature").get()
currentTemperature.getType().get() == AttributeType.TEMPERATURE_CELCIUS
!currentTemperature.getValue().isPresent()
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
index 88657dd48..00d505eb2 100644
--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
@@ -246,7 +246,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets.size() == 3
assets.get(0).id == managerDemoSetup.apartment1Id
assets.get(1).id == managerDemoSetup.apartment1LivingroomId
- assets.get(1).getAttributesList().size() == 6
+ assets.get(1).getAttributesList().size() == 7
!assets.get(1).getAttribute("currentTemperature").get().getValue().isPresent()
assets.get(1).getAttribute("currentTemperature").get().meta.size() == 6
!assets.get(1).getAttribute("targetTemperature").get().getValue().isPresent()
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentNotificationWhenAlarmTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentNotificationWhenAlarmTest.groovy
index d4b6f4d2e..65834f6ee 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentNotificationWhenAlarmTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentNotificationWhenAlarmTest.groovy
@@ -55,12 +55,11 @@ class ApartmentNotificationWhenAlarmTest extends Specification implements Manag
assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1
}
- and: "the alarm enabled, presence detected flag and timestamp of the room should not be set"
+ and: "the alarm enabled, presence detected flag of room should not be set"
def apartment1Asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
assert !apartment1Asset.getAttribute("alarmEnabled").get().valueAsBoolean.orElse(null)
def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
assert !livingRoomAsset.getAttribute("presenceDetected").orElse(null).valueAsBoolean.orElse(null)
- assert !livingRoomAsset.getAttribute("lastPresenceDetected").orElse(null).getValue().isPresent()
and: "an authenticated test user"
def realm = "customerA"
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentPresenceDetectionTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentPresenceDetectionTest.groovy
index 1b11ad167..a481da307 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentPresenceDetectionTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentPresenceDetectionTest.groovy
@@ -24,7 +24,7 @@ import static org.openremote.model.attribute.AttributeEvent.Source.SENSOR
class ApartmentPresenceDetectionTest extends Specification implements ManagerContainerTrait {
- def "Detect presence with motion counter"() {
+ def "Motion detection with motion counter"() {
given: "the container environment is started"
def conditions = new PollingConditions(timeout: 10, delay: 1)
@@ -36,6 +36,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
def rulesetStorageService = container.getService(RulesetStorageService.class)
def simulatorProtocol = container.getService(SimulatorProtocol.class)
RulesEngine apartment1Engine = null
+ List<AssetEvent> insertedAssetEvents = []
and: "some rules"
Ruleset ruleset = new AssetRuleset(
@@ -51,22 +52,19 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
assert apartment1Engine != null
assert apartment1Engine.isRunning()
assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1
+ apartment1Engine.assetEventsConsumer = { assetEvent ->
+ insertedAssetEvents << assetEvent
+ }
+ setPseudoClocksToRealTime(container, apartment1Engine)
}
- and: "the presence detected flag and timestamp of the room should not be set"
+ and: "the motion detected flag and timestamp of the room should not be set"
def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
- assert !livingRoomAsset.getAttribute("presenceDetected").get().getValue().isPresent()
- assert !livingRoomAsset.getAttribute("lastPresenceDetected").get().getValue().isPresent()
+ assert !livingRoomAsset.getAttribute("motionDetected").get().getValue().isPresent()
+ assert !livingRoomAsset.getAttribute("lastMotionDetected").get().getValue().isPresent()
- when: "we have an events consumer for collecting test data"
- List<AssetEvent> insertedAssetEvents = []
- apartment1Engine.assetEventsConsumer = { assetEvent ->
- insertedAssetEvents << assetEvent
- }
-
- and: "several motion counter increments occur in the room, but not enough for presence detection"
+ when: "someone enters and leaves the room a few times"
insertedAssetEvents = []
- setPseudoClocksToRealTime(container, apartment1Engine)
// The motion counter increments 5 times, 3 minutes apart
for (i in 1..5) {
def motionCountIncrement = new AttributeEvent(
@@ -81,11 +79,12 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
advancePseudoClocks(3, MINUTES, container, apartment1Engine)
}
- then: "presence should not be detected"
+ then: "motion should not be detected"
new PollingConditions(initialDelay: 3).eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
+ assert !asset.getAttribute("motionDetected").get().getValue().isPresent()
+ assert !asset.getAttribute("lastMotionDetected").get().getValue().isPresent()
assert !asset.getAttribute("presenceDetected").get().getValue().isPresent()
- assert !asset.getAttribute("lastPresenceDetected").get().getValue().isPresent()
}
when: "time is advanced enough for event expiration"
@@ -96,66 +95,182 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1
}
- when: "several motion counter increments occur in the room, fast enough for presence detection"
+ when: "someone is moving around in the room"
insertedAssetEvents = []
- double expectedLastPresenceTimestamp = 0d
- // The motion counter increments 5 times, 1 minute apart
+ double expectedLastMotionTimestamp = 0d
+ // The motion counter increments 5 times, 30 seconds apart
for (i in 1..5) {
+
+ // Increment the motion counter
def motionCountIncrement = new AttributeEvent(
- managerDemoSetup.apartment1LivingroomId, "motionCount", Values.create(i), getClockTimeOf(apartment1Engine)
+ managerDemoSetup.apartment1LivingroomId, "motionCount", Values.create(100+i), getClockTimeOf(apartment1Engine)
)
simulatorProtocol.putState(motionCountIncrement)
new PollingConditions(timeout: 3).eventually {
assert insertedAssetEvents.any() {
- expectedLastPresenceTimestamp = it.valueTimestamp
+ expectedLastMotionTimestamp = it.valueTimestamp
it.matches(motionCountIncrement, SENSOR, true)
}
}
- advancePseudoClocks(1, MINUTES, container, apartment1Engine)
+
+ advancePseudoClocks(30, SECONDS, container, apartment1Engine)
}
- then: "presence should be detected"
+ then: "motion should be detected and the last motion counter increment is the last motion timestamp"
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
- assert asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().isPresent()
- assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceTimestamp
+ assert asset.getAttribute("motionDetected").get().getValueAsBoolean().get()
+ assert asset.getAttribute("lastMotionDetected").get().getValueAsNumber().isPresent()
+ assert asset.getAttribute("lastMotionDetected").get().getValueAsNumber().get() == expectedLastMotionTimestamp
+ assert !asset.getAttribute("presenceDetected").get().getValue().isPresent()
+ }
+
+ when: "there is no motion detected for a while"
+ advancePseudoClocks(20, MINUTES, container, apartment1Engine)
+
+ then: "no motion should be detected but the last timestamp still available"
+ conditions.eventually {
+ def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
+ assert !asset.getAttribute("motionDetected").get().getValueAsBoolean().get()
+ assert asset.getAttribute("lastMotionDetected").get().getValueAsNumber().isPresent()
+ assert asset.getAttribute("lastMotionDetected").get().getValueAsNumber().get() == expectedLastMotionTimestamp
+ assert !asset.getAttribute("presenceDetected").get().getValue().isPresent()
+ }
+
+ when: "time is advanced enough for event expiration"
+ advancePseudoClocks(2, HOURS, container, apartment1Engine)
+
+ then: "the events should have been expired and retracted automatically from the knowledge session"
+ conditions.eventually {
+ assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1
+ }
+
+ cleanup: "the server should be stopped"
+ stopContainer(container)
+ }
+
+ def "Motion detection with motion counter and presence confirmation with CO2 level"() {
+
+ given: "the container environment is started"
+ 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 rulesService = container.getService(RulesService.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
+ def rulesetStorageService = container.getService(RulesetStorageService.class)
+ def simulatorProtocol = container.getService(SimulatorProtocol.class)
+ RulesEngine apartment1Engine = null
+ List<AssetEvent> insertedAssetEvents = []
+
+ and: "some rules"
+ Ruleset ruleset = new AssetRuleset(
+ "Demo Apartment - Presence Detection with motion counter",
+ managerDemoSetup.apartment1Id,
+ getClass().getResource("/demo/rules/DemoApartmentPresenceDetectionCounter.drl").text
+ )
+ rulesetStorageService.merge(ruleset)
+
+ expect: "the rule engines to become available and be running"
+ conditions.eventually {
+ apartment1Engine = rulesService.assetEngines.get(managerDemoSetup.apartment1Id)
+ assert apartment1Engine != null
+ assert apartment1Engine.isRunning()
+ assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1
+ apartment1Engine.assetEventsConsumer = { assetEvent ->
+ insertedAssetEvents << assetEvent
+ }
+ setPseudoClocksToRealTime(container, apartment1Engine)
}
- when: "time moves on and we keep incrementing the motion counter in short intervals "
+ and: "the presence detected flag of the room should not be set"
+ def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
+ assert !livingRoomAsset.getAttribute("presenceDetected").get().getValue().isPresent()
+
+ when: "someone is moving around in the room"
insertedAssetEvents = []
- // The motion counter increments 20 times, 90 seconds apart
- for (i in 1..20) {
+ double expectedLastMotionTimestamp = 0d
+ // The motion counter increments 5 times, 30 seconds apart
+ for (i in 1..5) {
+
+ // Increment the motion counter
def motionCountIncrement = new AttributeEvent(
- managerDemoSetup.apartment1LivingroomId, "motionCount", Values.create(i), getClockTimeOf(apartment1Engine)
+ managerDemoSetup.apartment1LivingroomId, "motionCount", Values.create(100+i), getClockTimeOf(apartment1Engine)
)
simulatorProtocol.putState(motionCountIncrement)
new PollingConditions(timeout: 3).eventually {
assert insertedAssetEvents.any() {
- expectedLastPresenceTimestamp = it.valueTimestamp
+ expectedLastMotionTimestamp = it.valueTimestamp
it.matches(motionCountIncrement, SENSOR, true)
}
}
- advancePseudoClocks(90, SECONDS, container, apartment1Engine)
+
+ advancePseudoClocks(30, SECONDS, container, apartment1Engine)
}
- then: "presence should still be detected and the timestamp updated"
+ and: "someone is not moving but still present in the room"
+ // The CO2 level increments 3 times, 5 minutes apart
+ for (i in 1..3) {
+
+ def co2LevelIncrement = new AttributeEvent(
+ managerDemoSetup.apartment1LivingroomId, "co2Level", Values.create(400 + i), getClockTimeOf(apartment1Engine)
+ )
+ simulatorProtocol.putState(co2LevelIncrement)
+ new PollingConditions(timeout: 3).eventually {
+ assert insertedAssetEvents.any() {
+ it.matches(co2LevelIncrement, SENSOR, true)
+ }
+ }
+
+ advancePseudoClocks(5, MINUTES, container, apartment1Engine)
+ }
+
+ then: "presence should be detected and the last motion counter increment is the last detected timestamp"
+ conditions.eventually {
+ def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
+ assert asset.getAttribute("motionDetected").get().getValueAsBoolean().get()
+ assert asset.getAttribute("lastMotionDetected").get().getValueAsNumber().isPresent()
+ assert asset.getAttribute("lastMotionDetected").get().getValueAsNumber().get() == expectedLastMotionTimestamp
+ assert asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ }
+
+ when: "someone stays in the room but doesn't move"
+ insertedAssetEvents = []
+ // The CO2 level increments 5 times, 5 minutes apart
+ for (i in 1..5) {
+
+ def co2LevelIncrement = new AttributeEvent(
+ managerDemoSetup.apartment1LivingroomId, "co2Level", Values.create(500 + i), getClockTimeOf(apartment1Engine)
+ )
+ simulatorProtocol.putState(co2LevelIncrement)
+ new PollingConditions(timeout: 3).eventually {
+ assert insertedAssetEvents.any() {
+ it.matches(co2LevelIncrement, SENSOR, true)
+ }
+ }
+
+ advancePseudoClocks(5, MINUTES, container, apartment1Engine)
+ }
+
+ then: "presence should still be detected but no motion"
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
+ assert !asset.getAttribute("motionDetected").get().getValueAsBoolean().get()
+ assert asset.getAttribute("lastMotionDetected").get().getValueAsNumber().isPresent()
+ assert asset.getAttribute("lastMotionDetected").get().getValueAsNumber().get() == expectedLastMotionTimestamp
assert asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().isPresent()
- assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceTimestamp
}
- when: "time moves on without the motion counter incrementing"
+ when: "there is no CO2 level increase for a while"
advancePseudoClocks(20, MINUTES, container, apartment1Engine)
then: "presence should be gone but the last timestamp still available"
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
+ assert !asset.getAttribute("motionDetected").get().getValueAsBoolean().get()
+ assert asset.getAttribute("lastMotionDetected").get().getValueAsNumber().isPresent()
+ assert asset.getAttribute("lastMotionDetected").get().getValueAsNumber().get() == expectedLastMotionTimestamp
assert !asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().isPresent()
- assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceTimestamp
}
when: "time is advanced enough for event expiration"
@@ -170,6 +285,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
stopContainer(container)
}
+ // TODO This should be a very simple test that only shows how to accumulate and count events in rules, maybe move to new test clas
def "Detect presence with motion sensor"() {
given: "the container environment is started"
diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
index 37e7be3d7..95b0bae84 100644
--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
@@ -26,6 +26,7 @@ import org.openremote.model.attribute.AttributeType;
import org.openremote.model.value.ArrayValue;
import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.Value;
+import org.openremote.model.value.Values;
import java.util.Date;
import java.util.Optional;
@@ -260,6 +261,64 @@ public abstract class AbstractAssetUpdate {
return !attribute.getValue().equals(Optional.ofNullable(oldValue));
}
+ /**
+ * <code>true</code> if this value is not null and that value is null or this value is greater than that value.
+ */
+ public boolean isValueGreaterThan(Double that) {
+ Double number = getValueAsNumber();
+ return (number != null && that == null) || (number != null && number > that);
+ }
+
+ /**
+ * <code>true</code> if this value is not null and that value is null or this value is greater than that value.
+ */
+ public boolean isValueGreaterThan(Long that) {
+ return isValueGreaterThan(that != null ? (double) that : null);
+ }
+
+ /**
+ * <code>true</code> if this value is not null and the old value is null or this value is greater than old value.
+ */
+ public boolean isValueGreaterThanOldValue() {
+ return isValueGreaterThan(Values.getNumber(getOldValue()).orElse(null));
+ }
+
+ /**
+ * <code>true</code> if this value is null and that value is not null or this value is less than that value.
+ */
+ public boolean isValueLessThan(Double that) {
+ Double number = getValueAsNumber();
+ return (number == null && that != null) || (number != null && number < that);
+ }
+
+ /**
+ * <code>true</code> if this value is null and that value is not null or this value is less than that value.
+ */
+ public boolean isValueLessThan(Long that) {
+ return isValueLessThan(that != null ? (double) that : null);
+ }
+
+ /**
+ * <code>true</code> if this value is null and the old value is not null or this value is less than old value.
+ */
+ public boolean isValueLessThanOldValue() {
+ return isValueLessThan(Values.getNumber(getOldValue()).orElse(null));
+ }
+
+ /**
+ * Value is null or {@link org.openremote.model.value.BooleanValue} <code>false</code>.
+ */
+ public boolean isValueFalse() {
+ return getValueAsBoolean() == null || !getValueAsBoolean();
+ }
+
+ /**
+ * Value is not null or {@link org.openremote.model.value.BooleanValue} <code>true</code>.
+ */
+ public boolean isValueTrue() {
+ return getValueAsBoolean() != null && getValueAsBoolean();
+ }
+
public AttributeRef getAttributeRef() {
return attribute.getReferenceOrThrow();
}