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
Basic rules service implemented (not tested yet)
Rich Turnerf3b476560610
diff --git a/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateChange.java b/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateChange.javaindex 9d685206d..0e606f9ea 100644--- a/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateChange.java+++ b/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateChange.java@@ -21,19 +21,22 @@ package org.openremote.manager.server.attribute;import elemental.json.JsonValue;import org.openremote.model.Attribute;+import org.openremote.model.AttributeRef;public class AttributeStateChange {protected Object attributeParent;protected Attribute attribute;+ protected AttributeRef attributeRef;protected JsonValue oldValue;protected JsonValue newValue;protected boolean rewind;protected boolean handled;protected boolean error;- public AttributeStateChange(Object attributeParent, Attribute attribute, JsonValue oldValue, JsonValue newValue) {+ public AttributeStateChange(Object attributeParent, Attribute attribute, AttributeRef attributeRef, JsonValue oldValue, JsonValue newValue) {this.attributeParent = attributeParent;this.attribute = attribute;+ this.attributeRef = attributeRef;this.oldValue = oldValue;this.newValue = newValue;}@@ -49,6 +52,10 @@ public class AttributeStateChange {return attributeParent;}+ public AttributeRef getAttributeRef() {+ return attributeRef;+ }+public JsonValue getOldValue() {return oldValue;}@@ -94,4 +101,41 @@ public class AttributeStateChange {public void setHandled(boolean handled) {this.handled = handled;}++ /**+ * Two attribute state changes are considered equal if their attribute ref, old value+ * and new value are equal+ */+ @Override+ public boolean equals(Object o) {+ if (o == null) {+ return false;+ }++ if (o.getClass() != this.getClass()) {+ return false;+ }++ AttributeStateChange that = (AttributeStateChange) o;++ return that.getAttributeRef().equals(this.getAttributeRef()) &&+ that.getOldValue().equals(this.getOldValue()) &&+ that.getNewValue().equals(this.getNewValue());+ }++ @Override+ public int hashCode() {+ return attributeRef.hashCode() + (oldValue != null ? oldValue.hashCode() : 0) + (newValue != null ? newValue.hashCode() : 0);+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "attribute=" + attribute ++ ", oldValue=" + (oldValue != null ? oldValue.asString() : "null") ++ ", newValue=" + (newValue != null ? newValue.asString() : "null") ++ ", handled=" + handled ++ ", error=" + error ++ '}';+ }}diff --git a/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateRouterService.java b/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateRouterService.javaindex c786f2d89..36c40cfc0 100644--- a/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateRouterService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/attribute/AttributeStateRouterService.java@@ -105,10 +105,12 @@ public class AttributeStateRouterService extends RouteBuilder implements ContainAttributeStateChange stateChange = new AttributeStateChange(thing,thingAttribute,+ attributeState.getAttributeRef(),thingAttribute.getValue_TODO_BUG_IN_JAVASCRIPT(),attributeState.getValue());for (int i=0; i<consumers.size(); i++) {+ boolean error = false;AttributeStateConsumerResult result = consumers.get(i).consumeAttributeStateChange(stateChange);if(result == null) {// Assume ok if no result returned@@ -116,6 +118,9 @@ public class AttributeStateRouterService extends RouteBuilder implements Contain}switch (result) {case OK:+ // Check error flag (just in case consumer swallowed any exceptions)+ error = stateChange.isError();+// Check handled status of changeif (stateChange.isHandled()) {// Don't pass this change to any more consumers@@ -126,7 +131,11 @@ public class AttributeStateRouterService extends RouteBuilder implements Containdefault:// TODO: maybe rewind the state change and run through processed consumers in reverse order?LOG.info("Attribute state change consumer returned ERROR result so abandoning further processing of state change");- throw new RuntimeException("Attribute state change consumer return ERROR result");+ error = true;+ }++ if (error) {+ throw new RuntimeException("Attribute state change consumer return ERROR result");}}});diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesProvider.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesProvider.javaindex 821b48ae8..c0da09d22 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesProvider.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesProvider.java@@ -2,6 +2,7 @@ package org.openremote.manager.server.rules;import org.kie.api.KieServices;import org.kie.api.io.Resource;+import org.kie.api.runtime.conf.ClockTypeOption;import java.util.stream.Stream;@@ -9,4 +10,5 @@ public interface RulesProvider {Stream<Resource> getResources(KieServices kieServices);+ ClockTypeOption getClockType();}diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.javaindex e6be48e6a..7c1ea42b1 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java@@ -19,13 +19,48 @@*/package org.openremote.manager.server.rules;+import org.kie.api.KieBase;+import org.kie.api.KieServices;+import org.kie.api.builder.KieBuilder;+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.conf.EqualityBehaviorOption;+import org.kie.api.conf.EventProcessingOption;+import org.kie.api.io.Resource;+import org.kie.api.io.ResourceType;+import org.kie.api.runtime.KieContainer;+import org.kie.api.runtime.KieSession;+import org.kie.api.runtime.KieSessionConfiguration;+import org.kie.api.runtime.conf.TimedRuleExectionOption;+import org.kie.api.runtime.rule.FactHandle;+import org.kie.internal.builder.DecisionTableConfiguration;+import org.kie.internal.builder.DecisionTableInputType;+import org.kie.internal.builder.KnowledgeBuilderFactory;import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.manager.server.attribute.AttributeStateChange;import org.openremote.manager.server.attribute.AttributeStateConsumerResult;import org.openremote.manager.server.attribute.AttributeStateChangeConsumer;+import org.openremote.model.AttributeRef;++import java.util.Collection;+import java.util.HashMap;+import java.util.Map;+import java.util.logging.Level;+import java.util.logging.Logger;public class RulesService implements ContainerService, AttributeStateChangeConsumer {+ private static final Logger LOG = Logger.getLogger(RulesService.class.getName());++ private KieBase kb;+ private KieSession knowledgeSession;+ private Map<AttributeRef, FactHandle> stateSources = new HashMap<>();+ private long currentFactCount;++ private RuleUtil ruleUtil;+@Overridepublic void init(Container container) throws Exception {@@ -38,11 +73,209 @@ public class RulesService implements ContainerService, AttributeStateChangeConsu@Overridepublic void stop(Container container) throws Exception {+ stopEngine();+ }++ protected void stopEngine() {+ LOG.fine("Stopping RuleEngine");+ if (knowledgeSession != null) {+ knowledgeSession.dispose();+ LOG.fine("Knowledge session disposed");+ }++ stateSources.clear();+ kb = null;+ }++ // TODO: Support runtime re-deployment+ public void deploy(RulesProvider rulesProvider) {+ if (rulesProvider == null) {+ return;+ }++ stopEngine();++ KieServices kieServices = KieServices.Factory.get();+ KieModuleModel kieModuleModel = kieServices.newKieModuleModel();++ KieBaseModel kieBaseModel = kieModuleModel.newKieBaseModel("OpenRemoteKBase")+ .setDefault(true)+ .setEqualsBehavior(EqualityBehaviorOption.EQUALITY)+ .setEventProcessingMode(EventProcessingOption.STREAM);+ KieFileSystem kfs = kieServices.newKieFileSystem();+ kfs.writeKModuleXML(kieModuleModel.toXML());++ rulesProvider.getResources(kieServices).forEach(resource -> {+ if (!addResource(resource, kieServices, kfs)) {+ // Fail hard and fast+ LOG.severe("Failed to deploy rules resource '" + resource.getSourcePath() + "' so rules engine won't run");+ throw new RuntimeException();+ }+ }+ );++ KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());++ kb = kieContainer.getKieBase();++ KieSessionConfiguration kieSessionConfiguration = kieServices.newKieSessionConfiguration();+ // 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 (rulesProvider.getClockType() != null) {+ kieSessionConfiguration.setOption(rulesProvider.getClockType());+ }++ knowledgeSession = kb.newKieSession(kieSessionConfiguration, null);++ ruleUtil = new RuleUtil();++ setGlobal("util", ruleUtil);+ setGlobal("JSON", Container.JSON);+ setGlobal("LOG", LOG);++ try {+ RuleExecutionLogger ruleExecutionLogger = new RuleExecutionLogger();+ knowledgeSession.addEventListener(ruleExecutionLogger);+ } catch (Throwable t) {+ throw new RuntimeException(t);+ }++ LOG.info("Rule engine started");+ LOG.info(kieBaseModel.toString());+ knowledgeSession.fireAllRules();}@Overridepublic AttributeStateConsumerResult consumeAttributeStateChange(AttributeStateChange attributeStateChange) {- return null;+ if (kb == null) {+ LOG.fine("No knowledge base configured, skipping processing of: " + attributeStateChange);+ return AttributeStateConsumerResult.OK;+ }++ try {+ long newFactCount;++ // If this fact is not in working memory (considering its equals() method)...+ if (!knowledgeSession.getObjects().contains(attributeStateChange)) {++ // ... update or new insert?+ boolean isUpdate = true;++ // If there already is a fact in wm with the same entity ID and attribute name+ if (stateSources.keySet().contains(attributeStateChange.getAttributeRef())) {+ try {+ // ... retract it from working memory ...+ knowledgeSession.delete(stateSources.get(attributeStateChange.getAttributeRef()));+ } finally {+ // ... and make sure we don't keep a reference to a fact+ stateSources.remove(attributeStateChange.getAttributeRef());+ }+ } else {+ isUpdate = false;+ }++ // Put the fact into wm and remember the handle+ FactHandle handle = knowledgeSession.insert(attributeStateChange);+ stateSources.put(attributeStateChange.getAttributeRef(), handle);++ if (isUpdate) {+ LOG.finest("Inserted: " + attributeStateChange);+ } else {+ LOG.finest("Updated: " + attributeStateChange);+ }++ // TODO: Prevent run away fact creation (not sure how we can do this reliably as facts can be generated in rule RHS)+ // MR: this is heuristic number which comes good for finding facts memory leak in the drl file.+ // problem - when you are not careful then drl can insert new facts till memory exhaustion. As there+ // are usually few 100 facts in drl's I'm working with, putting arbitrary number gives me early feedback+ // that there is potential problem. Perhaps we should think about a better solution to this problem?+ newFactCount = knowledgeSession.getFactCount();+ LOG.finest("New fact count: " + newFactCount);+ if (newFactCount != currentFactCount) {+ LOG.finest("Fact count changed from " + currentFactCount + " to " + newFactCount + " on '" + attributeStateChange + "'");+ }+ currentFactCount = newFactCount;+ }++ LOG.finest("Firing all rules");+ knowledgeSession.fireAllRules();++ return AttributeStateConsumerResult.OK;+ } catch (Throwable t) {+ LOG.log(Level.SEVERE, "Error executing rules for: " + attributeStateChange, t);+ if (t.getCause() != null) {+ LOG.log(Level.SEVERE, "Root Cause: \n", t.getCause());+ }+ throw t;+ }+ }++ public KieSession getKnowledgeSession() {+ return knowledgeSession;+ }++ protected void setGlobal(String identifier, Object object) {+ try {+ knowledgeSession.setGlobal(identifier, object);+ } catch (Throwable t) {+ // Ignore, Drools complains if the DRL doesn't declare the global, but it works+ }+ }++ protected boolean addResource(Resource resource, KieServices kieServices, KieFileSystem kfs) {+ String sourcePath = resource.getSourcePath();+ if (sourcePath == null) {+ throw new IllegalArgumentException("Resource definition must have source path: " + resource);+ }+ LOG.info("Adding rule definition: " + resource);+ try {++ // TODO Drools config API is shit, this is hidden in some internal code+ if (ResourceType.DTABLE.matchesExtension(sourcePath)) {+ int lastDot = sourcePath.lastIndexOf('.');+ if (lastDot >= 0 && sourcePath.length() > lastDot + 1) {+ String extension = sourcePath.substring(lastDot + 1);+ DecisionTableConfiguration tableConfig = KnowledgeBuilderFactory.newDecisionTableConfiguration();+ tableConfig.setInputType(DecisionTableInputType.valueOf(extension.toUpperCase()));+ resource.setConfiguration(tableConfig);+ }+ }++ LOG.fine("Rule definition resource config: " + resource.getConfiguration().toProperties());+ kfs.write("src/main/resources/" + sourcePath, resource);+ KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll();++ if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {+ Collection<Message> errors = kieBuilder.getResults().getMessages(Message.Level.ERROR);+ LOG.severe("Error in rule definition: " + resource);+ for (Message error : errors) {+ LOG.severe(error.getText());+ }+ // If compilation failed, remove rules from FileSystem so it won't fail on next pass here if any+ kfs.delete("src/main/resources/" + sourcePath);+ } else {+ LOG.info("Added rule definition: " + resource);+ return true;+ }+ } catch (Throwable t) {+ LOG.log(+ Level.SEVERE,+ "Error in rule definition: " + resource,+ t+ );+ // If compilation failed, remove rules from FileSystem so it won't fail on next pass here if any+ kfs.delete("src/main/resources/" + sourcePath);+ }+ return false;+ }++ @Override+ public String toString() {+ return "RuleEngine{" ++ "factCount=" + currentFactCount ++ "}";}}diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovynew file mode 100644index 000000000..226ffa1bf--- /dev/null+++ b/manager/test/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovy@@ -0,0 +1,116 @@+package org.openremote.test.rules++import org.kie.api.KieBase+import org.kie.api.KieServices+import org.kie.api.builder.KieFileSystem+import org.kie.api.builder.model.KieSessionModel+import org.kie.api.runtime.KieContainer+import org.kie.api.runtime.KieSession+import org.kie.internal.io.ResourceFactory+import org.openremote.agent.rules.RuleExecutionLogger+import org.openremote.agent.sensor.CustomSensorState+import org.openremote.test.ContainerTrait+import spock.lang.Shared+import spock.lang.Specification++import java.util.logging.*++import static org.kie.api.builder.Message.Level.ERROR++class RuleExecutionLoggerTest extends Specification implements ContainerTrait {++ public static TEST_SENSOR_NAME = "SENSOR_NAME";++ @Shared+ KieSession ksession++ def setup() {+ def kieServices = KieServices.Factory.get()+ def kieModuleModel = kieServices.newKieModuleModel()+ def kieBaseModel = kieModuleModel.newKieBaseModel("OpenRemoteKBase")+ .setDefault(true)+ .setEqualsBehavior(org.kie.api.conf.EqualityBehaviorOption.EQUALITY)+ def kieSessionModel = kieBaseModel.newKieSessionModel("OpenRemoteKSession")+ .setDefault(true)+ .setType(KieSessionModel.KieSessionType.STATEFUL)+ KieFileSystem kfs = kieServices.newKieFileSystem()+ kfs.writeKModuleXML(kieModuleModel.toXML())++ kfs.write(ResourceFactory.newClassPathResource("org/openremote/test/rules/simple/TestRuleFiring.drl")+ );+ def kieBuilder = kieServices.newKieBuilder(kfs).buildAll();++ if (kieBuilder.getResults().hasMessages(ERROR)) {+ throw new RuntimeException("KIE builder has errors")+ }++ KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId())+ KieBase kb = kieContainer.getKieBase();+ ksession = kb.newKieSession();+ }++ def cleanup() {+ if (ksession != null) {+ ksession.dispose()+ ksession = null;+ }+ }++ /**+ * This test confirms the plumbing for the event listener is working.+ * This test is testing the following behavior:+ * The event listener detects rule activations.+ * The listener fires "BeforeMatchFired" in response to rule activations.+ * The listener is properly detecting and logging information about the rule (name, declarations, LHS, etc.).+ */+ def "Event listener plumbing"() {+ given: "a custom state event"+ CustomSensorState newState = new CustomSensorState(1, TEST_SENSOR_NAME, "ON");+ ksession.insert(newState)++ and: "a logger of rule execution"+ RuleExecutionLogger ruleExecutionLogger = new RuleExecutionLogger()+ ksession.addEventListener(ruleExecutionLogger)+ //add a handler so logging output can be stored in active memory+ Logger ruleLogger = ruleExecutionLogger.getLOG()+ def testLogHandler = new TestLogHandler()+ ruleLogger.addHandler(testLogHandler);+ ruleLogger.setLevel(Level.ALL);++ when: "rules are fired"+ ksession.fireAllRules();++ String lastLog = String.format("rule \"%s\" // (package org.openremote.test.rules)\n" ++ "\tDeclarations \n\t\tDeclaration: \"\$e\"\n\t\tValue:\n\t\t\tSensor Name: \"%s\"\n\t\t\tSensor Value: \"ON\"\n" ++ "\tLHS objects(antecedents)\n\t\tClass: \"CustomSensorState\"\n\t\tFields: \n\t\t\tSensor name: \t\"%s\"\n\t\t\tState value: \t\"ON\"\n", "TestRuleFiring", TEST_SENSOR_NAME, TEST_SENSOR_NAME);++ then: "the execution should be logged"+ testLogHandler.lastLevel == Level.INFO+ testLogHandler.lastMessage == lastLog+ }++ static class TestLogHandler extends Handler {++ Level lastLevel+ String lastMessage;++ TestLogHandler() {+ this.setLevel(Level.ALL);+ this.setFormatter(new SimpleFormatter());+ }++ @Override+ void publish(LogRecord record) {+ lastLevel = record.getLevel();+ lastMessage = record.getMessage();+ }++ @Override+ void flush() {+ }++ @Override+ void close() {+ }+ }+}\ No newline at end of filediff --git a/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovynew file mode 100644index 000000000..7effdb3c0--- /dev/null+++ b/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy@@ -0,0 +1,102 @@+package org.openremote.test.rules++import elemental.json.Json+import elemental.json.JsonObject+import elemental.json.JsonType+import org.openremote.agent3.protocol.simulator.SimulatorProtocol+import org.openremote.container.message.MessageBrokerService+import org.openremote.manager.server.asset.AssetService+import org.openremote.manager.server.setup.SetupService+import org.openremote.manager.server.setup.builtin.ManagerDemoSetup+import org.openremote.model.AttributeRef+import org.openremote.model.AttributeState+import org.openremote.model.Attributes+import org.openremote.model.units.ColorRGB+import org.openremote.test.ManagerContainerTrait+import spock.lang.Specification+import spock.util.concurrent.PollingConditions++import static org.openremote.agent3.protocol.Protocol.ACTUATOR_TOPIC++class RulesDeploymentTest extends Specification implements ManagerContainerTrait {++ def "Check agent and thing deployment"() {++ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 30, initialDelay: 3)++ when: "the demo agent and thing have been deployed"+ def serverPort = findEphemeralPort()+ def container = startContainer(defaultConfig(serverPort), defaultServices())+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)+ def simulatorProtocol = container.getService(SimulatorProtocol.class)+ def assetService = container.getService(AssetService.class)++ then: "the simulator elements should have the initial state"+ conditions.eventually {+ assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Toggle").asBoolean()+ assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Dimmer").getType() == JsonType.NULL // No initial value!+ assert new ColorRGB(simulatorProtocol.getState(managerDemoSetup.thingId, "light1Color") as JsonObject) == new ColorRGB(88, 123, 88)+ assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1PowerConsumption").asNumber() == 12.345d+ }++ when: "a client wants to change a thing attributes' value, triggering an actuator"+ conditions = new PollingConditions(timeout: 3, initialDelay: 2)+ /* TODO What's the call path for thing attribute value updates and therefore the asset client API?++ Proposal:++ 1. Receive AttributeState on client API++ 2. Handle security and verify the message is for a linked agent/thing/attribute in the asset database++ 3. Send the AttributeState to the Protocol through ACTUATOR_TOPIC and trigger device/service call++ 4a. We assume that most protocol implementations are not using fire-and-forget but request/reply+ communication. Thus, an AttributeState has no further consequences besides triggering an+ actuator. We expect that a sensor "response" will let us know "soon" if the call was successful.+ Only a sensor value change will result in an update of the asset database state. The window of+ inconsistency we can accept depends on how "soon" a protocol typically responds.++ 4b. Alternatively, if the updated attribute is configured with the "forceUpdate" meta item, we write+ the new attribute state directly into the asset database after triggering the actuator. This flag+ is useful if the protocol does not reflect actuator changes "immediately". For example, if we+ send a value to a light dimmer actuator, does the light dimmer also have a sensor that responds+ quickly with the new value? If the device/service does not reply to value changes, we can force+ an update of the "current state" in our database and simply assume that the actuator call was+ successful.++ 4c. Should "forceUpdate" be the default behavior?+ */+ def light1DimmerChange = new AttributeState(+ new AttributeRef(managerDemoSetup.thingId, "light1Dimmer"), Json.create(66)+ )+ container.getService(MessageBrokerService.class).getProducerTemplate().sendBody(+ ACTUATOR_TOPIC, light1DimmerChange+ )++ then: "the simulator state should be updated"+ conditions.eventually {+ assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Dimmer").asNumber() == 66+ }++ when: "a simulated sensor changes its value"+ conditions = new PollingConditions(timeout: 3, initialDelay: 2)+ simulatorProtocol.putState(+ new AttributeRef(managerDemoSetup.thingId, "light1Dimmer"),+ Json.create(77),+ true+ )++ then: "the thing attribute value should be updated"+ conditions.eventually {+ def thing = assetService.find(managerDemoSetup.thingId)+ def attributes = new Attributes(thing.getAttributes())+ assert attributes.get("light1Dimmer").getValue_TODO_BUG_IN_JAVASCRIPT().getType() == JsonType.NUMBER+ assert attributes.get("light1Dimmer").getValueAsInteger() == 77+ }++ cleanup: "the server should be stopped"+ stopContainer(container)+ }+}diff --git a/manager/test/src/test/resources/org.openremote.test.rules/ClimateControl.drl b/manager/test/src/test/resources/org.openremote.test.rules/ClimateControl.drlnew file mode 100644index 000000000..bd259311d--- /dev/null+++ b/manager/test/src/test/resources/org.openremote.test.rules/ClimateControl.drl@@ -0,0 +1,1358 @@+package org.openremote.agent.test.rules;++import java.util.concurrent.*;+import java.util.Date;+import java.text.SimpleDateFormat;+import java.io.*;+import org.openremote.agent.sensor.*;++global org.openremote.agent.command.Commands commands;+global org.openremote.agent.rules.RulePersistence persistence;+global org.openremote.agent.rules.RuleUtil util;+global com.fasterxml.jackson.databind.ObjectMapper JSON;+global java.util.logging.Logger LOG;++declare SensorState+ @role(event)+end++rule "-PSB: Init"+salience 10+then+ commands.execute("VR1.ET", persistence.readData("VR1.ET","--:--"));+ commands.execute("VR1.ET.inc", "OFF");+ commands.execute("VR1.ET.dec", "OFF");+ commands.execute("VETA.inc", "OFF");+ commands.execute("VETA.dec", "OFF");+ commands.execute("VETD.inc", "OFF");+ commands.execute("VETD.dec", "OFF");+ commands.execute("VR1.COMFORT",persistence.readData("VR1.COMFORT","20.0\u00B0"));+ commands.execute("VR1.COMFORT.inc","OFF");+ commands.execute("VR1.COMFORT.dec","OFF");+ commands.execute("VR1.TEMPERATURE","19.5\u00B0");+ commands.execute("VR1.TEMPERATURE.inc","OFF");+ commands.execute("VR1.TEMPERATURE.dec","OFF");+ commands.execute("VNEXTACTION",persistence.readData("VNEXTACTION","-")); // Earlier arrive with reset+ commands.execute("VPERSONSENSETIME","-");+ commands.execute("VLEAVES", "1.0");+ commands.execute("VSCORE", "0");+ commands.execute("VHEATINGSETPOINT", "16");+ commands.execute("VWINDOW","Closed");+ commands.execute("VADVICEDONE", "OFF");+ commands.execute("VSUMMER", "No");+ commands.execute("VADVICE", "You're doing great!");+ commands.execute("VACATION.inc", "OFF");+ commands.execute("VACATION.dec", "OFF");+ commands.execute("VACATION", persistence.readData("VACATION", "0"));+ commands.execute("VTOTALSCORE",persistence.readData("VTOTALSCORE", "0"));+ commands.execute("VLEVEL", persistence.readData("VLEVEL", "0"));+ commands.execute("VATA", persistence.readData("VATA","-"));+ commands.execute("VATD", persistence.readData("VATD","-"));+ commands.execute("VPRESENCE","No");+ commands.execute("GVconfig",persistence.readData("GVconfig", "OpenRemote"));+ commands.execute("VArrivalBackground", "on");+ commands.execute("VDepartureBackground", "off");+end++rule "-PSB: Init ETA when empty"+salience 9+when+ SensorState(sensorName matches "VETA.*", $s: sensorName, value=="")+then+ commands.execute($s, persistence.readData($s, "09:00"));+end++rule "-PSB: Init ETD when empty"+salience 8+when+ SensorState(sensorName matches "VETD.*", $s: sensorName, value=="")+then+ commands.execute($s, persistence.readData($s, "17:00"));+end++rule "--Show timers"+salience 10+// timer(int:100)+when+ SensorState(sensorName=="TimerEEEE", $a:value!="N/A")+ SensorState(sensorName=="Timerd", $b:value!="N/A")+ SensorState(sensorName=="TimerHH", $d:value!="N/A")+ SensorState(sensorName=="TimerMMM", $c:value!="N/A")+ 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());+end++rule "--PSB: store values"+timer(int: 2s)+when+(+ SensorState($s:sensorName matches "VET.*", $v:value!="", eval(!persistence.readData($s,"").equals($v))) ||+ SensorState($s:sensorName=="VACATION", $v:value, eval(!persistence.readData($s,"").equals($v))) ||+ SensorState($s:sensorName=="VTOTALSCORE", $v:value, eval(!persistence.readData($s,"").equals($v))) ||+ SensorState($s:sensorName=="VLEVEL", $v:value, eval(!persistence.readData($s,"").equals($v))) ||+ SensorState($s:sensorName=="VR1.COMFORT", $v:value, eval(!persistence.readData($s,"").equals($v))) ||+ SensorState($s:sensorName=="VATA", $v:value, eval(!persistence.readData($s,"").equals($v))) ||+ SensorState($s:sensorName=="VATD", $v:value, eval(!persistence.readData($s,"").equals($v))) ||+ SensorState($s:sensorName=="VNEXTACTION", $v:value, eval(!persistence.readData($s,"").equals($v))) ||+ SensorState($s:sensorName=="VR1.ET", $v:value, eval(!persistence.readData($s,"").equals($v))) ||+ SensorState($s:sensorName=="VETA", $v:value, eval(!persistence.readData($s,"").equals($v))) ||+ SensorState($s:sensorName=="VETD", $v:value, eval(!persistence.readData($s,"").equals($v))) ||+ SensorState($s:sensorName matches "^GV.*", $v:value, eval(!persistence.readData($s,"").equals($v)))+)+then+ LOG.fine($s+" old value: "+persistence.readData($s,"||")+"; new value:"+$v.toString());+ persistence.writeData($s, $v);+end++rule "-PSB: VR1.ET Inc"+ timer(int:300ms) // debounce & protect double click+when+ SensorState(sensorName == "VR1.ET", $v: value)+ SensorState(sensorName == "VR1.ET.inc" , value == "ON")+then+ commands.execute("VR1.ET", util.shiftTime($v.toString(), 5));+ commands.execute("VR1.ET.inc", "off");+ commands.execute("VR1.ET.dec", "OFF");+end++rule "-PSB: VETA Inc"+ timer(int:300ms) // debounce & protect double click+when+ SensorState(sensorName == "VETA", $v: value)+ SensorState(sensorName == "VETA.inc" , value == "ON")+then+ commands.execute("VETA", util.shiftTime($v.toString(), 5));+ commands.execute("VETA.inc", "off");+ commands.execute("VETA.dec", "OFF");+end++rule "-PSB: VETD Inc"+ timer(int:300ms) // debounce & protect double click+when+ SensorState(sensorName == "VETD", $v: value)+ SensorState(sensorName == "VETD.inc" , value == "ON")+then+ commands.execute("VETD", util.shiftTime($v.toString(), 5));+ commands.execute("VETD.inc", "off");+ commands.execute("VETD.dec", "OFF");+end++rule "-PSB: VR1.ET Dec"+ timer(int:300ms)+when+ SensorState(sensorName == "VR1.ET", $v: value)+ SensorState(sensorName == "VR1.ET.dec" , value == "ON")+then+ commands.execute("VR1.ET", util.shiftTime($v.toString(), -15));+ commands.execute("VR1.ET.inc", "OFF");+ commands.execute("VR1.ET.dec", "off");+end++rule "-PSB: VETA Dec"+ timer(int:300ms)+when+ SensorState(sensorName == "VETA", $v: value)+ SensorState(sensorName == "VETA.dec" , value == "ON")+then+ commands.execute("VETA", util.shiftTime($v.toString(), -15));+ commands.execute("VETA.inc", "OFF");+ commands.execute("VETA.dec", "off");+end++rule "-PSB: VETD Dec"+ timer(int:300ms)+when+ SensorState(sensorName == "VETD", $v: value)+ SensorState(sensorName == "VETD.dec" , value == "ON")+then+ commands.execute("VETD", util.shiftTime($v.toString(), -15));+ commands.execute("VETD.inc", "OFF");+ commands.execute("VETD.dec", "off");+end++rule "PSB: VUSERSCHEDULECHANGES change counter"+ timer(int: 30s) // Wait 30s to mark user's schedule change+when+(+ SensorState($s:sensorName == "VR1.ET.inc" , value == "off") ||+ SensorState($s:sensorName == "VR1.ET.dec" , value == "off") ||+ SensorState($s:sensorName == "VETA.inc" , value == "off") ||+ SensorState($s:sensorName == "VETA.dec" , value == "off") ||+ SensorState($s:sensorName == "VETD.inc" , value == "off") ||+ SensorState($s:sensorName == "VETD.dec" , value == "off")+)+then+ // off - changed by user+ // OFF - idle state after restart+ commands.execute($s, "OFF");+ int cnt = 0;+ try{+ cnt = Integer.parseInt(persistence.readData("VUSERSCHEDULECHANGES","0"));+ }finally{+ cnt += 1;+ persistence.writeData("VUSERSCHEDULECHANGES", cnt);+ }+end++rule "PSB: set departure time on manual VR1.ET change"+ salience 10+ timer(int: 300ms)+when+ SensorState(sensorName == "VR1.ET", $v: value)+(+ SensorState(sensorName == "VR1.ET.inc" , value == "ON") ||+ SensorState(sensorName == "VR1.ET.dec" , value == "ON") ||+ SensorState(sensorName == "VETD.inc", value == "ON") ||+ SensorState(sensorName == "VETD.dec", value == "ON")+)+ SensorState(sensorName == "VNEXTACTION", value == "-")+then+ commands.execute("VNEXTACTION", "Departure");+end++rule "PSB: VR1.COMFORT inc"+ timer(int:300ms)+when+ SensorState(sensorName == "VR1.COMFORT", $v: value, eval(util.parseDouble(value) < 24))+ SensorState(sensorName == "VR1.COMFORT.inc" , value == "ON")+then+ commands.execute("VR1.COMFORT.inc","off");+ commands.execute("VR1.COMFORT.dec","OFF");+ commands.execute("VR1.COMFORT", util.shiftDouble($v.toString(), 0.5, "\u00B0"));+end++rule "PSB: VR1.COMFORT dec"+ timer(int:300ms)+when+ SensorState(sensorName == "VR1.COMFORT", $v: value, eval(util.parseDouble(value) > 18))+ SensorState(sensorName == "VR1.COMFORT.dec" , value == "ON")+then+ commands.execute("VR1.COMFORT.inc","OFF");+ commands.execute("VR1.COMFORT.dec","off");+ commands.execute("VR1.COMFORT", util.shiftDouble($v.toString(), -0.5, "\u00B0"));+end++rule "PSB: VR1.COMFORT INC/dec" // needed when change on the boundary+ salience -10+ timer(int:300ms)+when+ SensorState(sensorName == "VR1.COMFORT.inc" , value == "ON")+then+ commands.execute("VR1.COMFORT.inc","off");+ commands.execute("VR1.COMFORT.dec","OFF");+end++rule "PSB: VR1.COMFORT inc/DEC" // needed when change on the boundary+ salience -10+ timer(int:300ms)+when+ SensorState(sensorName == "VR1.COMFORT.dec" , value == "ON")+then+ commands.execute("VR1.COMFORT.inc","OFF");+ commands.execute("VR1.COMFORT.dec","off");+end++rule "PSB: VR1.TEMPERATURE inc"+ timer(int:300ms)+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName == "VR1.TEMPERATURE", $v: value, eval(util.parseDouble(value) <26))+ SensorState(sensorName == "VR1.TEMPERATURE.inc" , value == "ON")+then+ commands.execute("VR1.TEMPERATURE.inc","off");+ commands.execute("VR1.TEMPERATURE.dec","OFF"); // Do not increase change counter+ commands.execute("VR1.TEMPERATURE", util.shiftDouble($v.toString(), 0.5, "\u00B0"));+end++rule "PSB: VR1.TEMPERATURE dec"+ timer(int:300ms)+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName == "VR1.TEMPERATURE", $v: value, eval(util.parseDouble(value) > 16)) // Lower temp limit+ SensorState(sensorName == "VR1.TEMPERATURE.dec" , value == "ON")+then+ commands.execute("VR1.TEMPERATURE.inc","OFF");+ commands.execute("VR1.TEMPERATURE.dec","off");+ commands.execute("VR1.TEMPERATURE", util.shiftDouble($v.toString(), -0.5, "\u00B0"));+end++rule "PSB: VR1.TEMPERATURE INC/dec" // needed when on the boundary and in summer+ salience -10+ timer(int:300ms)+when+ SensorState(sensorName == "VR1.TEMPERATURE.inc" , value == "ON")+then+ commands.execute("VR1.TEMPERATURE.inc","off");+ commands.execute("VR1.TEMPERATURE.dec","OFF");+end++rule "PSB: VR1.TEMPERATURE inc/DEC" // needed when on the boundary and in summer+ salience -10+ timer(int:300ms)+when+ SensorState(sensorName == "VR1.TEMPERATURE.dec" , value == "ON")+then+ commands.execute("VR1.TEMPERATURE.inc","OFF");+ commands.execute("VR1.TEMPERATURE.dec","off");+end++rule "PSB: VR1.TEMPERATURE change counter"+ timer(int: 30s) // Wait 30s to mark user's temperature change+when+(+ SensorState($s:sensorName == "VR1.TEMPERATURE.inc" , value == "off") ||+ SensorState($s:sensorName == "VR1.TEMPERATURE.dec" , value == "off") ||+ SensorState($s:sensorName == "VR1.COMFORT.inc" , value == "off") ||+ SensorState($s:sensorName == "VR1.COMFORT.dec" , value == "off")+)+then+ // off - changed by user+ // OFF - idle state after restart+ commands.execute($s, "OFF");+ int cnt = 0;+ try{+ cnt = Integer.parseInt(persistence.readData("VSETTEMPCHANGES","0"));+ }finally{+ cnt += 1;+ persistence.writeData("VSETTEMPCHANGES", cnt);+ }+end++rule "PSB: VR1.TEMPERATURE change summer"+salience 10+when+ SensorState(sensorName=="VSUMMER", value=="Yes")+(+ SensorState(sensorName == "VR1.TEMPERATURE.inc" , $s: sensorName, value == "ON") ||+ SensorState(sensorName == "VR1.TEMPERATURE.dec", $s: sensorName, value == "ON")+)+then+ commands.execute($s, "OFF");+end++rule "PSB: set departure on manual TEMPERATURE change after expected attendance"+salience 10+ timer(int:300ms)+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName == "VR1.ET", $et: value)+(+ SensorState(sensorName == "VR1.TEMPERATURE.inc" , value == "ON") ||+ SensorState(sensorName == "VR1.TEMPERATURE.dec" , value == "ON")+)+ SensorState(sensorName == "VNEXTACTION", value == "-")+then+ // Set departure time when temp manually adjusted after leave+ commands.execute("VNEXTACTION", "Departure");+ commands.execute("VR1.ET", util.shiftTime($et.toString(), 60));+ commands.execute("VETD", util.shiftTime($et.toString(), 60));+end++rule "-PSB: Move ETA to ET at midnight"+when+ SensorState(sensorName=="TimerEEE", $e:value)+ SensorState(sensorName=="TimerHH",$h:value,eval(util.parseTimestamp(value) >= util.parseTimestamp("00:02"))) // Wait 2 minutes to be sure that $e is OK+ SensorState(sensorName matches ("VETA."+$e), eval(util.parseTimestamp(value) > util.parseTimestamp($h)), $va:value)+ SensorState(sensorName matches ("VETD."+$e), $vd: value)+ SensorState(sensorName=="VNEXTACTION", value=="-")+ SensorState(sensorName=="VACATION", eval(Integer.parseInt(value.toString())==0))+then+ commands.execute("VR1.ET", $va.toString());+ commands.execute("VETA", $va.toString());+ commands.execute("VETD", $vd.toString());+ commands.execute("VNEXTACTION", "Arrive");+end++rule "-Move ETA ETD for current day"+when+ SensorState(sensorName=="TimerEEE", $e:value)+ SensorState(sensorName matches ("VETA."+$e), $va:value)+ SensorState(sensorName matches ("VETD."+$e), $vd: value)+then+ commands.execute("VETA", $va.toString());+ commands.execute("VETD", $vd.toString());+end++rule "-PSB: reset VATA"+when+ SensorState(sensorName=="VNEXTACTION", value=="Arrive")+then+ commands.execute("VATA","-");+end++rule "-PSB: reset VATD"+when+ SensorState(sensorName=="VATA",value=="-")+then+ commands.execute("VATD","-");+end++rule "PSB: decrease vacation counter at midnight"+when+ $timer: SensorState(sensorName=="TimerHH", value!="N/A", eval(value.toString().substring(0,5).equals("00:00"))) // more reliable than timer(cron: )+ SensorState(sensorName=="VACATION", $v: value, eval(Integer.parseInt(value.toString())>0), this before [2m] $timer)+then+ commands.execute("VACATION", Integer.parseInt($v.toString())-1);+end++rule "PSB: reset action at midnight"+when+ SensorState(sensorName=="TimerHH", value!="N/A", eval(value.toString().substring(0,5).equals("00:00"))) // more reliable than timer(cron: )+then+ commands.execute("VR1.ET", "-");+ commands.execute("VNEXTACTION", "-");+end++rule "-PSB: Move ETD to ET at arrive init"+// This one is needed for cases when system is restart after arrive time+when+ SensorState(sensorName=="TimerEEE",$e:value)+ SensorState(sensorName=="TimerHH",$h:value)+ SensorState(sensorName matches ("VETA."+$e), eval(util.parseTimestamp(value) <= util.parseTimestamp($h)), eval(value.toString().length()==5))+ SensorState(sensorName matches ("VETD."+$e), $vd:value, eval(value.toString().length()==5))+// SensorState(sensorName=="VNEXTACTION", value=="-")+ SensorState(sensorName=="VR1.ET", value == "--:--")+then+ commands.execute("VR1.ET", $vd.toString());+ commands.execute("VETD", $vd.toString());+ commands.execute("VNEXTACTION", "Departure");+end++rule "-PSB: Move ETD to ET at arrive"+when+ SensorState(sensorName=="TimerEEE",$e:value)+ SensorState(sensorName=="TimerHH",$h:value)+ SensorState(sensorName=="VNEXTACTION", value=="Arrive")+ SensorState(sensorName matches ("VETD."+$e), $vd:value)+ SensorState(sensorName=="VETA", value != "-", value != "--:--", value != "status")+ SensorState(sensorName=="VETA", eval(util.parseTimestamp(value) < util.parseTimestamp($h)))+ SensorState(sensorName=="VACATION", eval(Integer.parseInt(value.toString())==0))+then+ commands.execute("VR1.ET", $vd.toString());+ commands.execute("VNEXTACTION", "Departure");+end++rule "PSB: actual arrival time earlier when temperature increased and person detected"+timer(int: 10s) // Prevent glitch at midnight reset+when+ // Before attendance schedule+ SensorState(sensorName=="TimerHH",$h:value)+ SensorState(sensorName=="VNEXTACTION", value=="Arrive")+ // Temperature increased manually (higher than ECO)+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VR1.COMFORT", $vc: value)+ SensorState(sensorName=="VR1.TEMPERATURE", eval(util.parseDouble(value) > java.lang.Math.max(util.parseDouble($vc)-5.0, 16.0)))+ // Person detected+ SensorState(sensorName=="VPERSONSENSE", value == "1")+ SensorState(sensorName=="VATA",value=="-")+then+ commands.execute("VR1.ET", $h.toString().substring(0,5));+end++rule "PSB: fetch actual arrival time"+when+ SensorState(sensorName=="TimerHH", $h:value)+ SensorState(sensorName=="VATA", value == "-")+ SensorState(sensorName=="VNEXTACTION", value=="Departure")+ SensorState(sensorName=="VPERSONSENSE", value=="1")+then+ commands.execute("VATA", $h.toString().substring(0,5));+end++rule "PSB: fetch earlier actual arrival time up to 30 min v02"+when+ SensorState(sensorName=="TimerHH", $h:value, eval(util.parseTimestamp(value) >= util.parseTimestamp("04:30"))) // Earliest time of arrival is 4:30 AM+ SensorState(sensorName=="VATA", value == "-")+ SensorState(sensorName=="VNEXTACTION", value=="Arrive")+ SensorState(sensorName=="VPERSONSENSE", value=="1")+ SensorState(sensorName=="VETA", value != "-", value != "--:--")+ SensorState(sensorName=="VETA", eval(util.parseTimestamp(util.shiftTime(value,-30)) <= util.parseTimestamp($h)))+then+ commands.execute("VATA", $h.toString().substring(0,5));+end++rule "PSB: Move - to ET at end of work"+timer(int: 1s) // avoid racing+when+ SensorState(sensorName=="TimerHH",$h:value)+ SensorState(sensorName=="VETD", value != "-", value != "--:--")+ SensorState(sensorName=="VETD", eval(util.parseTimestamp(value) < util.parseTimestamp($h)))+ SensorState(sensorName=="VNEXTACTION", value=="Departure")+then+ commands.execute("VR1.ET", "-");+ commands.execute("VNEXTACTION", "-");+end++rule "PSB: Move - to ET on vacation"+when+ SensorState(sensorName=="VACATION", eval(Integer.parseInt(value.toString())>0))+then+ commands.execute("VR1.ET", "-");+ commands.execute("VNEXTACTION", "-");+end++rule "PSB: fetch actual departure time"+when+ SensorState(sensorName=="VATA", value != "-")+ SensorState(sensorName=="VATD", value == "-")+ SensorState(sensorName=="VNEXTACTION", value=="-")+ SensorState(sensorName=="VPERSONSENSETIME", $v:value, eval(value.toString().length()>4))+then+ commands.execute("VATD", $v.toString().substring(0,5));+ commands.execute("VPERSONSENSETIME","-");+end++rule "PSB: fetch later departure time"+when+ SensorState(sensorName=="TimerEEE",$e:value)+ SensorState(sensorName=="VNEXTACTION", value=="-")+ SensorState(sensorName matches ("VETD."+$e), $vd:value)+ SensorState(sensorName=="VATA", value != "-")+ SensorState(sensorName=="VATD", value != "-")+ SensorState(sensorName=="VPERSONSENSETIME", $v:value, eval(value.toString().length()>4),+ eval(util.parseTimestamp(value)<=util.parseTimestamp(util.shiftTime($vd,15))), // Till 15 min after scheduled departure+ eval(util.parseTimestamp(value)<=util.parseTimestamp("23:55"))) // Till 23:55 - does not wrap on midnight+ SensorState(sensorName=="VACATION", eval(Integer.parseInt(value.toString())==0))+then+ commands.execute("VATD", $v.toString().substring(0,5));+ commands.execute("VPERSONSENSETIME","-");+end++rule "PSB: adjust estimated times at midnight"+when+ SensorState(sensorName=="TimerEEE", $e: value)+ $timer: SensorState(sensorName=="TimerHH", value!="N/A", eval(value.toString().substring(0,5).equals("23:58"))) // more reliable than timer(cron: )+ SensorState(sensorName matches ("VETD."+$e), $ved:value, this before [1m] $timer) // Loop cut+ SensorState(sensorName matches ("VETA."+$e), $vea:value, this before [1m] $timer)+ SensorState(sensorName=="VATD", $vd:value, value!="-")+ SensorState(sensorName=="VATA", $va:value, value!="-")+ SensorState(sensorName=="VACATION", eval(Integer.parseInt(value.toString())==0))+then+ Double alpha = 2.0/(3+1); // 3 stays for 3 days exponential average+ long nt = (long) (alpha*util.parseTimestamp($va) + (1-alpha)*util.parseTimestamp($vea));+ commands.execute("VETA."+$e.toString(), util.formatTimestamp(nt));+ LOG.fine("EA="+$vea.toString()+" AA="+$va.toString()+" NA="+ util.formatTimestamp(nt));+ nt = (long) (alpha*util.parseTimestamp($vd) + (1-alpha)*util.parseTimestamp($ved));+ commands.execute("VETD."+$e.toString(), util.formatTimestamp(nt));+ LOG.fine("ED="+$ved.toString()+" AD="+$vd.toString()+" ND="+ util.formatTimestamp(nt));+end++rule "--PSB: move sense"+when+ SensorState($s:sensorName=="FS.PIR", value=="on")+ SensorState(sensorName=="TimerHH", $h:value)+then+ LOG.info("Move sense on "+$s+" @"+$h);+ commands.execute("VPERSONSENSETIME", $h.toString());+end++rule "--pir echo"+when+ SensorState(sensorName=="FS.PIR", $v:value)+ SensorState(sensorName=="TimerHH", $h:value)+then+ LOG.info("PIR state "+$v.toString()+" @"+$h);+end++rule "-PSB: person sense"+when+ SensorState($s:sensorName=="FS.PIR", value=="on")+ SensorState(sensorName=="VPERSONSENSE", value!="1")+then+ commands.execute("VPERSONSENSE", "1");+end++rule "-PSB: no person sense"+timer(int: 2s)+when+ SensorState(sensorName=="FS.PIR", value!="on")+ SensorState(sensorName=="VPERSONSENSE", value!="0")+then+ commands.execute("VPERSONSENSE", "0");+end++rule "-PSB: window open sense"+when+ SensorState(sensorName=="FS.Window", value=="on")+then+ commands.execute("VWINDOW","Open");+end++rule "-PSB: window closed sense"+when+ SensorState(sensorName=="FS.Window", value=="off")+then+ commands.execute("VWINDOW","Closed");+end++rule "--FS outside temperature sense"+when+ SensorState(sensorName=="FS.Toutside", $v: value)+then+ commands.execute("VOUTSIDE", $v.toString() );+ LOG.fine("Fake outside temperature: "+$v.toString() );+end++rule "--FS inside temperature sense"+when+ SensorState(sensorName=="FS.Tinside", $v: value)+then+ LOG.fine("Fake inside temperature: "+ $v.toString() );+ commands.execute("VROOMTEMPERATURE", $v.toString() );+end++rule "PSB: Presence"+when+ SensorState(sensorName == "VPERSONSENSE", value == "1")+ SensorState(sensorName=="VNEXTACTION", value=="Departure") // within expected attendance schedule+then+ commands.execute("VPRESENCE","Yes");+end++rule "PSB: Absence when 30 min no movement"+timer(int: 30m)+when+ SensorState(sensorName == "VPERSONSENSE", value == "0")+ SensorState(sensorName=="VNEXTACTION", value=="Departure") // within expected attendance schedule+then+ commands.execute("VPRESENCE","No");+end++rule "PSB: Absence after 15 min v02"+timer(int: 15m)+when+ SensorState(sensorName == "VPERSONSENSE", value == "0")+then+ commands.execute("VPRESENCE","No");+end++rule "-PSB: Absence after scheduled presence time"+when+ SensorState(sensorName=="VNEXTACTION", value!="Departure") // outsidse expected attendance schedule+then+ commands.execute("VPRESENCE","No");+end++rule "-PSB: heating ECO"+when+(+ SensorState(sensorName=="VNEXTACTION", value!="Departure") || // outsidse expected attendance schedule+ SensorState(sensorName=="VSUMMER", value=="Yes")+)+then+ commands.execute("VHEATING","ECO");+end++rule "-PSB: heating Stand-by from ECO"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VNEXTACTION", value=="Departure") // within expected attendance schedule+ SensorState(sensorName=="VPRESENCE", value=="No")+ SensorState(sensorName=="VHEATING", value == "ECO")+ SensorState(sensorName=="VR1.COMFORT", $vc: value)+then+ commands.execute("VR1.TEMPERATURE", $vc.toString());+ commands.execute("VHEATING", "Stand-by");+end++rule "-PSB: heating Stand-by from ECO preheating 30 min v02"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VNEXTACTION", value=="Arrive") // within expected attendance schedule+ SensorState(sensorName=="VHEATING", value == "ECO")+ SensorState(sensorName=="VR1.COMFORT", $vc: value)++ SensorState(sensorName=="TimerHH", $h:value, eval(util.parseTimestamp(value) >= util.parseTimestamp("04:30"))) // Earliest time of arrival is 4:30 AM+ SensorState(sensorName=="VETA", value != "-", value != "--:--")+ SensorState(sensorName=="VETA", eval(util.parseTimestamp(util.shiftTime(value,-30)) <= util.parseTimestamp($h)))+then+ commands.execute("VR1.TEMPERATURE", $vc.toString());+ commands.execute("VHEATING", "Stand-by");+end++rule "-PSB: heating Stand-by from Comfort"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VNEXTACTION", value=="Departure") // within expected attendance schedule+ SensorState(sensorName=="VPRESENCE", value=="No")+ SensorState(sensorName=="VHEATING", value == "Comfort")+ SensorState(sensorName=="VR1.COMFORT", $vc: value)+ SensorState(sensorName=="VR1.TEMPERATURE", value==$vc) // Only when no manual temperature increase+then+ commands.execute("VHEATING","Stand-by");+end++rule "-PSB: heating Comfort on presence"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VPRESENCE", value=="Yes")+ SensorState(sensorName=="VR1.COMFORT", $v: value)+then+ commands.execute("VHEATING","Comfort");+ commands.execute("VR1.TEMPERATURE", $v.toString());+end++rule "-PSB: heating Comfort on temperature increase"+timer(int: 1s) // debounce+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VR1.COMFORT", $vc: value)+ SensorState(sensorName=="VR1.TEMPERATURE", eval(util.parseDouble(value) > util.parseDouble($vc)))+ SensorState(sensorName=="VHEATING", value != "Comfort")+then+ commands.execute("VHEATING","Comfort");+end++rule "-PSB: heating setpoint ECO"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VHEATING", value=="ECO")+ SensorState(sensorName=="VR1.COMFORT", $v: value)+then+ String s = $v.toString();+ Double t;+ try{+ t = java.lang.Math.max(16.0, Double.parseDouble(s.substring(0,s.length()-1))-5); // 5 degrees below comfort+ } catch (NumberFormatException e){+ t = 16.0;+ }+ commands.execute("VHEATINGSETPOINT", String.format("%.1f",t));+ commands.execute("VR1.TEMPERATURE", String.format("%.1f\u00B0",t));+end++rule "-PSB: heating setpoint ECO summer"+when+ SensorState(sensorName=="VSUMMER", value=="Yes")+ SensorState(sensorName=="VHEATING", value=="ECO")+ SensorState(sensorName=="VR1.COMFORT", $v: value)+then+ String s = $v.toString();+ Double t = java.lang.Math.max(16.0, Double.parseDouble(s.substring(0,s.length()-1))-5); // 5 degrees below comfort+ commands.execute("VHEATINGSETPOINT", String.format("%.1f",t));+ commands.execute("VR1.TEMPERATURE", "-");+end++rule "-PSB: heating setpoint Stand-by"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VHEATING", value=="Stand-by")+ SensorState(sensorName=="VR1.COMFORT", $v: value)+ SensorState(sensorName=="VR1.TEMPERATURE", value==$v) // When temperature changed manually keep it till ECO+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); // But the user is not aware as on display there is comfort+end++rule "-PSB: heating setpoint Comfort"+timer(int: 1s) // avoid race between "VHEATING" & "VR1.TEMPERATURE"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VHEATING", value=="Comfort")+ SensorState(sensorName=="VR1.TEMPERATURE", $v: value) // set by rule "PSB: heating Comfort" to VR1.COMFORT or manually+then+ String s = $v.toString();+ Double t = java.lang.Math.max(16.0, Double.parseDouble(s.substring(0,s.length()-1)));+ commands.execute("VHEATINGSETPOINT", String.format("%.1f",t));+end++rule "-PSB: leaves 0"+when+ SensorState(sensorName=="VLEAVES", value=="0.0")+then+ commands.execute("VLEAF1", "l0.png");+ commands.execute("VLEAF2", "l0.png");+ commands.execute("VLEAF3", "l0.png");+end++rule "-PSB: leaves 0.5"+when+ SensorState(sensorName=="VLEAVES", value=="0.5")+then+ commands.execute("VLEAF1", "l1.png");+ commands.execute("VLEAF2", "l0.png");+ commands.execute("VLEAF3", "l0.png");+end++rule "-PSB: leaves 1"+when+ SensorState(sensorName=="VLEAVES", value=="1.0")+then+ commands.execute("VLEAF1", "l2.png");+ commands.execute("VLEAF2", "l0.png");+ commands.execute("VLEAF3", "l0.png");+end++rule "-PSB: leaves 1.5"+when+ SensorState(sensorName=="VLEAVES", value=="1.5")+then+ commands.execute("VLEAF1", "l2.png");+ commands.execute("VLEAF2", "l1.png");+ commands.execute("VLEAF3", "l0.png");+end++rule "-PSB: leaves 2"+when+ SensorState(sensorName=="VLEAVES", value=="2.0")+then+ commands.execute("VLEAF1", "l2.png");+ commands.execute("VLEAF2", "l2.png");+ commands.execute("VLEAF3", "l0.png");+end++rule "-PSB: leaves 2.5"+when+ SensorState(sensorName=="VLEAVES", value=="2.5")+then+ commands.execute("VLEAF1", "l2.png");+ commands.execute("VLEAF2", "l2.png");+ commands.execute("VLEAF3", "l1.png");+end++rule "-PSB: leaves 3"+when+ SensorState(sensorName=="VLEAVES", value=="3.0")+then+ commands.execute("VLEAF1", "l2.png");+ commands.execute("VLEAF2", "l2.png");+ commands.execute("VLEAF3", "l2.png");+end++rule "-PSB: energy efficiency 1"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 23)) // Comfort++ SensorState(sensorName=="VHEATING", value!="ECO") // needed because of race+ SensorState(sensorName=="VPRESENCE", value=="No")+then+ commands.execute("VLEAVES", "0.0");+ commands.execute("VSCORE", 0);+end++rule "-PSB: energy efficiency 2"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 23)) // Comfort++ SensorState(sensorName=="VHEATING", value!="ECO") // needed because of race+ SensorState(sensorName=="VPRESENCE", value=="Yes")+ SensorState(sensorName=="VWINDOW", value=="Open")+then+ commands.execute("VLEAVES", "0.5");+ commands.execute("VSCORE", 0);+end++// v02+rule "-PSB: energy efficiency 2-1 v02"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Open")+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) < 23)) // Comfort, Comfort-, Comfort--+ SensorState(sensorName=="VHEATING", value!="ECO") // needed because of race+ SensorState(sensorName=="VPRESENCE", value=="No")+ SensorState(sensorName=="VOUTSIDE", $t: value)+ SensorState(sensorName=="VR1.TEMPERATURE", eval(util.parseDouble($t) < util.parseDouble(value))) // Lower outside temperature+then+ commands.execute("VLEAVES", "0.5");+ commands.execute("VSCORE", 0);+end++rule "-PSB: energy efficiency 2-2 v02"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Closed")+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 23)) // Comfort++ SensorState(sensorName=="VHEATING", value!="ECO") // needed because of race+ SensorState(sensorName=="VPRESENCE", value=="No")+then+ commands.execute("VLEAVES", "0.5");+ commands.execute("VSCORE", 0);+end++rule "-PSB: energy efficiency 2-3 v02"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Closed")+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) < 23), eval(Double.parseDouble(value.toString()) >= 18)) // Comfort, Comfort-, Comfort--, not eco+ SensorState(sensorName=="VHEATING", value!="ECO") // needed because of race+ SensorState(sensorName=="VPRESENCE", value=="No")+then+ commands.execute("VLEAVES", "1.0");+ commands.execute("VSCORE", 0);+end+// v02++rule "-PSB: energy efficiency 3"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 21), eval(Double.parseDouble(value.toString()) < 23)) // Comfort+ SensorState(sensorName=="VHEATING", value!="ECO") // needed because of race+ SensorState(sensorName=="VPRESENCE", value=="No")+then+ commands.execute("VLEAVES", "1.0");+ commands.execute("VSCORE", 0);+end++rule "-PSB: energy efficiency 4"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Open") // Added because otherwise it overrules efficiency 11+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 21), eval(Double.parseDouble(value.toString()) < 23)) // Comfort+ SensorState(sensorName=="VHEATING", value!="ECO") // needed because of race+ SensorState(sensorName=="VPRESENCE", value=="Yes")+then+ commands.execute("VLEAVES", "1.0");+ commands.execute("VSCORE", 0);+end++rule "-PSB: energy efficiency 5"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VHEATING", value=="Stand-by")+ SensorState(sensorName=="VPRESENCE", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Open")+then+ commands.execute("VLEAVES", "1.0");+ commands.execute("VSCORE", 0);+end++rule "-PSB: energy efficiency 6"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 23)) // Comfort++ SensorState(sensorName=="VHEATING", value!="ECO") // needed because of race+ SensorState(sensorName=="VPRESENCE", value=="Yes")+ SensorState(sensorName=="VWINDOW", value=="Open")+then+ commands.execute("VLEAVES", "1.0");+ commands.execute("VSCORE", 0);+end++rule "-PSB: energy efficiency 7"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Open")+ SensorState(sensorName=="VHEATING", value=="Stand-by")+ SensorState(sensorName=="VPRESENCE", value=="No")+ SensorState(sensorName=="VOUTSIDE", $t: value)+ SensorState(sensorName=="VR1.TEMPERATURE", eval(util.parseDouble($t) < util.parseDouble(value))) // Lower outside temperature+then+ commands.execute("VLEAVES", "1.5");+ commands.execute("VSCORE", 1);+end++rule "-PSB: energy efficiency 8"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Open")+ SensorState(sensorName=="VHEATING", value=="ECO")+ SensorState(sensorName=="VPRESENCE", value=="No")+ SensorState(sensorName=="VOUTSIDE", $t: value)+ SensorState(sensorName=="VR1.TEMPERATURE", eval(util.parseDouble($t) < util.parseDouble(value))) // Lower outside temperature+then+ commands.execute("VLEAVES", "1.5");+ commands.execute("VSCORE", 1);+end++rule "-PSB: energy efficiency 9"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Closed")+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 23)) // Comfort++ SensorState(sensorName=="VHEATING", value!="ECO") // needed because of race+ SensorState(sensorName=="VPRESENCE", value=="Yes")+then+ commands.execute("VLEAVES", "1.5");+ commands.execute("VSCORE", 1);+end++rule "-PSB: energy efficiency 10"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Open")+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 20), eval(Double.parseDouble(value.toString()) < 21)) // Comfort-+ SensorState(sensorName=="VHEATING", value!="ECO") // needed because of race+ SensorState(sensorName=="VPRESENCE", value=="Yes")+ SensorState(sensorName=="VOUTSIDE", $t: value)+ SensorState(sensorName=="VR1.TEMPERATURE", eval(util.parseDouble($t) < util.parseDouble(value))) // Lower outside temperature+then+ commands.execute("VLEAVES", "1.5");+ commands.execute("VSCORE", 1);+end++rule "-PSB: energy efficiency 11"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Closed")+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 21), eval(Double.parseDouble(value.toString()) < 23)) // Comfort+ SensorState(sensorName=="VHEATING", value!="ECO") // needed because of race+ SensorState(sensorName=="VPRESENCE", value=="Yes")+then+ commands.execute("VLEAVES", "2.0");+ commands.execute("VSCORE", 2);+end++rule "-PSB: energy efficiency 12 v02"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Closed")+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 20), eval(Double.parseDouble(value.toString()) < 21)) // Comfort-+ SensorState(sensorName=="VHEATING", value!="ECO") // needed because of race+ SensorState(sensorName=="VPRESENCE", value=="Yes") // v02+then+ commands.execute("VLEAVES", "2.5");+ commands.execute("VSCORE", 3);+end++rule "-PSB: energy efficiency 13"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Open")+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) < 20)) // Comfort--+ SensorState(sensorName=="VHEATING", value!="ECO") // needed because of race+ SensorState(sensorName=="VPRESENCE", value=="Yes")+ SensorState(sensorName=="VOUTSIDE", $t: value)+ SensorState(sensorName=="VR1.TEMPERATURE", eval(util.parseDouble($t) >= util.parseDouble(value))) // Higher outside temperature+then+ commands.execute("VLEAVES", "3.0");+ commands.execute("VSCORE", 4);+end++rule "-PSB: energy efficiency 14"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Closed")+ SensorState(sensorName=="VHEATING", value=="ECO")+ SensorState(sensorName=="VPRESENCE", value=="No")+then+ commands.execute("VLEAVES", "3.0");+ commands.execute("VSCORE", 4);+end++rule "-PSB: energy efficiency 15"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Closed")+ SensorState(sensorName=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) < 20)) // Comfort--+ SensorState(sensorName=="VPRESENCE", value=="Yes") // No important IMHO+then+ commands.execute("VLEAVES", "3.0");+ commands.execute("VSCORE", 4);+end++rule "-PSB: energy efficiency Summer"+when+ SensorState(sensorName=="VSUMMER", value=="Yes")+then+ commands.execute("VLEAVES", "3.0");+ commands.execute("VSCORE", 4);+end++rule "--PSB: increase total score every 15m"+when+ $timer: SensorState(sensorName=="TimerHH", value!="N/A", eval(Integer.parseInt(value.toString().substring(3,5)) % 15 == 0)) // more reliable than timer(cron: )+ SensorState(sensorName=="VSCORE", $s: value)+ SensorState(sensorName=="VTOTALSCORE", $ts: value, this before [1m] $timer)+then+ commands.execute("VTOTALSCORE", Integer.parseInt($ts.toString())+Integer.parseInt($s.toString()));+end++rule "PSB: reward"+when+ $ts: SensorState(sensorName=="VTOTALSCORE", $s: value, eval(Integer.parseInt(value.toString()) >= 1000))+ SensorState(sensorName=="VLEVEL", $l: value, this before [1m] $ts)+then+ Integer i = Integer.parseInt($s.toString());+ commands.execute("VTOTALSCORE", i-1000); // Reset score+ commands.execute("VLEVEL", Integer.parseInt($l.toString())+1);+end++rule "--PSB: display totalscore"+when+ SensorState(sensorName=="VTOTALSCORE", $ts: value)+then+ commands.execute("VTOTALSCOREdisp", $ts+" / 1000");+end++rule "PSB: summer"+timer(int: 1h)+when+// SensorState(sensorName=="VR1.COMFORT", $sp: value)+// SensorState(sensorName=="VOUTSIDE", value!="", eval(util.parseDouble($sp) <= util.parseDouble(value) )) // Outside temp higher than set point+ SensorState(sensorName=="VOUTSIDE", $o:value) // Only for logging+ SensorState(sensorName=="YT.summer", value=="0") // Y-con test+ SensorState(sensorName=="VSUMMER", value!="Yes")+then+ LOG.fine("Summer is ON; outside="+$o.toString());+ commands.execute("VSUMMER", "Yes");+end++rule "PSB: no summer"+timer(int: 1h)+when+// SensorState(sensorName=="VR1.COMFORT", $sp: value)+// SensorState(sensorName=="VOUTSIDE", value!="", eval(util.parseDouble($sp) > util.parseDouble(value) )) // Outside temp lower than set point+ SensorState(sensorName=="VOUTSIDE", $o:value) // Only for logging+ SensorState(sensorName=="YT.summer", value=="1") // Y-con test+ SensorState(sensorName=="VSUMMER", value!="No")+then+ LOG.fine("Summer is OFF; outside="+$o.toString());+ commands.execute("VSUMMER", "No");+end++rule "-PSB: advice 1"+when+ SensorState(sensorName=="VWINDOW", value=="Open")+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VHEATINGSETPOINT", $sp: value)+ SensorState(sensorName=="VOUTSIDE", value!="", eval(Double.parseDouble($sp.toString()) > util.parseDouble(value) )) // Outside temp lower than set point+then+ commands.execute("VADVICE", "It's more energy efficient to close the windows when it is colder outside than it is inside");+ commands.execute("VADVICEDONE", "OFF");+ insert(new AdviceGiven("It's more energy efficient to close the windows when it is colder outside than it is inside"));+end++rule "-PSB: advice 1 done"+when+ SensorState(sensorName=="VHEATINGSETPOINT", $sp: value)+(+ SensorState(sensorName=="VWINDOW", value=="Closed") ||+ SensorState(sensorName=="VOUTSIDE", value!="", eval(Double.parseDouble($sp.toString()) <= util.parseDouble(value) )) // Outside temp lower than set point+)+ SensorState(sensorName=="VADVICE",eval(value.toString().substring(0,9).equals("It's more")))+then+ commands.execute("VADVICE", "You're doing great!");+ commands.execute("VADVICEDONE", "OFF");+end++rule "-PSB: advice 2"+when+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VR1.COMFORT", eval(util.parseDouble(value) > 20.5)) // Average is 20 hardcoded or from sensor?+then+ commands.execute("VADVICE", "Your comfort temperature is set higher than average. You can adjust it on the settings page.");+ commands.execute("VADVICEDONE", "OFF");+ insert(new AdviceGiven("Your comfort temperature is set higher than average. You can adjust it on the settings page."));+end++rule "-PSB: advice 2 done"+when+ SensorState(sensorName=="VR1.COMFORT", eval(util.parseDouble(value) <= 20.5)) // Average is 20 hardcoded or from sensor?+ SensorState(sensorName=="VADVICE",eval(value.toString().substring(0,12).equals("Your comfort")))+then+ commands.execute("VADVICE", "You're doing great!");+ commands.execute("VADVICEDONE", "OFF");+end++rule "-PSB: advice 3"+when+// irregular attendence+then+ commands.execute("VADVICEDONE", "OFF");+end++rule "-PSB: advice 4"+when+(+ SensorState(sensorName=="VADVICEDONE", value=="ON") ||+ SensorState(sensorName=="VSUMMER", value=="Yes")+)+then+ commands.execute("VADVICE", "You're doing great!");+ commands.execute("VADVICEDONE", "OFF");+ insert(new AdviceGiven("You're doing great!"));+end++declare AdviceGiven+ @role(event)+ @expires(10m)+ advice : String+end++rule "-PSB: advices given counter"+when+ SensorState(sensorName=="VADVICE", value!="", value!="You're doing great!")+ //AdviceGiven(advice!="You're doing great!") // This one fires with the same advice+then+ int cnt = 0;+ try{+ cnt = Integer.parseInt(persistence.readData("VADVICEGIVEN","0"));+ }finally{+ cnt += 1;+ persistence.writeData("VADVICEGIVEN", cnt);+ }+end++rule "-PSB: vacation inc"+ timer(int:300ms)+when+ SensorState(sensorName=="VACATION", $v: value)+ SensorState(sensorName=="VACATION.inc", value=="ON")+then+ commands.execute("VACATION", Integer.parseInt($v.toString())+1);+ commands.execute("VACATION.inc", "OFF");+end++rule "-PSB: vacation dec"+ timer(int:300ms)+when+ SensorState(sensorName=="VACATION", $v: value, eval(Integer.parseInt(value.toString()) > 0))+ SensorState(sensorName=="VACATION.dec", value=="ON")+then+ commands.execute("VACATION", Integer.parseInt($v.toString())-1);+ commands.execute("VACATION.dec", "OFF");+end++rule "-PSB: vacation inc/dec" // needed so the ON value does not hang+ salience -10+ timer(int:300ms)+when+ SensorState(sensorName matches "VACATION...c", $s: sensorName, value=="ON")+then+ commands.execute($s, "OFF");+end++rule "PSB: start next week stats"+ timer(cron: 0 0 0 ? * 1) // Every Sunday morning at midnight+when+ // Time scheduled+ Number($arrive: longValue>0) from accumulate(SensorState(sensorName matches "VETA.*", $a:value), sum(util.parseTimestamp($a)))+ Number($departure: longValue>0) from accumulate(SensorState(sensorName matches "VETD.*", $d:value), sum(util.parseTimestamp($d)))+then+ persistence.writeData("VSETTEMPCHANGES4" ,persistence.readData("VSETTEMPCHANGES3","0"));+ persistence.writeData("VSETTEMPCHANGES3" ,persistence.readData("VSETTEMPCHANGES2","0"));+ persistence.writeData("VSETTEMPCHANGES2" ,persistence.readData("VSETTEMPCHANGES1","0"));+ persistence.writeData("VSETTEMPCHANGES1" ,persistence.readData("VSETTEMPCHANGES","0"));+ persistence.writeData("VSETTEMPCHANGES" , "0");++ persistence.writeData("VUSERSCHEDULECHANGES4" ,persistence.readData("VUSERSCHEDULECHANGES3","0"));+ persistence.writeData("VUSERSCHEDULECHANGES3" ,persistence.readData("VUSERSCHEDULECHANGES2","0"));+ persistence.writeData("VUSERSCHEDULECHANGES2" ,persistence.readData("VUSERSCHEDULECHANGES1","0"));+ persistence.writeData("VUSERSCHEDULECHANGES1" ,persistence.readData("VUSERSCHEDULECHANGES","0"));+ persistence.writeData("VUSERSCHEDULECHANGES" , "0");++ persistence.writeData("VADVICEGIVEN4" ,persistence.readData("VADVICEGIVEN3","0"));+ persistence.writeData("VADVICEGIVEN3" ,persistence.readData("VADVICEGIVEN2","0"));+ persistence.writeData("VADVICEGIVEN2" ,persistence.readData("VADVICEGIVEN1","0"));+ persistence.writeData("VADVICEGIVEN1" ,persistence.readData("VADVICEGIVEN","0"));+ persistence.writeData("VADVICEGIVEN" , "0");++ // Time scheduled+ long minutes = ($departure-$arrive)/60000;+ long hours = minutes/60;++ persistence.writeData("VHOURSPRESENT4" ,persistence.readData("VHOURSPRESENT3","0:00"));+ persistence.writeData("VHOURSPRESENT3" ,persistence.readData("VHOURSPRESENT2","0:00"));+ persistence.writeData("VHOURSPRESENT2" ,persistence.readData("VHOURSPRESENT1","0:00"));+ persistence.writeData("VHOURSPRESENT1" , String.format("%2d:%02d", hours, minutes%60));+end++// New StrijpS 2016++rule "-PSB16: Full Timer"+when+ SensorState(sensorName=="TimerEEEE", $EEEE:value)+ SensorState(sensorName=="Timerd", $d: value)+ SensorState(sensorName=="TimerMMM", $MMM:value)+then+ commands.execute("VTimer", $EEEE.toString()+" "+$d.toString()+" "+$MMM.toString()+". I will be:");+end++rule "-PSB16: background arrival on"+when+ SensorState(sensorName=="TimerHH", $h:value)+ SensorState(sensorName=="VETA", eval(util.parseTimestamp(value) > util.parseTimestamp($h)) )+ SensorState(sensorName=="VArrivalBackground", value!="on")+then+ commands.execute("VArrivalBackground", "on");+end++rule "-PSB16: background departure on"+when+ SensorState(sensorName=="TimerHH", $h:value)+ SensorState(sensorName=="VETD", eval(util.parseTimestamp(value) > util.parseTimestamp($h)) )+ SensorState(sensorName=="VDepartureBackground", value!="on")+then+ commands.execute("VDepartureBackground", "on");+end++rule "-PSB16: background arrival off"+when+ SensorState(sensorName=="TimerHH", $h:value)+ SensorState(sensorName=="VETA", eval(util.parseTimestamp(value) <= util.parseTimestamp($h)) )+ SensorState(sensorName=="VArrivalBackground", value!="off")+then+ commands.execute("VArrivalBackground", "off");+end++rule "-PSB16: background departure off"+when+ SensorState(sensorName=="TimerHH", $h:value)+ SensorState(sensorName=="VETD", eval(util.parseTimestamp(value) <= util.parseTimestamp($h)) )+ SensorState(sensorName=="VDepartureBackground", value!="off")+then+ commands.execute("VDepartureBackground", "off");+end++// Fake sensors start++rule "-Fake sensors init"+then+ commands.execute("FS.Toutside", "15\u00B0");+ commands.execute("FS.Tinside", "19.5\u00B0");+ commands.execute("FS.PIR", "off");+ commands.execute("FS.Window", "off");+end++rule "--Fake sensors Toutside inc"+ timer(int:300ms)+when+ SensorState(sensorName == "FS.Toutside", $v: value, eval(util.parseDouble(value) < 50))+ SensorState(sensorName == "FS.Toutside.inc" , value == "on")+then+ commands.execute("FS.Toutside.inc","off");+ commands.execute("FS.Toutside", util.shiftDouble($v.toString(), 0.1, "\u00B0"));+end++rule "--Fake sensors Toutside dec"+ timer(int:300ms)+when+ SensorState(sensorName == "FS.Toutside", $v: value, eval(util.parseDouble(value) > -40))+ SensorState(sensorName == "FS.Toutside.dec" , value == "on")+then+ commands.execute("FS.Toutside.dec","off");+ commands.execute("FS.Toutside", util.shiftDouble($v.toString(), -0.1, "\u00B0"));+end++rule "--Fake sensors Tinside inc"+ timer(int:300ms)+when+ SensorState(sensorName == "FS.Tinside", $v: value, eval(util.parseDouble(value) < 40))+ SensorState(sensorName == "FS.Tinside.inc" , value == "on")+then+ commands.execute("FS.Tinside.inc","off");+ commands.execute("FS.Tinside", util.shiftDouble($v.toString(), 0.1, "\u00B0"));+end++rule "--Fake sensors Tinside dec"+ timer(int:300ms)+when+ SensorState(sensorName == "FS.Tinside", $v: value, eval(util.parseDouble(value) > 0))+ SensorState(sensorName == "FS.Tinside.dec" , value == "on")+then+ commands.execute("FS.Tinside.dec","off");+ commands.execute("FS.Tinside", util.shiftDouble($v.toString(), -0.1, "\u00B0"));+end++rule "--Fake sensors PIR off"+ timer(int: 2s)+when+ SensorState(sensorName=="FS.PIR", value=="on")+then+ commands.execute("FS.PIR", "off");+end++// Fake sensors end\ No newline at end of filediff --git a/manager/test/src/test/resources/org.openremote.test.rules/Vacation.drl b/manager/test/src/test/resources/org.openremote.test.rules/Vacation.drlnew file mode 100644index 000000000..285a030ec--- /dev/null+++ b/manager/test/src/test/resources/org.openremote.test.rules/Vacation.drl@@ -0,0 +1,68 @@+package org.openremote.test.rules;++global org.openremote.agent.command.Commands commands;++import org.openremote.agent.sensor.*;++/*+ * This example demonstrates creation of new facts from within the rules, in this+ * case a vacation object that can be used to determine differing behavior on event+ * actions.+ */++declare Vacation+ onVacation : boolean+end++/* Insert a new vacation fact */++rule "I'm going on vacation"+when+ SensorState ( sensorName == "vacation start" )+then+ Vacation vacation = new Vacation();+ insert ( vacation );+end++/* Retract the vacation fact */++rule "I'm back from vacation"+when+ SensorState ( sensorName == "vacation end" )+ $vacation : Vacation()+then+ retract ( $vacation );+end++/* Set night temperatures differently depending on presence of vacation fact */++rule "Set Night Temperature"+when+ CustomSensorState( sensorName == "time of day", value == "night" ) and not Vacation()+then+ commands.execute("temp", 18);+end++rule "Set Night Temperature when on Vacation"+when+ CustomSensorState ( sensorName == "time of day", value == "night" ) and exists Vacation()+then+ commands.execute("temp", 15);+end++/* Set day temperatures differently depending on the presence of vacation fact */++rule "Set Day Temperature"+when+ CustomSensorState ( sensorName == "time of day", value == "day" ) and not Vacation()+then+ commands.execute("temp", 21);+end++rule "Set Day Temperature when on Vacation"+when+ SensorState ( sensorName == "time of day", value == "day" ) and exists Vacation()+then+ commands.execute("temp", 15);+end+