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
Work on presence detection rules
Christian Bauer2c7f44d153d7
diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.java b/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.javaindex 4b8196861..7c8894d11 100644--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.java+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.java@@ -81,9 +81,9 @@ public class MapInfoPanel extends AbstractAppPanel {public void setItems(List<Pair<String, String>> infoItems) {contentPanel.clear();- int itemMaxFontSizePixels = 18;+ int itemLineHeightPixels = 20;int itemMarginPixels = 8;- int itemHeightPixels = itemMaxFontSizePixels + (itemMarginPixels*2);+ int itemHeightPixels = itemLineHeightPixels + (itemMarginPixels*2);int totalMaxHeight = itemHeightPixels * MAX_ITEMS_BEFORE_SCROLLING;for (Pair<String, String> infoItem : infoItems) {diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.ui.xmlindex eeebf0f63..143f70d0e 100644--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.ui.xml+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.ui.xml@@ -25,12 +25,12 @@.contentItemKeyLabel {font-size: 14px;- line-height: 14px;+ line-height: 16px;}.contentItemValueLabel {font-size: 18px;- line-height: 18px;+ line-height: 20px;}</ui:style>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 5c638de0e..8894063f6 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@@ -392,18 +392,38 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment1Livingroom.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment1Livingroom.setType(ROOM);List<AssetAttribute> apartment1LivingroomAttributes = Arrays.asList(- new AssetAttribute("presenceSensor", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("motionSensor", AttributeType.BOOLEAN, Json.create(false)).setMeta(new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Presence Sensor"))+ new MetaItem(AssetMeta.LABEL, Json.create("Motion Sensor"))+ ).add(+ new MetaItem(AssetMeta.DESCRIPTION, Json.create(+ "PIR sensor that sends 'true' when motion is sensed"+ ))+ ).add(+ new MetaItem(AssetMeta.RULE_EVENT, Json.create(true))+ )+ ),+ new AssetAttribute("motionCounter", AttributeType.INTEGER, Json.create(0))+ .setMeta(+ new Meta().add(+ new MetaItem(AssetMeta.LABEL, Json.create("Motion Counter"))+ ).add(+ new MetaItem(AssetMeta.DESCRIPTION, Json.create(+ "Sensor that increments a counter when motion is sensed"+ ))).add(new MetaItem(AssetMeta.RULE_EVENT, Json.create(true)))),- new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("presenceDetected", AttributeType.DECIMAL, Json.createNull()).setMeta(new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected"))+ new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected Timestamp"))+ ).add(+ new MetaItem(AssetMeta.DESCRIPTION, Json.create(+ "Timestamp of last detected presence, empty if nobody is present"+ ))).add(new MetaItem(AssetMeta.RULE_STATE, Json.create(true)))@@ -519,18 +539,38 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment2Livingroom.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment2Livingroom.setType(ROOM);List<AssetAttribute> apartment2LivingroomAttributes = Arrays.asList(- new AssetAttribute("presenceSensor", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("motionSensor", AttributeType.BOOLEAN, Json.create(false)).setMeta(new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Presence Sensor"))+ new MetaItem(AssetMeta.LABEL, Json.create("Motion Sensor"))+ ).add(+ new MetaItem(AssetMeta.DESCRIPTION, Json.create(+ "PIR sensor that sends 'true' when motion is sensed"+ ))).add(new MetaItem(AssetMeta.RULE_EVENT, Json.create(true)))),- new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("motionCounter", AttributeType.INTEGER, Json.create(0)).setMeta(new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected"))+ new MetaItem(AssetMeta.LABEL, Json.create("Motion Counter"))+ ).add(+ new MetaItem(AssetMeta.DESCRIPTION, Json.create(+ "Sensor that increments a counter when motion is sensed"+ ))+ ).add(+ new MetaItem(AssetMeta.RULE_EVENT, Json.create(true))+ )+ ),+ new AssetAttribute("presenceDetected", AttributeType.DECIMAL, Json.createNull())+ .setMeta(+ new Meta().add(+ new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected Timestamp"))+ ).add(+ new MetaItem(AssetMeta.DESCRIPTION, Json.create(+ "Timestamp of last detected presence, empty if nobody is present"+ ))).add(new MetaItem(AssetMeta.RULE_STATE, Json.create(true)))@@ -579,18 +619,38 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment3Livingroom.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment3Livingroom.setType(ROOM);List<AssetAttribute> apartment3LivingroomAttributes = Arrays.asList(- new AssetAttribute("presenceSensor", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("motionSensor", AttributeType.BOOLEAN, Json.create(false)).setMeta(new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Presence Sensor"))+ new MetaItem(AssetMeta.LABEL, Json.create("Motion Sensor"))+ ).add(+ new MetaItem(AssetMeta.DESCRIPTION, Json.create(+ "PIR sensor that sends 'true' when motion is sensed"+ ))).add(new MetaItem(AssetMeta.RULE_EVENT, Json.create(true)))),- new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("motionCounter", AttributeType.INTEGER, Json.create(0)).setMeta(new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected"))+ new MetaItem(AssetMeta.LABEL, Json.create("Motion Counter"))+ ).add(+ new MetaItem(AssetMeta.DESCRIPTION, Json.create(+ "Sensor that increments a counter when motion is sensed"+ ))+ ).add(+ new MetaItem(AssetMeta.RULE_EVENT, Json.create(true))+ )+ ),+ new AssetAttribute("presenceDetected", AttributeType.DECIMAL, Json.createNull())+ .setMeta(+ new Meta().add(+ new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected Timestamp"))+ ).add(+ new MetaItem(AssetMeta.DESCRIPTION, Json.create(+ "Timestamp of last detected presence, empty if nobody is present"+ ))).add(new MetaItem(AssetMeta.RULE_STATE, Json.create(true)))diff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drlindex bc6b5e6e5..d12cb6b69 100644--- a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl@@ -7,22 +7,83 @@ import elemental.json.Json;global java.util.logging.Logger LOG;global org.openremote.model.rules.Assets assets;-rule "Set presence detected if sensor is triggered multiple times"+/*++Calculate and set the "presenceDetected" timestamp attribute of a ROOM when either motion sensor+is triggered several times within a defined time window, or a motion counter is incremented+several times within a time window. The timestamp will be cleared if no motion is sensed in+a defined time window or a motion counter has not been incremented within a time window.+All time windows and the number of matches required can be configured.++*/++/* ####################################### MOTION SENSOR ###################################### */++rule "Set presence detected timestamp if motion sensor is triggered in time window"when- // The presence sensor of a room is triggered- $pir : AssetEvent(type == AssetType.ROOM, attributeName == "presenceSensor", value.asBoolean)+ // The motion sensor in a room is triggered+ $roomEvent : AssetEvent(type == AssetType.ROOM, attributeName == "motionSensor", value.asBoolean)// More than 2 times in the last 15 minutesNumber(intValue > 2) from accumulate(- $pir2 : AssetEvent(id == $pir.id, attributeName == "presenceSensor", type == AssetType.ROOM, value.asBoolean) over window:time(15m),- count($pir2)+ $roomEvent2 : AssetEvent(id == $roomEvent.id, attributeName == "motionSensor", value.asBoolean) over window:time(15m),+ count($roomEvent2))- // And the presence latch is not set already- AssetState(id == $pir.getId(), attributeName == "presenceDetected", !value.asBoolean)+ // And the presence detected timestamp is not set already+ AssetState(id == $roomEvent.getId(), attributeName == "presenceDetected", valueNull)+then+ // Set the presence detected timestamp of the room+ long currentTime = drools.getWorkingMemory().getSessionClock().getCurrentTime();+ assets.dispatch(+ new AttributeEvent($roomEvent.getId(), "presenceDetected", Json .create(currentTime))+ );+end+rule "Clear presence detected timestamp if motion sensor was not triggered in a while"+when+ // The motion sensor in a room as not been triggered in the last 15 minutes+ $roomEvent : AssetEvent(type == AssetType.ROOM, attributeName == "motionSensor", value.asBoolean)+ not(AssetEvent(id == $roomEvent.id, attributeName == "motionSensor", value.asBoolean, this != $roomEvent, this after[0s,15m] $roomEvent ))+ // And the presence detected timestamp is set+ AssetState(id == $roomEvent.getId(), attributeName == "presenceDetected", !valueNull)+then+ // Clear the presence detected timestamp of the room+ assets.dispatch(+ new AttributeEvent($roomEvent.getId(), "presenceDetected", Json .createNull())+ );+end++/* ####################################### MOTION COUNTER ###################################### */++rule "Set presence detected timestamp 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)+ accumulate(+ AssetEvent(id == $roomEvent.id, attributeName == "motionCounter", $newMC: value.asNumber > 0) over window:time(15m);+ $count: count(1),+ $maxMC: max($newMC);+ $maxMC > $orgMC, $count > 2+ )+ // And the presence detected timestamp is not set already+ AssetState(id == $roomEvent.getId(), attributeName == "presenceDetected", valueNull)+then+ // Set the presence detected timestamp of the room+ long currentTime = drools.getWorkingMemory().getSessionClock().getCurrentTime();+ assets.dispatch(+ new AttributeEvent($roomEvent.getId(), "presenceDetected", Json .create(currentTime))+ );+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 ))+ // And the presence detected timestamp is set+ AssetState(id == $roomEvent.getId(), attributeName == "presenceDetected", !valueNull)then- LOG.info("### PRESENCE DETECTED IN ROOM: " + $pir);- // Set the presence latch of the room+ // Clear the presence detected timestamp of the roomassets.dispatch(- new AttributeEvent($pir.getId(), "presenceDetected", Json.create(true))+ new AttributeEvent($roomEvent.getId(), "presenceDetected", Json .createNull()));enddiff --git a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovyindex ffc6d5c4d..f9963d37e 100644--- a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy+++ b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy@@ -82,4 +82,8 @@ trait ManagerContainerTrait extends ContainerTrait {clockConsumer.call(engine.sessionClock as PseudoClockScheduler)}+ static long getClockTimeOf(RulesEngine engine) {+ (engine.sessionClock as PseudoClockScheduler).currentTime+ }+}diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovyindex 98de03845..0307fa6bd 100644--- a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy@@ -76,87 +76,6 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTraistopContainer(container)}- def "Presence Detection"() {-- given: "the container environment is started"- enablePseudoClock()- def conditions = new PollingConditions(timeout: 10, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainer(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-- expect: "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- }-- and: "the presence latch of the room should not be set"- def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)- assert !livingRoomAsset.getAttribute("presenceDetected").get().valueAsBoolean-- and: "the presence latch of the other room should not be set"- def otherLivingRoomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)- assert !otherLivingRoomAsset.getAttribute("presenceDetected").get().valueAsBoolean-- and: "several presence sensor events are triggered in the room"- for (i in 0..2) {- def livingroomPresenceChange = new AttributeEvent(- managerDemoSetup.apartment1LivingroomId, "presenceSensor", Json.create(true)- )- assetProcessingService.sendAttributeEvent(livingroomPresenceChange)- conditions.eventually {- // Wait until we have the facts- assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A + 1 + i- }- withClockOf(customerAEngine) { it.advanceTime(2, MINUTES) }- }-- and: "several presence sensor events are triggered in the other room (but not enough to trigger 'detection')"- for (i in 0..2) {- def livingroomPresenceChange = new AttributeEvent(- managerDemoSetup.apartment1LivingroomId, "presenceSensor", Json.create(true)- )- assetProcessingService.sendAttributeEvent(livingroomPresenceChange)- conditions.eventually {- // Wait until we have the facts- assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A + 4 + i- }- withClockOf(customerAEngine) { it.advanceTime(10, MINUTES) }- }-- and: "the presence latch of the room should be set"- conditions.eventually {- def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)- assert asset.getAttribute("presenceDetected").get().valueAsBoolean- }-- and: "the presence latch of the other room should NOT be set"- conditions.eventually {- def asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)- assert !asset.getAttribute("presenceDetected").get().valueAsBoolean- }-- when: "time is advanced enough to trigger event expiration"- withClockOf(customerAEngine) { it.advanceTime(1, HOURS) }-- 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- }-- cleanup: "the server should be stopped"- disablePseudoClock()- stopContainer(container)- }-def "Vacation Mode"() {given: "the container environment is started"diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentPresenceDetectionTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentPresenceDetectionTest.groovynew file mode 100644index 000000000..66e6821aa--- /dev/null+++ b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentPresenceDetectionTest.groovy@@ -0,0 +1,202 @@+package org.openremote.test.rules++import elemental.json.Json+import elemental.json.JsonType+import org.openremote.manager.server.asset.AssetProcessingService+import org.openremote.manager.server.asset.AssetStorageService+import org.openremote.manager.server.rules.RulesEngine+import org.openremote.manager.server.rules.RulesService+import org.openremote.manager.server.setup.SetupService+import org.openremote.manager.server.setup.builtin.KeycloakDemoSetup+import org.openremote.manager.server.setup.builtin.ManagerDemoSetup+import org.openremote.model.AttributeEvent+import org.openremote.test.ManagerContainerTrait+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_CUSTOMER_A++class ApartmentPresenceDetectionTest extends Specification implements ManagerContainerTrait {++ def "Set and clear presence detection timestamp depending on motion sensor"() {++ given: "the container environment is started"+ enablePseudoClock()+ def conditions = new PollingConditions(timeout: 5, delay: 1)+ def serverPort = findEphemeralPort()+ def container = startContainer(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++ expect: "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+ }++ 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 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: "several presence sensor events are triggered in the room"+ double expectedPresenceTimestampStart = getClockTimeOf(customerAEngine)+ for (i in 0..2) {+ def motionSensorTrigger = new AttributeEvent(+ managerDemoSetup.apartment1LivingroomId, "motionSensor", Json.create(true)+ )+ assetProcessingService.sendAttributeEvent(motionSensorTrigger)+ conditions.eventually {+ // Wait until we have the facts+ assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A + 1 + i+ }+ withClockOf(customerAEngine) { it.advanceTime(2, MINUTES) }+ }+ double expectedPresenceTimestampEnd = getClockTimeOf(customerAEngine)++ then: "the presence detected timestamp of the room should be set"+ conditions.eventually {+ def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)+ def presenceDetectedTimestamp = asset.getAttribute("presenceDetected").get().value.asNumber()+ assert presenceDetectedTimestamp > expectedPresenceTimestampStart && presenceDetectedTimestamp < expectedPresenceTimestampEnd+ }++ when: "several presence sensor events are triggered in the other room (but not enough to trigger 'detection')"+ for (i in 0..2) {+ def motionSensorTrigger = new AttributeEvent(+ managerDemoSetup.apartment2LivingroomId, "motionSensor", Json.create(true)+ )+ assetProcessingService.sendAttributeEvent(motionSensorTrigger)+ conditions.eventually {+ // Wait until we have the facts+ assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A + 4 + i+ }+ withClockOf(customerAEngine) { it.advanceTime(10, MINUTES) }+ }++ then: "the presence detected timestamp of the other room should NOT be set"+ conditions.eventually {+ def asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)+ assert asset.getAttribute("presenceDetected").get().value.getType() == JsonType.NULL+ }++ and: "meanwhile presence detected timestamp of the first room should have been cleared"+ conditions.eventually {+ def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)+ assert asset.getAttribute("presenceDetected").get().value.getType() == JsonType.NULL+ }++ when: "time is advanced enough to trigger event expiration"+ withClockOf(customerAEngine) { it.advanceTime(1, HOURS) }++ 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+ }++ cleanup: "the server should be stopped"+ disablePseudoClock()+ stopContainer(container)+ }++ def "Set and clear presence detection timestamp depending on motion counter"() {++ given: "the container environment is started"+ enablePseudoClock()+ def conditions = new PollingConditions(timeout: 5, delay: 1)+ def serverPort = findEphemeralPort()+ def container = startContainer(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++ expect: "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+ }++ 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 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: "the motion counter sensor of the room is incremented"+ double expectedPresenceTimestampStart = getClockTimeOf(customerAEngine)+ for (i in 0..2) {+ def motionCounterIncrement = new AttributeEvent(+ managerDemoSetup.apartment1LivingroomId, "motionCounter", Json.create(i+1)+ )+ assetProcessingService.sendAttributeEvent(motionCounterIncrement)+ conditions.eventually {+ // Wait until we have the facts+ assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A + 1 + i+ }+ withClockOf(customerAEngine) { it.advanceTime(2, MINUTES) }+ }+ double expectedPresenceTimestampEnd = getClockTimeOf(customerAEngine)++ then: "the presence detected timestamp of the room should be set"+ conditions.eventually {+ def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)+ def presenceDetectedTimestamp = asset.getAttribute("presenceDetected").get().value.asNumber()+ assert presenceDetectedTimestamp > expectedPresenceTimestampStart && presenceDetectedTimestamp < expectedPresenceTimestampEnd+ }++ when: "the motion counter sensor in the other room is incremented (but not enough to trigger 'detection')"+ for (i in 0..2) {+ def motionCounterIncrement = new AttributeEvent(+ managerDemoSetup.apartment2LivingroomId, "motionCounter", Json.create(i+1)+ )+ assetProcessingService.sendAttributeEvent(motionCounterIncrement)+ conditions.eventually {+ // Wait until we have the facts+ assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A + 4 + i+ }+ withClockOf(customerAEngine) { it.advanceTime(10, MINUTES) }+ }++ then: "the presence detected timestamp of the other room should NOT be set"+ conditions.eventually {+ def asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)+ assert asset.getAttribute("presenceDetected").get().value.getType() == JsonType.NULL+ }++ and: "meanwhile presence detected timestamp of the first room should have been cleared"+ conditions.eventually {+ def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)+ assert asset.getAttribute("presenceDetected").get().value.getType() == JsonType.NULL+ }++ when: "time is advanced enough to trigger event expiration"+ withClockOf(customerAEngine) { it.advanceTime(1, HOURS) }++ 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+ }++ cleanup: "the server should be stopped"+ disablePseudoClock()+ stopContainer(container)+ }++}diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovyindex fb85bfacf..ddbb06d82 100644--- a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy@@ -96,8 +96,9 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerattachRuleExecutionLogger(rulesImport.apartment3Engine, apartment3EngineFiredRules)and: "an attribute event is pushed into the system for an attribute with RULE_STATE meta set to true"+ def presenceDetectedTimestamp = System.currentTimeMillis()def apartment1LivingRoomPresenceDetectedChange = new AttributeEvent(- managerDemoSetup.apartment1LivingroomId, "presenceDetected", Json.create(true)+ managerDemoSetup.apartment1LivingroomId, "presenceDetected", Json.create(presenceDetectedTimestamp))assetProcessingService.sendAttributeEvent(apartment1LivingRoomPresenceDetectedChange)@@ -145,7 +146,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "an attribute event with the same value as current value is pushed into the system"resetRuleExecutionLoggers()apartment1LivingRoomPresenceDetectedChange = new AttributeEvent(- managerDemoSetup.apartment1LivingroomId, "presenceDetected", Json.create(true)+ managerDemoSetup.apartment1LivingroomId, "presenceDetected", Json.create(presenceDetectedTimestamp))assetProcessingService.sendAttributeEvent(apartment1LivingRoomPresenceDetectedChange)@@ -190,7 +191,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerand: "an apartment 3 living room attribute event occurs"def apartment3LivingRoomPresenceDetectedChange = new AttributeEvent(- managerDemoSetup.apartment3LivingroomId, "presenceDetected", Json.create(true)+ managerDemoSetup.apartment3LivingroomId, "presenceDetected", Json.create(System.currentTimeMillis()))assetProcessingService.sendAttributeEvent(apartment3LivingRoomPresenceDetectedChange)@@ -201,7 +202,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassert customerAEngineFiredRules.size() == 2assert customerAEngineFiredRules.containsAll(["All", "All changed"])assert smartHomeEngineFiredRules.size() == 5- assert smartHomeEngineFiredRules.containsAll(["Living Room All", "Current Asset Update", "Parent Type Residence", "Asset Type Room", "Boolean Attributes"])+ assert smartHomeEngineFiredRules.containsAll(["Living Room All", "Current Asset Update", "Parent Type Residence", "Asset Type Room", "JSON Number value types"])assert apartment3EngineFiredRules.size() == 2assert apartment3EngineFiredRules.containsAll(["All", "All changed"])assert apartment1EngineFiredRules.size() == 0diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovyindex d034e02eb..f449072d2 100644--- a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy@@ -96,7 +96,7 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerConta}when: "the clock is advanced by a few seconds"- withClockOf(globalEngine) { it.advanceTime(8, SECONDS) }+ withClockOf(globalEngine) { it.advanceTime(10, SECONDS) }// TODO Weird behavior of timer rules, pseudo clock, and active mode: More than 5 seconds is needed to fire rule twicethen: "the rule engines should have fired the timed execution rule in the background"diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.javaindex bd06fae35..4856589d2 100644--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java@@ -19,6 +19,7 @@*/package org.openremote.model.asset;+import elemental.json.JsonType;import elemental.json.JsonValue;import org.openremote.model.AttributeEvent;import org.openremote.model.AttributeRef;@@ -217,6 +218,10 @@ public abstract class AbstractAssetUpdate {return attribute.getValue();}+ public boolean isValueNull() {+ return attribute.getValue().getType() == JsonType.NULL;+ }+public String getAttributeName() {return attribute.getName();}@@ -275,6 +280,7 @@ public abstract class AbstractAssetUpdate {return getClass().getSimpleName() + "{" +"id='" + getId() + '\'' +", name='" + getName() + '\'' ++ ", parentName='" + getParentName() + '\'' +", typeString='" + getType() + '\'' +", attributeName='" + getAttributeName() + '\'' +", attributeType=" + getAttributeType() +diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.javaindex 2cdf64858..f75118790 100644--- a/model/src/main/java/org/openremote/model/asset/Asset.java+++ b/model/src/main/java/org/openremote/model/asset/Asset.java@@ -135,7 +135,7 @@ import static org.openremote.model.asset.AssetAttribute.Functions.*;"id": "bzlRiJmSSMCl8HIUt9-lMg","version": 0,"createdOn": 1489042784157,- "name": "Livingroom",+ "name": "Living Room","type": "urn:openremote:asset:room","parentId": "B0x8ZOqZQHGjq_l0RxAJBA","parentName": "Apartment 1",@@ -162,7 +162,7 @@ import static org.openremote.model.asset.AssetAttribute.Functions.*;"name": "Livingroom Thermostat","type": "urn:openremote:asset:thing","parentId": "bzlRiJmSSMCl8HIUt9-lMg",- "parentName": "Livingroom",+ "parentName": "Living Room","parentType": "urn:openremote:asset:room","realmId": "c38a3fdf-9d74-4dac-940c-50d3dce1d248","tenantRealm": "customerA",