Skip to content

armgit / core

Public Imported from GitHub
0

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

Shows problems with inserting custom facts into knowledge session. Added AWAY state test based on vacation's sounter.

Michal Rutka7b78766bb325
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 84c3b8ae6..97d9e841c 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
@@ -363,6 +363,16 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
).add(
new MetaItem(AssetMeta.RULE_STATE, Json.create(true))
)
+ ),
+ new AssetAttribute( "lastScene", AttributeType.STRING, Json.create("NIGHT"))
+ .setMeta(
+ new Meta().add(
+ new MetaItem(AssetMeta.LABEL, Json.create("Current scene"))
+ ).add(
+ new MetaItem(AssetMeta.DESCRIPTION, Json.create("The scene which is currently active"))
+ ).add(
+ new MetaItem(AssetMeta.RULE_STATE, Json.create(true))
+ )
)
);
apartment1.setAttributeList(apartment1Attributes);
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 5b314fe08..b32345807 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
@@ -64,5 +64,10 @@ public class RulesDemoSetup extends AbstractManagerSetup {
Ruleset ruleset = new TenantRuleset("Demo Apartment - Vacation Mode", keycloakDemoSetup.customerATenant.getId(), rules);
apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();
}
+ try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentLHSClockCustomFact.drl")) {
+ String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));
+ Ruleset ruleset = new TenantRuleset("Demo Apartment - Clock Custom Fact", keycloakDemoSetup.customerBTenant.getId(), rules);
+ apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();
+ }
}
}
diff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentLHSClockCustomFact.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentLHSClockCustomFact.drl
new file mode 100644
index 000000000..13a8688a5
--- /dev/null
+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentLHSClockCustomFact.drl
@@ -0,0 +1,63 @@
+package org.openremote.test.rules;
+
+import org.openremote.model.*;
+import org.openremote.model.asset.*
+import elemental.json.Json;
+
+import java.util.*
+import java.time.DayOfWeek
+import java.time.LocalTime
+import java.time.LocalDateTime
+import java.time.Instant
+import java.time.ZoneId
+import java.time.format.TextStyle;
+import java.util.Locale;
+
+
+global java.util.logging.Logger LOG;
+global org.openremote.model.rules.Assets assets;
+
+declare CustomClock5s
+ @role(event)
+// @expires(45s)
+ clock: LocalDateTime
+ dow: String
+ dowNext: String
+ dowi: int
+end
+
+rule "Set custom clock fields"
+ timer (cron: 0/5 * * * * ? *)
+then
+ CustomClock5s cc = new CustomClock5s();
+
+ Instant instant = Instant.ofEpochMilli( drools.getWorkingMemory().getSessionClock().getCurrentTime() );
+ LocalDateTime res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
+ cc.setClock(res);
+
+ cc.setDow( cc.getClock().getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.ROOT) );
+ cc.setDowNext( cc.getClock().getDayOfWeek().plus(1).getDisplayName(TextStyle.SHORT, Locale.ROOT) );
+ cc.setDowi( cc.getClock().getDayOfWeek().getValue() );
+
+ LOG.info("@"+cc.toString());
+ insert(cc);
+end
+
+rule "Act on clock"
+// TODO There is fundamental problem in the rule engine. This rule is never executed without delay. This is wrong.
+// timer(int: 1s)
+when
+ $c: CustomClock5s()
+then
+ LOG.info("@"+(new java.util.Date(drools.getWorkingMemory().getSessionClock().getCurrentTime())).toString());
+end
+
+rule "Just to be sure"
+// TODO There is fundamental problem in the rule engine. This rule is never executed without delay. This is wrong.
+// timer(int: 1s)
+when
+ $c: CustomClock5s($cl: clock)
+ CustomClock5s(clock != $cl, this after $c)
+then
+ retract($c);
+end
diff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentVacationMode.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentVacationMode.drl
index bd22d34e8..bc7d79108 100644
--- a/manager/server/src/main/resources/demo/rules/DemoApartmentVacationMode.drl
+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentVacationMode.drl
@@ -12,10 +12,32 @@ rule "Decrement vacation days every day 1 minute after midnight until vacation i
timer (cron: 0 1 0 1/1 * ? *)
when
// Vacation days are more than zero, which means vacation mode is enabled
- $s: AssetState(attributeName == "vacationDays", type == AssetType.RESIDENCE, value.asNumber() > 0 )
+ AssetState($ref: attributeRef, attributeName == "vacationDays", type == AssetType.RESIDENCE, $val: value.asNumber() > 0 )
then
+ LOG.info("Drools SessionClock() is: "+(new java.util.Date(drools.getWorkingMemory().getSessionClock().getCurrentTime())).toString());
// Decrement the vacation days by one
- assets.dispatch(
- new AttributeEvent($s.getAttributeRef(), Json.create($s.getValue().asNumber() -1))
- );
+ assets.dispatch( new AttributeEvent($ref, Json.create($val - 1)) );
+end
+
+rule "Set state to AWAY when on holidays"
+when
+ $a: AssetState(attributeName == "vacationDays", value.asNumber() > 0 )
+ AssetState(attributeName == "lastScene", $ref: attributeRef, value.asString() != "AWAY")
+then
+ assets.dispatch( new AttributeEvent($ref, Json.create("AWAY")) );
+end
+
+rule "Set state to HOME when not on holidays"
+timer(int: 7h) // At morning
+when
+ $a: AssetState(attributeName == "vacationDays", value.asNumber() == 0 )
+ AssetState(attributeName == "lastScene", $ref: attributeRef, value.asString() != "HOME")
+then
+ assets.dispatch( new AttributeEvent($ref, Json.create("HOME")) );
+end
+
+rule "Echo asset state" // to see what states are send to the engine
+salience 10
+when AssetState()
+then
end
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.groovy
index c3bf3eb6c..cd3ad008c 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
@@ -12,9 +12,11 @@ import org.openremote.model.AttributeEvent
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
+import spock.lang.Ignore
import static java.util.concurrent.TimeUnit.*
import static org.openremote.model.asset.Asset.getAttribute
+import static org.openremote.test.RulesTestUtil.attachRuleExecutionLogger
class ApartmentActionsTest extends Specification implements ManagerContainerTrait {
@@ -41,9 +43,9 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
and: "the demo attributes marked with RULE_STATE = true meta should be inserted into the engines"
conditions.eventually {
- assert rulesService.assetStates.size() == 9
- assert customerAEngine.assetStates.size() == 9
- assert customerAEngine.knowledgeSession.factCount == 9
+ assert rulesService.assetStates.size() == 10
+ assert customerAEngine.assetStates.size() == 10
+ assert customerAEngine.knowledgeSession.factCount == 10
}
and: "the room lights in an apartment to be on"
@@ -58,7 +60,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
then: "the room lights in the apartment should be off"
conditions.eventually {
- assert customerAEngine.knowledgeSession.factCount == 10
+ assert customerAEngine.knowledgeSession.factCount == 11
livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
assert !livingRoomAsset.getAttribute("lightSwitch").get().valueAsBoolean
}
@@ -68,7 +70,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
then: "event expired"
conditions.eventually {
- assert customerAEngine.knowledgeSession.factCount == 9
+ assert customerAEngine.knowledgeSession.factCount == 10
}
cleanup: "stop the container"
@@ -95,7 +97,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
customerAEngine = rulesService.tenantDeployments.get(keycloakDemoSetup.customerATenant.id)
assert customerAEngine != null
assert customerAEngine.isRunning()
- assert customerAEngine.knowledgeSession.factCount == 9
+ assert customerAEngine.knowledgeSession.factCount == 10
}
and: "the presence latch of the room should not be set"
@@ -114,7 +116,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
assetProcessingService.sendAttributeEvent(livingroomPresenceChange)
conditions.eventually {
// Wait until we have the facts
- assert customerAEngine.knowledgeSession.factCount == 10 + i
+ assert customerAEngine.knowledgeSession.factCount == 11 + i
}
withClockOf(customerAEngine) { it.advanceTime(2, MINUTES) }
}
@@ -127,7 +129,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
assetProcessingService.sendAttributeEvent(livingroomPresenceChange)
conditions.eventually {
// Wait until we have the facts
- assert customerAEngine.knowledgeSession.factCount == 13 + i
+ assert customerAEngine.knowledgeSession.factCount == 14 + i
}
withClockOf(customerAEngine) { it.advanceTime(10, MINUTES) }
}
@@ -149,7 +151,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
then: "the events should have been expired and retracted automatically from the knowledge session"
conditions.eventually {
- assert customerAEngine.knowledgeSession.factCount == 9
+ assert customerAEngine.knowledgeSession.factCount == 10
}
cleanup: "the server should be stopped"
@@ -161,7 +163,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
given: "the container environment is started"
enablePseudoClock()
- def conditions = new PollingConditions(timeout: 10, delay: 1)
+ def conditions = new PollingConditions(timeout: 60, delay: 1)
def serverPort = findEphemeralPort()
def container = startContainer(defaultConfig(serverPort), defaultServices())
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
@@ -180,9 +182,9 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
and: "the demo attributes marked with RULE_STATE = true meta should be inserted into the engines"
conditions.eventually {
- assert rulesService.assetStates.size() == 9
- assert customerAEngine.assetStates.size() == 9
- assert customerAEngine.knowledgeSession.factCount == 9
+ assert rulesService.assetStates.size() >= 10
+ assert customerAEngine.assetStates.size() >= 10
+ assert customerAEngine.knowledgeSession.factCount >= 10
}
when: "the vacation days are set to 5"
@@ -194,6 +196,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
assert asset.getAttribute("vacationDays").get().valueAsInteger == 5
+ assert asset.getAttribute("lastScene").get().valueAsString == "AWAY"
}
when: "time advanced to the next day, which should trigger the cron rule"
@@ -203,6 +206,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
assert asset.getAttribute("vacationDays").get().valueAsInteger == 4
+ assert asset.getAttribute("lastScene").get().valueAsString == "AWAY"
}
when: "time advanced again (to test that the rule only fires once per day)"
@@ -212,6 +216,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
new PollingConditions(initialDelay: 2).eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
assert asset.getAttribute("vacationDays").get().valueAsInteger == 4
+ assert asset.getAttribute("lastScene").get().valueAsString == "AWAY"
}
expect: "the remaining vacation days to be decremented with each passing day"
@@ -221,15 +226,97 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
remainingDays--
withClockOf(customerAEngine) { it.advanceTime(1, DAYS) }
-
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
assert asset.getAttribute("vacationDays").get().valueAsInteger == remainingDays
+ assert asset.getAttribute("lastScene").get().valueAsString == "AWAY"
}
}
+ withClockOf(customerAEngine) { it.advanceTime(8, HOURS) }
+ conditions.eventually {
+ def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert asset.getAttribute("lastScene").get().valueAsString == "HOME"
+ }
+
+ cleanup: "the server should be stopped"
+ disablePseudoClock()
+ stopContainer(container)
+ }
+
+ // The same behaviour is with the realtime and pseudo clock.
+ // TODO see below for explanation.
+ @Ignore
+ def "Test Custom Fact Clock Real"() {
+
+ given: "the container environment is started"
+ def conditions = new PollingConditions(timeout: 60, delay: 1)
+ def serverPort = findEphemeralPort()
+ def container = startContainer(defaultConfig(serverPort), defaultServices())
+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
+ def rulesService = container.getService(RulesService.class)
+ RulesDeployment customerBEngine
+ List<String> customerBEngineFiredRules = []
+
+ expect: "the rule engines to become available and be running"
+ conditions.eventually {
+ customerBEngine = rulesService.tenantDeployments.get(keycloakDemoSetup.customerBTenant.id)
+ assert customerBEngine != null
+ assert customerBEngine.isRunning()
+ }
+
+ when: "check if the custom clock is running"
+ attachRuleExecutionLogger(customerBEngine, customerBEngineFiredRules)
+ Thread.sleep(16000)
+
+ then: "Check how many rules were triggered"
+ conditions.eventually {
+ assert customerBEngineFiredRules.size() >= 8 // The >= to be good even when we have slower machine
+ }
+
+ cleanup: "the server should be stopped"
+ stopContainer(container)
+ }
+
+ // This test shows a fundamental problem with current rule's engine. Custom facts inserted into the knowledge
+ // session are not detected on the current delta and dissapear. Only when a rule has the delay in form of timer(int: x)
+ // then they are triggered. This means that one must controll timing and racing by hand instead of Drools.
+ // TODO fix this otherwise impossible to work on rules
+ @Ignore
+ def "Test Custom Fact Clock Pseudo"() {
+
+ given: "the container environment is started"
+ enablePseudoClock()
+ def conditions = new PollingConditions(timeout: 60, 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)
+ RulesDeployment customerBEngine
+ List<String> customerBEngineFiredRules = []
+
+ expect: "the rule engines to become available and be running"
+ conditions.eventually {
+ customerBEngine = rulesService.tenantDeployments.get(keycloakDemoSetup.customerBTenant.id)
+ assert customerBEngine != null
+ assert customerBEngine.isRunning()
+ }
+
+ when: "check if the custom clock is running"
+ attachRuleExecutionLogger(customerBEngine, customerBEngineFiredRules)
+ withClockOf(customerBEngine) { it.advanceTime(15, SECONDS) }
+ Thread.sleep(16000)
+
+ then: "Check how many rules were triggered"
+ conditions.eventually {
+ assert customerBEngineFiredRules.size() == 8
+ }
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.groovy
index 9983ab063..288d61249 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
@@ -80,11 +80,11 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
and: "the demo attributes marked with RULE_STATE = true meta should be inserted into the engines"
conditions.eventually {
- assert rulesService.assetStates.size() == 9
- assert rulesImport.globalEngine.assetStates.size() == 9
+ assert rulesService.assetStates.size() == 10
+ assert rulesImport.globalEngine.assetStates.size() == 10
assert rulesImport.masterEngine.assetStates.size() == 0
- assert rulesImport.customerAEngine.assetStates.size() == 9
- assert rulesImport.apartment1Engine.assetStates.size() == 5
+ assert rulesImport.customerAEngine.assetStates.size() == 10
+ assert rulesImport.apartment1Engine.assetStates.size() == 6
assert rulesImport.apartment3Engine.assetStates.size() == 2
}
@@ -177,7 +177,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
smartHomeEngine = rulesService.assetDeployments.get(managerDemoSetup.smartHomeId)
assert smartHomeEngine != null
assert smartHomeEngine.isRunning()
- assert smartHomeEngine.assetStates.size() == 9
+ assert smartHomeEngine.assetStates.size() == 10
assert smartHomeEngine.allRulesets.length == 1
assert smartHomeEngine.allRulesets[0].enabled
assert smartHomeEngine.allRulesets[0].name == "Some smart home asset rules"
@@ -246,7 +246,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
rulesImport.globalEngine = rulesService.globalDeployment
assert rulesImport.globalEngine != null
assert rulesImport.globalEngine.isRunning()
- assert rulesImport.globalEngine.assetStates.size() == 9
+ assert rulesImport.globalEngine.assetStates.size() == 10
assert rulesImport.globalEngine.allRulesets.length == 2
assert rulesImport.globalEngine.allRulesets[1].enabled
assert rulesImport.globalEngine.allRulesets[1].name == "Some global test rules"