Skip to content

armgit / core

Public Imported from GitHub
0

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

Presence detection demo with motion sensor instead of counter

Christian Bauerbf7e0a21cae1
diff --git a/container/src/main/java/org/openremote/container/timer/TimerService.java b/container/src/main/java/org/openremote/container/timer/TimerService.java
index adceeea3b..794e8ac5c 100644
--- a/container/src/main/java/org/openremote/container/timer/TimerService.java
+++ b/container/src/main/java/org/openremote/container/timer/TimerService.java
@@ -25,6 +25,7 @@ import org.openremote.container.ContainerService;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.logging.Logger;
import static org.openremote.container.util.MapAccess.getString;
@@ -33,6 +34,8 @@ import static org.openremote.container.util.MapAccess.getString;
*/
public class TimerService implements ContainerService {
+ private static final Logger LOG = Logger.getLogger(TimerService.class.getName());
+
public static final String TIMER_CLOCK_TYPE = "TIMER_CLOCK_TYPE";
public static final String TIMER_CLOCK_TYPE_DEFAULT = Clock.REAL.toString();
@@ -59,6 +62,8 @@ public class TimerService implements ContainerService {
@Override
public void init() {
timer.set(System.currentTimeMillis());
+ long current = timer.get();
+ LOG.info("Initialized pseudo clock to: " + (current) + "/" + new Date(current));
}
@Override
diff --git a/manager/client/src/main/java/org/openremote/manager/client/simulator/Simulator.java b/manager/client/src/main/java/org/openremote/manager/client/simulator/Simulator.java
index 027bc2a15..02ca09508 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/simulator/Simulator.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/simulator/Simulator.java
@@ -22,7 +22,6 @@ package org.openremote.manager.client.simulator;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.IsWidget;
-import com.google.gwt.user.client.ui.Widget;
import elemental.client.Browser;
import org.openremote.manager.client.Environment;
import org.openremote.manager.client.event.ShowSuccessEvent;
@@ -35,9 +34,7 @@ import org.openremote.model.simulator.SimulatorElement;
import org.openremote.model.simulator.SimulatorState;
import org.openremote.model.value.ValueType;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import java.util.function.Consumer;
import static org.openremote.manager.client.widget.ValueEditors.*;
@@ -92,7 +89,10 @@ public class Simulator extends FlowPanel implements IsWidget {
clear();
formGroups.clear();
- for (SimulatorElement element : simulatorState.getElements()) {
+ List<SimulatorElement> sortedElements = Arrays.asList(simulatorState.getElements());
+ Collections.sort(sortedElements, Comparator.comparing(o -> simulatorState.getElementName(o)));
+
+ for (SimulatorElement element : sortedElements) {
FormGroup formGroup = new FormGroup();
formGroup.getElement().getStyle().setWidth(80, Style.Unit.PCT);
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 2761b5e3b..a96b436cd 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
@@ -113,17 +113,16 @@ public abstract class AbstractManagerSetup implements Setup {
return room;
}
- protected void addDemoApartmentRoomMotionCounter(ServerAsset room, boolean shouldBeLinked, Supplier<MetaItem[]> agentLinker) {
+ protected void addDemoApartmentRoomMotionSensor(ServerAsset room, boolean shouldBeLinked, Supplier<MetaItem[]> agentLinker) {
room.addAttributes(
- new AssetAttribute("motionCount", NUMBER)
+ new AssetAttribute("motionSensor", NUMBER)
.setMeta(
- new MetaItem(LABEL, Values.create("Motion Count")),
- new MetaItem(DESCRIPTION, Values.create("Sensor that increments a counter when motion is detected")),
+ new MetaItem(LABEL, Values.create("Motion Sensor")),
+ new MetaItem(DESCRIPTION, Values.create("Value is greater than zero when motion is sensed")),
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))
+ new MetaItem(RULE_EVENT_EXPIRES, Values.create("1h"))
).addMeta(shouldBeLinked ? agentLinker.get() : null),
new AssetAttribute("motionDetected", AttributeType.BOOLEAN)
.setMeta(
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 8a6a53f8e..6419f3a08 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
@@ -362,7 +362,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
apartment1ServiceAgentId = apartment1ServiceAgent.getId();
ServerAsset apartment1Livingroom = createDemoApartmentRoom(apartment1, "Living Room");
- addDemoApartmentRoomMotionCounter(apartment1Livingroom, true, () -> new MetaItem[]{
+ addDemoApartmentRoomMotionSensor(apartment1Livingroom, true, () -> new MetaItem[]{
new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()),
new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME))
});
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/RulesDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/RulesDemoSetup.java
index 8ffbf9b3c..480ff0561 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/RulesDemoSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/RulesDemoSetup.java
@@ -51,9 +51,9 @@ public class RulesDemoSetup extends AbstractManagerSetup {
// ################################ Rules demo data ###################################
// Apartment 1
- try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentPresenceDetectionCounter.drl")) {
+ try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentPresenceDetection.drl")) {
String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));
- Ruleset ruleset = new AssetRuleset("Demo Apartment - Presence Detection with motion counter", managerDemoSetup.apartment1Id, rules);
+ Ruleset ruleset = new AssetRuleset("Demo Apartment - Presence Detection with motion sensor", managerDemoSetup.apartment1Id, rules);
apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();
}
try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentVacationMode.drl")) {
@@ -63,11 +63,6 @@ public class RulesDemoSetup extends AbstractManagerSetup {
}
// Apartment 2
- try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentPresenceDetectionPIR.drl")) {
- String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));
- Ruleset ruleset = new AssetRuleset("Demo Apartment - Presence Detection with motion PIR", managerDemoSetup.apartment2Id, rules);
- apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();
- }
try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentAllLightsOff.drl")) {
String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));
Ruleset ruleset = new AssetRuleset("Demo Apartment - All Lights Off", managerDemoSetup.apartment2Id, rules);
diff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl
similarity index 64%
rename from manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl
rename to manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl
index 1f474e152..94b136e5d 100644
--- a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl
+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl
@@ -2,29 +2,29 @@ package org.openremote.test.rules;
import java.util.ArrayList;
import org.openremote.model.*;
-import org.openremote.model.asset.*
-import org.openremote.model.value.Values
-import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.asset.*;
+import org.openremote.model.value.*;
+import org.openremote.model.attribute.*;
global java.util.logging.Logger LOG;
global org.openremote.model.rules.Assets assets;
/*
-Uses 'motionCount' and optional 'co2Level' of a room asset to set the 'motionDetected',
+Uses 'motionSensor' 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
+is based on multiple triggers of the motion sensor over a time window. Presence
detection is based on motion detection, and increasing CO2 level over a time window.
*/
-rule "Set motion detected flag of room when motion counter increments"
+rule "Set motion detected flag of room when motion sensor has been triggered"
when
// 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
+ // And the motion sensor has been triggered at least 3 times in the last 2 minutes
accumulate(
- AssetEvent(id == $room.id, attributeName == "motionCount", valueGreaterThanOldValue) over window:time(2m);
- $motionIncrements: count(1);
- $motionIncrements >= 3
+ AssetEvent(id == $room.id, attributeName == "motionSensor", isValueGreaterThan(0)) over window:time(2m);
+ $motionTriggers: count(1);
+ $motionTriggers >= 3
)
then
// Set the motion detected flag of the room
@@ -33,34 +33,32 @@ then
);
end
-
-rule "Update the motion detected timestamp when motion counter increments"
+rule "Update the motion detected timestamp when motion sensor has been triggered"
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))
+ // And the motion sensor has been triggered
+ AssetState(id == $room.id, attributeName == "motionSensor", isValueGreaterThan(0), $lastTriggerTimestamp: valueTimestamp)
+ // And the last sensor trigger event is newer than the recorded last detected time
+ AssetState(id == $room.id, attributeName == "lastMotionDetected", isValueLessThan($lastTriggerTimestamp))
then
- // Update the last presence detected timestamp to the latest counter increment event
+ // Update the last presence detected timestamp to the latest motion sensor trigger event
assets.dispatch(
- new AttributeEvent($room.getId(), "lastMotionDetected", Values.create($lastIncrementTimestamp))
+ new AttributeEvent($room.getId(), "lastMotionDetected", Values.create($lastTriggerTimestamp))
);
end
-
-rule "Clear motion detected flag of a room if the motion counter doesn't increment"
+rule "Clear motion detected flag of a room if the motion sensor hasn't been triggered"
when
// 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
+ // And the room has a motion sensor
+ AssetState(id == $room.id, attributeName == "motionSensor")
+ // And the motion sensor was not triggered in the last 15 minutes
accumulate(
- AssetEvent(id == $room.id, attributeName == "motionCount", valueGreaterThanOldValue) over window:time(15m);
- $countMotion: count(1);
- $countMotion == 0
+ AssetEvent(id == $room.id, attributeName == "motionSensor", isValueGreaterThan(0)) over window:time(15m);
+ $motionTriggers: count(1);
+ $motionTriggers == 0
)
then
// Clear the motion detected flag of the room
@@ -79,8 +77,8 @@ when
// 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
+ $increasedCO2: count(1);
+ $increasedCO2 >= 2
)
then
// Set the presence detected flag of the room
@@ -101,8 +99,8 @@ when
// And the CO2 level was not increased in the last 11 minutes
accumulate(
AssetEvent(id == $room.id, attributeName == "co2Level", valueGreaterThanOldValue) over window:time(11m);
- $countCO2: count(1);
- $countCO2 == 0
+ $increasedCO2: count(1);
+ $increasedCO2 == 0
)
then
// Clear the presence detected flag of the room
diff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drl
deleted file mode 100644
index 7dcc5540a..000000000
--- a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drl
+++ /dev/null
@@ -1,158 +0,0 @@
-package org.openremote.test.rules;
-
-import org.openremote.model.*;
-import org.openremote.model.asset.*
-import org.openremote.model.value.Values
-import java.util.Date
-import org.openremote.model.attribute.AttributeEvent;
-
-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 sensor triggers several times within a time window. The flag will be
-removed if the motion sensor has not been triggered within a time window. All time windows and
-the number of matches required can be configured.
-*/
-
-declare initFact
- @role(event)
- init: Boolean
-end
-
-rule "Insert init fact at startup"
-then
- insert(new initFact(true));
-end
-
-rule "Init firstPresenceDetected"
-salience 10
-when
- $init: initFact(init)
- $room : AssetState(type == AssetType.ROOM, attributeName == "motionSensor")
- AssetState(id==$room.id, attributeName == "firstPresenceDetected")
-then
- retract($init);
- assets.dispatch(
- new AttributeEvent($room.getId(), "firstPresenceDetected", Values.create(-1))
- );
-end
-
-rule "Fetch the first presence detected time stamp"
-when
- // A room has a motion sensor
- $room : AssetState(type == AssetType.ROOM, attributeName == "motionSensor")
- // And the presence detected flag is not set already
- // TODO although rule "Init firstPresenceDetected" is triggered this does not work here when uncommented.
- // we need some kind on unset value marker, probably -1 does not work. In the old rules files it was string "-"
- // AssetState(id == $room.id, attributeName == "firstPresenceDetected", valueAsNumber==-1)
- AssetState(id == $room.id, attributeName == "firstPresenceDetected", value==null)
- // And the motion sensor is triggered
- $sensorState: AssetState(id == $room.id, attributeName == "motionSensor", valueAsBoolean == true)
-then
- LOG.info("@-@"+(new java.util.Date(drools.getWorkingMemory().getSessionClock().getCurrentTime())).toString());
- // Fetch the first presence detected timestamp of the room
- assets.dispatch(
- new AttributeEvent($room.getId(), "firstPresenceDetected", Values.create($sensorState.getValueTimestamp()))
- );
-end
-
-declare CO2Rising
- @role(event)
- @expires(10m)
- roomId: String
-end
-
-rule "Insert CO2 rising event"
-when
- AssetState($roomId: id, type==AssetType.ROOM, attributeName == "co2Level", valueAsNumber > Values.getNumber(oldValue).orElse(null))
-then
- LOG.info("@-@"+(new java.util.Date(drools.getWorkingMemory().getSessionClock().getCurrentTime())).toString());
- insert(new CO2Rising($roomId));
-end
-
-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", valueAsBoolean != true)
- // And at least 5 motion sensor triggers have been received in the last 10 minutes
- accumulate(
- AssetEvent(id == $room.id, attributeName == "motionSensor", valueAsBoolean == true) over window:time(10m);
- $count: count(1);
- $count >= 5
- )
- // Only when there is no CO2 sensor
- not AssetState(id == $room.id, attributeName == "co2Level")
-then
- LOG.info("@-@"+(new java.util.Date(drools.getWorkingMemory().getSessionClock().getCurrentTime())).toString());
- // Set the presence detected flag of the room
- assets.dispatch(
- new AttributeEvent($room.getId(), "presenceDetected", Values.create(true))
- );
-end
-
-rule "Set presence detected flag if CO2 rises in time window"
-when
- // A room has a motion sensor
- $room : AssetState(type == AssetType.ROOM, attributeName == "co2Level")
- // And "firstPresenceDetected" is true
-// AssetState(id == $room.id, attributeName == "firstPresenceDetected", valueAsNumber > 0)
- // And the presence detected flag is not set already
- AssetState(id == $room.id, attributeName == "presenceDetected", valueAsBoolean != true)
- // And at least 5 CO2Rising have been received in the last 10 minutes
- accumulate(
- CO2Rising(roomId==$room.id) over window:time(10m);
- $count: count(1);
- $count >= 5
- )
-then
- LOG.info("@-@"+(new java.util.Date(drools.getWorkingMemory().getSessionClock().getCurrentTime())).toString());
- // Set the presence detected flag of the room
- assets.dispatch(
- new AttributeEvent($room.getId(), "presenceDetected", Values.create(true))
- );
-end
-
-rule "Update the presence detected timestamp if motion sensor is triggered and we have already detected presence"
-when
- // The presence detected flag is set in a room
- $room: AssetState(type == AssetType.ROOM, attributeName == "presenceDetected", valueAsBoolean == true)
- // And the motion sensor is triggered
- $sensorState: AssetState(id == $room.id, attributeName == "motionSensor", valueAsBoolean == true)
-then
- LOG.info("@-@"+(new java.util.Date(drools.getWorkingMemory().getSessionClock().getCurrentTime())).toString());
- // Update the last presence detected timestamp of the room
- assets.dispatch(
- new AttributeEvent($room.getId(), "lastPresenceDetected", Values.create($sensorState.getValueTimestamp()))
- );
-end
-
-rule "Clear presence detected flag if motion sensor was not triggered for 10m and CO2 is not rising for 20m"
-when
- // A room has a motion sensor
- $room: AssetState(type == AssetType.ROOM, attributeName == "motionSensor")
- // And the presence detected flag is set
- AssetState(id == $room.id, attributeName == "presenceDetected", valueAsBoolean == true)
- // And no motion sensor triggers have been received in the last 10 minutes
- accumulate(
- AssetEvent(id == $room.id, attributeName == "motionSensor", valueAsBoolean == true) over window:time(10m);
- $count: count(1);
- $count == 0
- )
- // and no increasing CO2 in the last 20 minutes
- accumulate(
- CO2Rising(roomId == $room.id) over window:time(20m);
- $countCO2: count(1);
- $countCO2 == 0
- )
-then
- // TODO this should be 10 min after the Update rule, but it happens at irregular times, sometimes earlier, sometimes later.
- LOG.info("@-@"+(new java.util.Date(drools.getWorkingMemory().getSessionClock().getCurrentTime())).toString());
- // Clear the presence detected flag of the room
- assets.dispatch(
- new AttributeEvent($room.getId(), "presenceDetected", Values.create(false))
- );
-end
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 1221c3ca7..361290e1a 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
@@ -411,7 +411,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
asset = assetStorageService.find(
new AssetQuery()
.id(managerDemoSetup.apartment1LivingroomId)
- .select(new Select("co2Level", "lastMotionDetected", "motionCount").loadComplete(true))
+ .select(new Select("co2Level", "lastMotionDetected", "motionSensor").loadComplete(true))
)
then: "result should match"
@@ -433,14 +433,14 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
asset.getAttribute("co2Level").get().meta.size() == 11
asset.getAttribute("lastMotionDetected").isPresent()
asset.getAttribute("lastMotionDetected").get().meta.size() == 4
- asset.getAttribute("motionCount").isPresent()
- asset.getAttribute("motionCount").get().meta.size() == 9
+ asset.getAttribute("motionSensor").isPresent()
+ asset.getAttribute("motionSensor").get().meta.size() == 8
when: "a query is executed to select a subset of protected attributes"
asset = assetStorageService.find(
new AssetQuery()
.id(managerDemoSetup.apartment1LivingroomId)
- .select(new Select("co2Level", "lastMotionDetected", "motionCount").loadComplete(true).filterProtected(true))
+ .select(new Select("co2Level", "lastMotionDetected", "motionSensor").loadComplete(true).filterProtected(true))
)
then: "result should contain only matches that are protected"
@@ -462,7 +462,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
asset.getAttribute("co2Level").get().meta.size() == 8
asset.getAttribute("lastMotionDetected").isPresent()
asset.getAttribute("lastMotionDetected").get().meta.size() == 3
- !asset.getAttribute("motionCount").isPresent()
+ !asset.getAttribute("motionSensor").isPresent()
cleanup: "the server should be stopped"
stopContainer(container)
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 2d100425c..aa4d3c4e6 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
@@ -14,18 +14,16 @@ import org.openremote.model.rules.AssetRuleset
import org.openremote.model.rules.Ruleset
import org.openremote.model.value.Values
import org.openremote.test.ManagerContainerTrait
-import spock.lang.Ignore
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
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_APARTMENT_2
import static org.openremote.model.attribute.AttributeEvent.Source.SENSOR
class ApartmentPresenceDetectionTest extends Specification implements ManagerContainerTrait {
- def "Motion detection with motion counter"() {
+ def "Motion detection with motion sensor"() {
given: "the container environment is started"
def conditions = new PollingConditions(timeout: 10, delay: 1)
@@ -42,9 +40,9 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
and: "some rules"
Ruleset ruleset = new AssetRuleset(
- "Demo Apartment - Presence Detection with motion counter",
+ "Demo Apartment - Presence Detection with motion sensor",
managerDemoSetup.apartment1Id,
- getClass().getResource("/demo/rules/DemoApartmentPresenceDetectionCounter.drl").text
+ getClass().getResource("/demo/rules/DemoApartmentPresenceDetection.drl").text
)
rulesetStorageService.merge(ruleset)
@@ -57,7 +55,6 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
apartment1Engine.assetEventsConsumer = { assetEvent ->
insertedAssetEvents << assetEvent
}
- setPseudoClocksToRealTime(container, apartment1Engine)
}
and: "the motion detected flag and timestamp of the room should not be set"
@@ -65,23 +62,22 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
assert !livingRoomAsset.getAttribute("motionDetected").get().getValue().isPresent()
assert !livingRoomAsset.getAttribute("lastMotionDetected").get().getValue().isPresent()
- when: "the system has been running for a while (subsequent attribute events are newer than initial state)"
- advancePseudoClocks(5, SECONDS, container, apartment1Engine)
-
- and: "someone enters and leaves the room a few times"
+ when: "someone enters and leaves the room a few times"
insertedAssetEvents = []
- // The motion counter increments 5 times, 3 minutes apart
+ // The motion sensor triggers 5 times, 3 minutes apart
for (i in 1..5) {
- def motionCountIncrement = new AttributeEvent(
- managerDemoSetup.apartment1LivingroomId, "motionCount", Values.create(i), getClockTimeOf(apartment1Engine)
+ // Use the loop i as value so we can identify and test if we have processed this event
+ def motionSensorTrigger = new AttributeEvent(
+ managerDemoSetup.apartment1LivingroomId, "motionSensor", Values.create(i), getClockTimeOf(apartment1Engine)
)
// Use the simulator to inject the update
- simulatorProtocol.putValue(motionCountIncrement)
+ simulatorProtocol.putValue(motionSensorTrigger)
- // Wait until rules engine completes work asynchronously
+ // Wait until rules engine completes work asynchronously, must have processed the event
new PollingConditions(timeout: 5, delay: 0.5).eventually {
- assert insertedAssetEvents.any() { it.matches(motionCountIncrement, SENSOR, true) }
+ assert insertedAssetEvents.any() { it.matches(motionSensorTrigger, SENSOR, true) }
+ // And wait until we have processed resulting events due to rules firing
assert noEventProcessedIn(assetProcessingService, 500)
}
@@ -107,18 +103,18 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
when: "someone is moving around in the room"
insertedAssetEvents = []
double expectedLastMotionTimestamp = 0d
- // The motion counter increments 5 times, 30 seconds apart
+ // The motion sensor triggers 5 times, 30 seconds apart
for (i in 1..5) {
- def motionCountIncrement = new AttributeEvent(
- managerDemoSetup.apartment1LivingroomId, "motionCount", Values.create(100+i), getClockTimeOf(apartment1Engine)
+ def motionSensorTrigger = new AttributeEvent(
+ managerDemoSetup.apartment1LivingroomId, "motionSensor", Values.create(i), getClockTimeOf(apartment1Engine)
)
- simulatorProtocol.putValue(motionCountIncrement)
+ simulatorProtocol.putValue(motionSensorTrigger)
new PollingConditions(timeout: 5, delay: 0.5).eventually {
assert insertedAssetEvents.any() {
expectedLastMotionTimestamp = it.valueTimestamp
- it.matches(motionCountIncrement, SENSOR, true)
+ it.matches(motionSensorTrigger, SENSOR, true)
}
assert noEventProcessedIn(assetProcessingService, 500)
}
@@ -135,7 +131,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
assert !asset.getAttribute("presenceDetected").get().getValue().isPresent()
}
- when: "there is no motion detected for a while"
+ when: "there is no motion sensed for a while"
advancePseudoClocks(20, MINUTES, container, apartment1Engine)
then: "no motion should be detected but the last timestamp still available"
@@ -159,7 +155,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
stopContainer(container)
}
- def "Motion detection with motion counter and presence confirmation with CO2 level"() {
+ def "Motion detection with motion sensor and presence confirmation with CO2 level"() {
given: "the container environment is started"
def conditions = new PollingConditions(timeout: 10, delay: 1)
@@ -176,9 +172,9 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
and: "some rules"
Ruleset ruleset = new AssetRuleset(
- "Demo Apartment - Presence Detection with motion counter",
+ "Demo Apartment - Presence Detection with motion sensor",
managerDemoSetup.apartment1Id,
- getClass().getResource("/demo/rules/DemoApartmentPresenceDetectionCounter.drl").text
+ getClass().getResource("/demo/rules/DemoApartmentPresenceDetection.drl").text
)
rulesetStorageService.merge(ruleset)
@@ -191,33 +187,27 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
apartment1Engine.assetEventsConsumer = { assetEvent ->
insertedAssetEvents << assetEvent
}
- setPseudoClocksToRealTime(container, apartment1Engine)
}
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: "the system has been running for a while (subsequent attribute events are newer than initial state)"
- advancePseudoClocks(5, SECONDS, container, apartment1Engine)
-
- and: "someone is moving around in the room"
+ when: "someone is moving around in the room"
insertedAssetEvents = []
double expectedLastMotionTimestamp = 0d
- // The motion counter increments 5 times, 30 seconds apart
+ // The motion sensor triggers 5 times, 30 seconds apart
for (i in 1..5) {
- // Increment the motion counter
- def motionCountIncrement = new AttributeEvent(
- managerDemoSetup.apartment1LivingroomId, "motionCount", Values.create(100+i), getClockTimeOf(apartment1Engine)
+ def motionSensorTrigger = new AttributeEvent(
+ managerDemoSetup.apartment1LivingroomId, "motionSensor", Values.create(i), getClockTimeOf(apartment1Engine)
)
- simulatorProtocol.putValue(motionCountIncrement)
+ simulatorProtocol.putValue(motionSensorTrigger)
new PollingConditions(timeout: 5, delay: 0.5).eventually {
assert insertedAssetEvents.any() {
expectedLastMotionTimestamp = it.valueTimestamp
- boolean result = it.matches(motionCountIncrement, SENSOR, true)
- return result
+ it.matches(motionSensorTrigger, SENSOR, true)
}
assert noEventProcessedIn(assetProcessingService, 500)
}
@@ -244,7 +234,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
advancePseudoClocks(5, MINUTES, container, apartment1Engine)
}
- then: "presence should be detected and the last motion counter increment is the last detected timestamp"
+ then: "presence should be detected and the last motion sensor trigger is the last detected timestamp"
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
assert asset.getAttribute("motionDetected").get().getValueAsBoolean().get()
@@ -305,218 +295,4 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
cleanup: "the server should be stopped"
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
- @Ignore
- def "Detect presence with motion sensor"() {
-
- given: "the container environment is started"
- def conditions = new PollingConditions(timeout: 60, 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 assetProcessingService = container.getService(AssetProcessingService.class)
- def assetStorageService = container.getService(AssetStorageService.class)
- def rulesetStorageService = container.getService(RulesetStorageService.class)
- RulesEngine apartment2Engine = null
-
- and: "some rules"
- Ruleset ruleset = new AssetRuleset(
- "Demo Apartment - Presence Detection with motion PIR",
- managerDemoSetup.apartment2Id,
- getClass().getResource("/demo/rules/DemoApartmentPresenceDetectionPIR.drl").text
- )
- rulesetStorageService.merge(ruleset)
-
- expect: "the rule engines to become available and be running"
- conditions.eventually {
- apartment2Engine = rulesService.assetEngines.get(managerDemoSetup.apartment2Id)
- assert apartment2Engine != null
- assert apartment2Engine.isRunning()
- assert apartment2Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_2
- }
-
- 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().getValueAsBoolean().get()
- assert !livingRoomAsset.getAttribute("lastPresenceDetected").get().getValueAsNumber().isPresent()
- assert !livingRoomAsset.getAttribute("firstPresenceDetected").get().getValueAsNumber().isPresent()
- def bathRoomAsset = assetStorageService.find(managerDemoSetup.apartment2BathroomId, true)
- assert !bathRoomAsset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- assert !bathRoomAsset.getAttribute("lastPresenceDetected").get().getValueAsNumber().isPresent()
- // TODO: Fix this check - value actually contains -1.0 (as inserted by the Init firstPresentDetected rule)
- assert !bathRoomAsset.getAttribute("firstPresenceDetected").get().getValueAsNumber().isPresent()
-
- when: "we have an events consumer for collecting test data"
- List<AssetEvent> insertedAssetEvents = []
- apartment2Engine.assetEventsConsumer = { assetEvent ->
- insertedAssetEvents << assetEvent
- }
-
- and: "several motion sensor events are triggered in the room, but not enough for presence detection"
- insertedAssetEvents = []
- setPseudoClocksToRealTime(container, apartment2Engine)
- def firstPresenceDetectedTimeStamp = 0;
- // Send 5 triggers each 3 minutes apart
- for (i in 1..5) {
- def motionSensorTrigger = new AttributeEvent(
- managerDemoSetup.apartment2BathroomId, "motionSensor", Values.create(true), getClockTimeOf(apartment2Engine)
- )
- assetProcessingService.sendAttributeEvent(motionSensorTrigger)
- if (i == 1)
- firstPresenceDetectedTimeStamp = motionSensorTrigger.timestamp
- new PollingConditions(timeout: 25, initialDelay: 0.2, delay: 0.2).eventually {
- assert insertedAssetEvents.any() { it.matches(motionSensorTrigger) }
- }
- advancePseudoClocks(3, MINUTES, container, apartment2Engine)
- }
-
- then: "presence should not be detected"
- new PollingConditions(initialDelay: 3).eventually {
- def asset = assetStorageService.find(managerDemoSetup.apartment2BathroomId, true)
- assert !asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- assert !asset.getAttribute("lastPresenceDetected").get().getValue().isPresent()
- // First presence should be fetch
- // TODO this test sometimes fails as the rule "Fetch the first presence detected time stamp" is triggered twice, which is wrong as it should trigger only once
- // assert asset.getAttribute("firstPresenceDetected").get().getValueAsNumber().orElse(null) == firstPresenceDetectedTimeStamp
- }
-
- 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
- assert !bathRoomAsset.getAttribute("firstPresenceDetected").get().getValueAsNumber().isPresent()
- }
-
- when: "several motion sensor events are triggered in the room, fast enough for presence detection"
- insertedAssetEvents = []
- double expectedLastPresenceTimestampBathroom = 0
- def expectedLastPresenceTimestampLivingroom = 0
- // Send 5 triggers each 1 minute apart
- for (i in 1..5) {
- def motionSensorTriggerLivingroom = new AttributeEvent(
- managerDemoSetup.apartment2LivingroomId, "motionSensor", Values.create(true), getClockTimeOf(apartment2Engine)
- )
- def motionSensorTriggerBathroom = new AttributeEvent(
- managerDemoSetup.apartment2BathroomId, "motionSensor", Values.create(true), getClockTimeOf(apartment2Engine)
- )
- def co2LevelIncrement = new AttributeEvent(
- managerDemoSetup.apartment2LivingroomId, "co2Level", Values.create(400 + i), getClockTimeOf(apartment2Engine)
- )
- expectedLastPresenceTimestampBathroom = motionSensorTriggerBathroom.timestamp
- assetProcessingService.sendAttributeEvent(motionSensorTriggerBathroom)
- if (i == 1) {
- // Trigger motion sensor
- assetProcessingService.sendAttributeEvent(motionSensorTriggerLivingroom)
- assetProcessingService.sendAttributeEvent(co2LevelIncrement)
- expectedLastPresenceTimestampLivingroom = motionSensorTriggerLivingroom.timestamp
- } else {
- // Increase CO2 because person is not moving but breathing
- assetProcessingService.sendAttributeEvent(co2LevelIncrement)
- }
- new PollingConditions(timeout: 25, initialDelay: 0.2, delay: 0.2).eventually {
- assert insertedAssetEvents.any() { it.matches(motionSensorTriggerBathroom) }
- if (i > 1) {
- // TODO why the following test fails?
- // assert insertedAssetEvents.any() { it.matches(co2LevelIncrement) }
- } else
- assert insertedAssetEvents.any() { it.matches(motionSensorTriggerLivingroom) }
- }
- advancePseudoClocks(1, MINUTES, container, apartment2Engine)
- }
-
- then: "presence should be detected"
- conditions.eventually {
- def asset = assetStorageService.find(managerDemoSetup.apartment2BathroomId, true)
- assert asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().orElse(null) == expectedLastPresenceTimestampBathroom
- asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
- assert asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().orElse(null) == expectedLastPresenceTimestampLivingroom
- }
-
- when: "time moves on and we keep triggering the motion sensor in short intervals "
- def expectedLastPresenceTimestamp
- insertedAssetEvents = []
- // Send 20 triggers each 10 seconds apart
- for (i in 1..20) {
- advancePseudoClocks(10, SECONDS, container, apartment2Engine)
- def motionSensorTriggerLivingroom = new AttributeEvent(
- managerDemoSetup.apartment2LivingroomId, "motionSensor", Values.create(true), getClockTimeOf(apartment2Engine)
- )
- def motionSensorTriggerBathroom = new AttributeEvent(
- managerDemoSetup.apartment2BathroomId, "motionSensor", Values.create(true), getClockTimeOf(apartment2Engine)
- )
- expectedLastPresenceTimestamp = motionSensorTriggerBathroom.timestamp
- assetProcessingService.sendAttributeEvent(motionSensorTriggerBathroom)
- assetProcessingService.sendAttributeEvent(motionSensorTriggerLivingroom)
- new PollingConditions(timeout: 25, initialDelay: 0.2, delay: 0.2).eventually {
- assert insertedAssetEvents.any() { it.matches(motionSensorTriggerBathroom) }
- assert insertedAssetEvents.any() { it.matches(motionSensorTriggerLivingroom) }
- }
- }
- def co2LevelIncrement = new AttributeEvent(
- managerDemoSetup.apartment2LivingroomId, "co2Level", Values.create(500), getClockTimeOf(apartment2Engine)
- )
- assetProcessingService.sendAttributeEvent(co2LevelIncrement)
-
- then: "presence should still be detected and the timestamp updated"
- conditions.eventually {
- def asset = assetStorageService.find(managerDemoSetup.apartment2BathroomId, true)
- assert asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- // TODO it sometimes fails with the following:
-// asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().orElse(null) == expectedLastPresenceTimestamp
-// | | | | | | |
-// | | | | | | 1495967135894
-// | | | | | false
-// | | | | 1.495967045894E12
-// | | | Optional[1.495967045894E12]
-// | | AssetAttribute{assetId='6DWae4YmRn64I1eyYSi2qA', name='lastPresenceDetected'} {"meta":[{"name":"urn:openremote:asset:meta:label","value":"Last Presence Timestamp"},{"name":"urn:openremote:asset:meta:description","value":"Timestamp of last detected presence"},{"name":"urn:openremote:asset:meta:ruleState","value":true}],"type":"TIMESTAMP_MILLIS","value":1.495967045894E12,"valueTimestamp":1.495967135871E12}
-// | Optional[AssetAttribute{assetId='6DWae4YmRn64I1eyYSi2qA', name='lastPresenceDetected'} {"meta":[{"name":"urn:openremote:asset:meta:label","value":"Last Presence Timestamp"},{"name":"urn:openremote:asset:meta:description","value":"Timestamp of last detected presence"},{"name":"urn:openremote:asset:meta:ruleState","value":true}],"type":"TIMESTAMP_MILLIS","value":1.495967045894E12,"valueTimestamp":1.495967135871E12}]
-// ServerAsset{id='6DWae4YmRn64I1eyYSi2qA', name='Living Room', type ='urn:openremote:asset:room'}
-
-// assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().orElse(null) == expectedLastPresenceTimestamp
- asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
- assert asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
-// assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().orElse(null) == expectedLastPresenceTimestamp
- }
-
- when: "time moves on without the motion sensor being triggered"
- advancePseudoClocks(9, MINUTES, container, apartment2Engine)
-
- then: "presence should be gone but the last timestamp still available"
- // First in the bathroom after exactly 10m since last movement
- conditions.eventually {
- advancePseudoClocks(1, MINUTES, container, apartment2Engine)
- def asset = assetStorageService.find(managerDemoSetup.apartment2BathroomId, true)
- assert !asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
-// assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().orElse(null) == expectedLastPresenceTimestamp
- // TODO check if this is exactly after 10m
- }
- advancePseudoClocks(9, MINUTES, container, apartment2Engine)
-
- and: "In the living room after 20m since CO2 increment"
- conditions.eventually {
- advancePseudoClocks(1, MINUTES, container, apartment2Engine)
- def asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
- assert !asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
-// assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().orElse(null) == expectedLastPresenceTimestamp
- // TODO check if this is exactly after 20m
- }
-
- 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
- }
-
- cleanup: "the server should be stopped"
- stopContainer(container)
- }
-
}