Skip to content

armgit / core

Public Imported from GitHub
0

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

Drools pseudo clock for reliable testing of rules

Michal Rutkab23718bb9ec8
diff --git a/agent/src/main/java/org/openremote/agent/AgentService.java b/agent/src/main/java/org/openremote/agent/AgentService.java
index 6de00f94d..1ce27bf99 100644
--- a/agent/src/main/java/org/openremote/agent/AgentService.java
+++ b/agent/src/main/java/org/openremote/agent/AgentService.java
@@ -17,6 +17,7 @@ public class AgentService implements ContainerService {
final protected InputStream deploymentXml;
final protected CommandBuilder commandBuilder;
final protected RulesProvider rulesProvider;
+ final protected String droolsClock;
protected AgentContext agentContext;
@@ -24,6 +25,14 @@ public class AgentService implements ContainerService {
this.deploymentXml = deploymentXml;
this.commandBuilder = commandBuilder;
this.rulesProvider = rulesProvider;
+ this.droolsClock = "realtime";
+ }
+
+ public AgentService(InputStream deploymentXml, CommandBuilder commandBuilder, RulesProvider rulesProvider, String droolsClock) {
+ this.deploymentXml = deploymentXml;
+ this.commandBuilder = commandBuilder;
+ this.rulesProvider = rulesProvider;
+ this.droolsClock = droolsClock;
}
@Override
@@ -35,7 +44,7 @@ public class AgentService implements ContainerService {
new InMemorySensorStateHandler(),
rulesProvider
);
- agentContext = new AgentContext("OpenRemoteAgent123", deployment);
+ agentContext = new AgentContext("OpenRemoteAgent123", deployment, droolsClock);
}
@Override
diff --git a/agent/src/main/java/org/openremote/agent/command/builtin/DateTimeCommand.java b/agent/src/main/java/org/openremote/agent/command/builtin/DateTimeCommand.java
index f50ab4a4a..684b879aa 100644
--- a/agent/src/main/java/org/openremote/agent/command/builtin/DateTimeCommand.java
+++ b/agent/src/main/java/org/openremote/agent/command/builtin/DateTimeCommand.java
@@ -37,6 +37,7 @@ public class DateTimeCommand implements PushCommand, Runnable {
private String command;
private SimpleDateFormat dateFormatter;
private SunriseSunsetCalculator calculator;
+ private Calendar now;
/**
* The polling interval which is used for the sensor update thread
@@ -96,19 +97,21 @@ public class DateTimeCommand implements PushCommand, Runnable {
}
}
+ public long getTime() { return now.getTimeInMillis(); }
+
public String calculateData() {
return calculateData("");
}
public String calculateData(String customTime) {
- // customTime should be in format "hhhh:mm:ss" or "" for current time.
- // hours filed can be more than one day. For example "25:00:00" is 1:00:00 the next day.
- Calendar now = Calendar.getInstance(this.timezone);
+ // customTime should be in format "hhhh[:mm[:ss]]" or "" for current time.
+ // hours filed can be more than one day. For example "25" is 1 the following day.
+ now = Calendar.getInstance(this.timezone);
if(customTime != null && !customTime.isEmpty()) {
String[] timeParts = customTime.split(":");
now.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeParts[0]));
- now.set(Calendar.MINUTE, Integer.parseInt(timeParts[1]));
- now.set(Calendar.SECOND, Integer.parseInt(timeParts[2]));
+ now.set(Calendar.MINUTE, timeParts.length>1 ? Integer.parseInt(timeParts[1]) : 0);
+ now.set(Calendar.SECOND, timeParts.length>2 ? Integer.parseInt(timeParts[2]) : 0);
}
if (command.equalsIgnoreCase("date")) {
return dateFormatter.format(now.getTime());
diff --git a/agent/src/main/java/org/openremote/agent/context/AgentContext.java b/agent/src/main/java/org/openremote/agent/context/AgentContext.java
index c37f9b376..b406b2cc9 100644
--- a/agent/src/main/java/org/openremote/agent/context/AgentContext.java
+++ b/agent/src/main/java/org/openremote/agent/context/AgentContext.java
@@ -18,12 +18,20 @@ public class AgentContext {
final protected String agentID;
final protected Deployment deployment;
+ final protected String droolsClock;
private volatile Boolean shutdownInProgress = false;
public AgentContext(String agentID, Deployment deployment) {
this.agentID = agentID;
this.deployment = deployment;
+ this.droolsClock = "realtime";
+ }
+
+ public AgentContext(String agentID, Deployment deployment, String droolsClock) {
+ this.agentID = agentID;
+ this.deployment = deployment;
+ this.droolsClock = droolsClock;
}
public String getAgentID() {
@@ -38,6 +46,8 @@ public class AgentContext {
return getDeployment().getCommands();
}
+ public String getDroolsClock() { return droolsClock; }
+
public synchronized void start() {
if (shutdownInProgress)
return;
diff --git a/agent/src/main/java/org/openremote/agent/rules/RuleEngine.java b/agent/src/main/java/org/openremote/agent/rules/RuleEngine.java
index cdec24e2c..4af7b3b3c 100644
--- a/agent/src/main/java/org/openremote/agent/rules/RuleEngine.java
+++ b/agent/src/main/java/org/openremote/agent/rules/RuleEngine.java
@@ -20,6 +20,7 @@
*/
package org.openremote.agent.rules;
+import org.drools.core.ClockType;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
@@ -27,7 +28,6 @@ import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
-import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.io.Resource;
@@ -76,11 +76,6 @@ public class RuleEngine {
.setDefault(true)
.setEqualsBehavior(EqualityBehaviorOption.EQUALITY)
.setEventProcessingMode(EventProcessingOption.STREAM);
- KieSessionModel kieSessionModel = kieBaseModel.newKieSessionModel("OpenRemoteKSession")
- .setDefault(true)
- .setType(KieSessionModel.KieSessionType.STATEFUL);
- // .setClockType(ClockTypeOption.get("pseudo")); // TODO: set in on the fly for tests
-
KieFileSystem kfs = kieServices.newKieFileSystem();
kfs.writeKModuleXML(kieModuleModel.toXML());
@@ -96,6 +91,10 @@ public class RuleEngine {
// Use this option to ensure timer rules are fired even in passive mode (triggered by fireAllRules.
// This ensures compatibility with the behaviour of previously used Drools 5.1
kieSessionConfiguration.setOption(TimedRuleExectionOption.YES);
+ if(agentContext.getDroolsClock().equals("pseudo")) {
+ kieSessionConfiguration.setOption(ClockTypeOption.get("pseudo"));
+ }
+
knowledgeSession = kb.newKieSession(kieSessionConfiguration, null);
switchFacade = new SwitchFacade();
diff --git a/agent/src/test/groovy/org/openremote/test/rules/ClimateControlTest.groovy b/agent/src/test/groovy/org/openremote/test/rules/ClimateControlTest.groovy
index aa2c09cdb..f61dbca55 100644
--- a/agent/src/test/groovy/org/openremote/test/rules/ClimateControlTest.groovy
+++ b/agent/src/test/groovy/org/openremote/test/rules/ClimateControlTest.groovy
@@ -2,6 +2,7 @@ package org.openremote.test.rules
import org.kie.api.KieServices
import org.kie.api.io.Resource
+import org.kie.api.runtime.KieSession
import org.openremote.agent.AgentService
import org.openremote.agent.rules.RulesProvider
import org.openremote.test.ContainerTrait
@@ -14,7 +15,6 @@ import java.util.stream.Stream
class ClimateControlTest extends Specification implements ContainerTrait {
- @Ignore
def "Climate control basic test template"() {
given: "a deployment with commands and sensors"
@@ -36,10 +36,12 @@ class ClimateControlTest extends Specification implements ContainerTrait {
and: "the started server"
def testCommandBuilder = new CustomTimeCommandBuilder();
+ def time = { $time -> testCommandBuilder.currentTime = $time }
def agentService = new AgentService(
deploymentXml,
testCommandBuilder,
- rulesProvider
+ rulesProvider,
+ "pseudo"
)
def serverPort = findEphemeralPort()
def container = startContainer(defaultConfig(serverPort), [agentService])
@@ -48,6 +50,9 @@ class ClimateControlTest extends Specification implements ContainerTrait {
def command = { $name, $arg -> agentService.getContext().getCommands().execute($name, $arg) }
def conditions = new PollingConditions(timeout: 10, initialDelay: 0.25)
+ KieSession ksession = agentService.getContext().getDeployment().getRuleEngine().getKnowledgeSession()
+ testCommandBuilder.setClock(ksession.getSessionClock())
+
// TODO Write tests
cleanup: "the server should be stopped"
@@ -75,22 +80,19 @@ class ClimateControlTest extends Specification implements ContainerTrait {
and: "the started server"
def testCommandBuilder = new CustomTimeCommandBuilder();
- testCommandBuilder.currentTime = "07:07:00"
def agentService = new AgentService(
deploymentXml,
testCommandBuilder,
- rulesProvider
+ rulesProvider,
+ "pseudo"
)
+ testCommandBuilder.currentTime = "7"
def serverPort = findEphemeralPort()
def container = startContainer(defaultConfig(serverPort), [agentService])
def sensor = { $sensor -> agentService.getContext().queryValue($sensor) }
def command = { $name, $arg -> agentService.getContext().getCommands().execute($name, $arg) }
- // TODO: wait for answer from Drools forum how it should be used. It does not work now.
- // KieSession ksession = agentService.getContext().getDeployment().getRuleEngine().getKnowledgeSession()
- // PseudoClockScheduler clock = new PseudoClockScheduler(ksession)
-
when: "give some time for initialization rules"
def conditions = new PollingConditions(timeout: 10, initialDelay: 0.25)
@@ -152,7 +154,7 @@ class ClimateControlTest extends Specification implements ContainerTrait {
cleanup: "the server should be stopped"
stopContainer(container)
}
-
+
def "Person sense test"() {
given: "a deployment with commands and sensors"
@@ -176,11 +178,12 @@ class ClimateControlTest extends Specification implements ContainerTrait {
and: "the started server"
def testCommandBuilder = new CustomTimeCommandBuilder();
def time = { $time -> testCommandBuilder.currentTime = $time }
- time "8:25:00"
+ time "8:25"
def agentService = new AgentService(
deploymentXml,
testCommandBuilder,
- rulesProvider
+ rulesProvider,
+ "pseudo"
)
def serverPort = findEphemeralPort()
def container = startContainer(defaultConfig(serverPort), [agentService])
@@ -188,6 +191,10 @@ class ClimateControlTest extends Specification implements ContainerTrait {
def sensor = { $sensor -> agentService.getContext().queryValue($sensor) }
def command = { $name, $arg -> agentService.getContext().getCommands().execute($name, $arg) }
+ KieSession ksession = agentService.getContext().getDeployment().getRuleEngine().getKnowledgeSession()
+ testCommandBuilder.setClock(ksession.getSessionClock())
+ time "8:26"
+
when: "Set time before going to office"
def conditions = new PollingConditions(timeout: 10, initialDelay: 0.25)
@@ -207,33 +214,51 @@ class ClimateControlTest extends Specification implements ContainerTrait {
then: "check if heating is in standby"
conditions.eventually {
+ assert sensor("VPRESENCE") == "No"
assert sensor("VHEATING") == "Stand-by"
assert Double.parseDouble(sensor("VHEATINGSETPOINT")) == 19
+ assert sensor("VR1.TEMPERATURE") == "20.0°"
}
+
when: "so go in"
command "FS.PIR", "on"
conditions = new PollingConditions(timeout: 10, initialDelay: 0.25)
then: "see if the arrival is registered"
conditions.eventually {
+ testCommandBuilder.incDroolsClock()
assert sensor("VNEXTACTION") == "Departure"
assert sensor("VATA") == "10:00"
assert sensor("VPERSONSENSE") == "0"
assert sensor("VPRESENCE") == "Yes"
- assert sensor("FS.PIR") == "off"
assert sensor("VHEATING") == "Comfort"
+ assert sensor("VR1.TEMPERATURE") == "20.0°"
+ assert sensor("FS.PIR") == "off"
assert Double.parseDouble(sensor("VHEATINGSETPOINT")) == 20
}
+ when: "Advance time 15m"
+ time "10:15"
+ conditions = new PollingConditions(timeout: 10, initialDelay: 0.25)
+
+ then: "Check if no presence"
+ conditions.eventually {
+ testCommandBuilder.incDroolsClock()
+ assert sensor("VPRESENCE") == "No"
+ assert sensor("VHEATING") == "Stand-by"
+ assert sensor("VR1.TEMPERATURE") == "20.0°"
+ assert Double.parseDouble(sensor("VHEATINGSETPOINT")) == 19
+ }
+
when: "go home at 4PM"
time "16:00:00"
command "FS.PIR", "on"
conditions = new PollingConditions(timeout: 10, initialDelay: 0.25)
- then: "wait for PIR off"
+ then: "wait for presence"
conditions.eventually {
- assert sensor("VPERSONSENSE") == "1"
- assert sensor("FS.PIR") == "off"
+ testCommandBuilder.incDroolsClock()
+ assert sensor("VPERSONSENSETIME") == "16:00:00"
}
when: "Go at midnight adjusting"
@@ -242,11 +267,13 @@ class ClimateControlTest extends Specification implements ContainerTrait {
then: "check departure"
conditions.eventually {
+ testCommandBuilder.incDroolsClock()
assert sensor("VPRESENCE") == "No"
assert sensor("VATD") == "16:00"
assert sensor("VNEXTACTION") == "-"
assert sensor("VHEATING") == "ECO"
assert Double.parseDouble(sensor("VHEATINGSETPOINT")) == 16
+ assert sensor("VR1.TEMPERATURE") == "16.0°"
}
when: "Check updated arrival and departure times"
diff --git a/agent/src/test/groovy/org/openremote/test/rules/CustomTimeCommandBuilder.java b/agent/src/test/groovy/org/openremote/test/rules/CustomTimeCommandBuilder.java
index a8f9b1cb3..019f1e7ae 100644
--- a/agent/src/test/groovy/org/openremote/test/rules/CustomTimeCommandBuilder.java
+++ b/agent/src/test/groovy/org/openremote/test/rules/CustomTimeCommandBuilder.java
@@ -1,5 +1,6 @@
package org.openremote.test.rules;
+import org.drools.core.time.impl.PseudoClockScheduler;
import org.openremote.agent.command.Command;
import org.openremote.agent.command.CommandBuilder;
import org.openremote.agent.command.PullCommand;
@@ -7,6 +8,7 @@ import org.openremote.agent.command.builtin.DateTimeCommand;
import org.openremote.agent.deploy.CommandDefinition;
import org.openremote.agent.sensor.Sensor;
+import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
public class CustomTimeCommandBuilder extends CommandBuilder {
@@ -14,6 +16,20 @@ public class CustomTimeCommandBuilder extends CommandBuilder {
private static final Logger LOG = Logger.getLogger(CustomTimeCommandBuilder.class.getName());
public String currentTime;
+ public long currentTimeL;
+ private PseudoClockScheduler clock;
+
+ public void setClock(PseudoClockScheduler droolsClock) {
+ clock = droolsClock;
+ clock.setStartupTime(currentTimeL);
+ }
+
+ public long incDroolsClock() {
+ if(clock != null) {
+ clock.advanceTime(1, TimeUnit.SECONDS);
+ }
+ return clock.getCurrentTime();
+ }
interface MyCustomCommand extends PullCommand {
@Override
@@ -30,7 +46,12 @@ public class CustomTimeCommandBuilder extends CommandBuilder {
@Override
public String read(Sensor sensor) {
- return dtcmd.calculateData(currentTime);
+ String calc = dtcmd.calculateData(currentTime);
+ if(clock != null){
+ clock.advanceTime(dtcmd.getTime()-clock.getCurrentTime(), TimeUnit.MILLISECONDS);
+ }
+ currentTimeL = dtcmd.getTime();
+ return calc;
}
};
diff --git a/agent/src/test/resources/org/openremote/test/rules/climatecontrol/ClimateControl.drl b/agent/src/test/resources/org/openremote/test/rules/climatecontrol/ClimateControl.drl
index 36d1d3609..a152b82ba 100644
--- a/agent/src/test/resources/org/openremote/test/rules/climatecontrol/ClimateControl.drl
+++ b/agent/src/test/resources/org/openremote/test/rules/climatecontrol/ClimateControl.drl
@@ -81,7 +81,7 @@ when
SensorState(sensorName=="TimerEEE", value!="N/A")
then
LOG.info("Sensor clock is: "+$a+" "+$b+" "+$c+" "+$d);
-// LOG.info("Drools SessionClock() is: "+(new java.util.Date(drools.getWorkingMemory().getSessionClock().getCurrentTime())).toString());
+ LOG.info("Drools SessionClock() is: "+(new java.util.Date(drools.getWorkingMemory().getSessionClock().getCurrentTime())).toString());
end
rule "--PSB: store values"
@@ -612,7 +612,7 @@ then
commands.execute("VPRESENCE","No");
end
-rule "PSB: Absence after 15 min v02"
+rule "PSB: Absence after 15 min v02"
timer(int: 15m)
when
SensorState(sensorName == "VPERSONSENSE", value == "0")
@@ -736,7 +736,7 @@ then
String s = $v.toString();
Double t = java.lang.Math.max(16.0, Double.parseDouble(s.substring(0,s.length()-1))-1); // 1 degree below comfort
commands.execute("VHEATINGSETPOINT", String.format("%.1f",t));
- commands.execute("VR1.TEMPERATURE", s);
+ commands.execute("VR1.TEMPERATURE", s); // But the user is not aware as on display there is comfort
end
rule "-PSB: heating setpoint Comfort"