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
Removed event processor chain (we only have one processor, ever...), more cleanup
Christian Bauer2d46b29ebf40
diff --git a/controller/src/main/java/org/openremote/controller/ControllerService.java b/controller/src/main/java/org/openremote/controller/ControllerService.javaindex f9c46cb6a..b41a6888c 100644--- a/controller/src/main/java/org/openremote/controller/ControllerService.java+++ b/controller/src/main/java/org/openremote/controller/ControllerService.java@@ -4,11 +4,11 @@ import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.controller.command.CommandBuilder;import org.openremote.controller.context.ControllerContext;-import org.openremote.controller.context.InMemoryStateStorage;+import org.openremote.controller.context.InMemorySensorStateStorage;import org.openremote.controller.deploy.DeploymentDefinition;import org.openremote.controller.deploy.xml.ControllerDOMParser;-import org.openremote.controller.event.EventProcessor;-import org.openremote.controller.model.Deployment;+import org.openremote.controller.deploy.Deployment;+import org.openremote.controller.rules.RulesProvider;import java.io.InputStream;@@ -16,32 +16,29 @@ public class ControllerService implements ContainerService {final protected ControllerDOMParser controllerDOMParser = new ControllerDOMParser();final protected InputStream deploymentXml;-final protected CommandBuilder commandBuilder;- final protected EventProcessor[] eventProcessors;+ final protected RulesProvider rulesProvider;- protected DeploymentDefinition deploymentDefinition;protected ControllerContext controllerContext;- public ControllerService(InputStream deploymentXml, CommandBuilder commandBuilder, EventProcessor[] eventProcessors) {+ public ControllerService(InputStream deploymentXml, CommandBuilder commandBuilder, RulesProvider rulesProvider) {this.deploymentXml = deploymentXml;this.commandBuilder = commandBuilder;- this.eventProcessors = eventProcessors;+ this.rulesProvider = rulesProvider;}@Overridepublic void init(Container container) throws Exception {- deploymentDefinition = controllerDOMParser.parse(deploymentXml, true);}@Overridepublic void configure(Container container) throws Exception {// TODO Support booting of multiple controller instancesDeployment deployment = new Deployment(- deploymentDefinition,+ controllerDOMParser.parse(deploymentXml, true),commandBuilder,- new InMemoryStateStorage(),- eventProcessors+ new InMemorySensorStateStorage(),+ rulesProvider);controllerContext = new ControllerContext("OpenRemoteController1", deployment);}diff --git a/controller/src/main/java/org/openremote/controller/command/Commands.java b/controller/src/main/java/org/openremote/controller/command/Commands.javaindex eb1ba27ab..1ebfd8747 100644--- a/controller/src/main/java/org/openremote/controller/command/Commands.java+++ b/controller/src/main/java/org/openremote/controller/command/Commands.java@@ -1,15 +1,13 @@package org.openremote.controller.command;-import org.openremote.controller.event.EventProcessor;import org.openremote.controller.deploy.CommandDefinition;-import org.openremote.controller.model.Deployment;+import org.openremote.controller.deploy.Deployment;import java.util.logging.Level;import java.util.logging.Logger;/**- * Can be used directly and/or by {@link EventProcessor}s to trigger- * {@link ExecutableCommand}s (e.g. in rules or from simple client call).+ * Facade for running {@link ExecutableCommand}s (e.g. in rules or from simple client call).*/public class Commands {diff --git a/controller/src/main/java/org/openremote/controller/command/EventProducerCommand.java b/controller/src/main/java/org/openremote/controller/command/EventProducerCommand.javadeleted file mode 100644index 26ccd548d..000000000--- a/controller/src/main/java/org/openremote/controller/command/EventProducerCommand.java+++ /dev/null@@ -1,9 +0,0 @@-package org.openremote.controller.command;--/**- * A tagging interface between two different types of event producers -- a pull- * command (an explicit request for device state) and a push command (for 'active'- * devices that broadcast their state).- */-public interface EventProducerCommand extends Command {-}diff --git a/controller/src/main/java/org/openremote/controller/command/PullCommand.java b/controller/src/main/java/org/openremote/controller/command/PullCommand.javaindex bb39018e4..35387b65f 100644--- a/controller/src/main/java/org/openremote/controller/command/PullCommand.java+++ b/controller/src/main/java/org/openremote/controller/command/PullCommand.java@@ -1,13 +1,20 @@package org.openremote.controller.command;-import org.openremote.controller.model.Sensor;+import org.openremote.controller.sensor.Sensor;-public interface PullCommand extends EventProducerCommand {+/**+ * Pull commands are intended for collecting updates from "passive" devices which must+ * be called periodically to read state updates.+ */+public interface PullCommand extends SensorUpdateCommand {int POLLING_INTERVAL = 500;/**- * Read a device status and translate it to a sensor's datatype.+ * Read and return raw device status.+ *+ * The {@link Sensor} is only provided as a hint, don't call+ * {@link Sensor#update} but return the current state instead.*/String read(Sensor sensor);diff --git a/controller/src/main/java/org/openremote/controller/command/PushCommand.java b/controller/src/main/java/org/openremote/controller/command/PushCommand.javaindex 015dfc06a..ce0b9625b 100644--- a/controller/src/main/java/org/openremote/controller/command/PushCommand.java+++ b/controller/src/main/java/org/openremote/controller/command/PushCommand.java@@ -1,22 +1,18 @@package org.openremote.controller.command;-import org.openremote.controller.model.Sensor;+import org.openremote.controller.sensor.Sensor;/**- * Push commands are intended for collecting events from "active" devices which broadcast+ * Push commands are intended for collecting updates from "active" devices which broadcast* them over various transport mechanisms -- examples include bus installations such as- * KNX bus or IP-network broadcasts. In some cases it is also possible to use event listener- * interface to implement polling mechanism to "passive" devices -- normally a default- * polling implementation is provided by {@link PullCommand}- * implementation but push commands can be used to override this default implementation.+ * KNX bus or IP-network broadcasts.** Push commands are expected to create their own threads (if needed) which implement the- * push functionality and also directly push received events to the context of the controller- * using the sensor callback API provided.+ * push functionality and also push updates to the context of the controller using the+ * sensor callback API provided.*- * Push command implementations use the sensor- * {@link org.openremote.controller.model.Sensor#update} method to push state changes- * into the controller, as shown in the example below:+ * Push command implementations use the sensor {@link Sensor#update} method to push state+ * changes into the controller's context, as shown in the example below:** <pre><code>*@@ -54,11 +50,11 @@ import org.openremote.controller.model.Sensor;*** <b>NOTE:</b> The controller at this point does not implement any flow control on its side --- * therefore a very busy listener can overflow it with too many events. Control- * flow must be implemented co-operatively by the listener implementation ensuring- * that not too many events are created.+ * therefore a very busy listener can overflow it with too many updates. Control+ * flow must be implemented by the listener implementation ensuring that not too+ * many updates are created.*/-public interface PushCommand extends EventProducerCommand {+public interface PushCommand extends SensorUpdateCommand {/*** This method may be invoked multiple times if the command instance is associateddiff --git a/controller/src/main/java/org/openremote/controller/command/SensorUpdateCommand.java b/controller/src/main/java/org/openremote/controller/command/SensorUpdateCommand.javanew file mode 100644index 000000000..4c9f1add4--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/command/SensorUpdateCommand.java@@ -0,0 +1,7 @@+package org.openremote.controller.command;++/**+ * A command that can be used to update the state of a sensor.+ */+public interface SensorUpdateCommand extends Command {+}diff --git a/controller/src/main/java/org/openremote/controller/command/builtin/DateTimeCommand.java b/controller/src/main/java/org/openremote/controller/command/builtin/DateTimeCommand.javaindex 41e68edf6..c14ac7739 100644--- a/controller/src/main/java/org/openremote/controller/command/builtin/DateTimeCommand.java+++ b/controller/src/main/java/org/openremote/controller/command/builtin/DateTimeCommand.java@@ -5,7 +5,7 @@ import com.luckycatlabs.sunrisesunset.dto.Location;import org.openremote.container.util.TextUtil;import org.openremote.controller.command.PushCommand;import org.openremote.controller.deploy.CommandDefinition;-import org.openremote.controller.model.Sensor;+import org.openremote.controller.sensor.Sensor;import java.text.SimpleDateFormat;import java.util.Calendar;@@ -155,7 +155,6 @@ public class DateTimeCommand implements PushCommand, Runnable {@Overridepublic void start(Sensor sensor) {- LOG.fine("*** setSensor called as part of EventListener init *** sensor is: " + sensor);if (pollingInterval == null) {throw new RuntimeException("Could not set sensor because no polling interval was given");}diff --git a/controller/src/main/java/org/openremote/controller/command/builtin/VirtualCommand.java b/controller/src/main/java/org/openremote/controller/command/builtin/VirtualCommand.javaindex 4c9c7f6e3..e599550f1 100644--- a/controller/src/main/java/org/openremote/controller/command/builtin/VirtualCommand.java+++ b/controller/src/main/java/org/openremote/controller/command/builtin/VirtualCommand.java@@ -3,7 +3,7 @@ package org.openremote.controller.command.builtin;import org.openremote.controller.command.ExecutableCommand;import org.openremote.controller.command.PullCommand;import org.openremote.controller.deploy.CommandDefinition;-import org.openremote.controller.model.*;+import org.openremote.controller.sensor.*;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;@@ -159,7 +159,7 @@ public class VirtualCommand implements ExecutableCommand, PullCommand {return "0";}}- } else if (sensor instanceof CustomStateSensor) {+ } else if (sensor instanceof CustomSensor) {return (state == null) ? "" : state;} else {throw new Error(diff --git a/controller/src/main/java/org/openremote/controller/context/ControllerContext.java b/controller/src/main/java/org/openremote/controller/context/ControllerContext.javaindex 6d028a2a3..a4fa3934b 100644--- a/controller/src/main/java/org/openremote/controller/context/ControllerContext.java+++ b/controller/src/main/java/org/openremote/controller/context/ControllerContext.java@@ -1,10 +1,10 @@package org.openremote.controller.context;-import org.openremote.controller.event.Event;-import org.openremote.controller.event.EventProcessingContext;-import org.openremote.controller.event.EventProcessorChain;-import org.openremote.controller.model.Deployment;-import org.openremote.controller.model.Sensor;+import org.openremote.controller.rules.RuleEngine;+import org.openremote.controller.sensor.SensorState;+import org.openremote.controller.sensor.SensorStateUpdate;+import org.openremote.controller.deploy.Deployment;+import org.openremote.controller.sensor.Sensor;import org.openremote.controller.command.Commands;import java.util.logging.Level;@@ -19,14 +19,14 @@ public class ControllerContext {final protected String controllerID;final protected Deployment deployment;- final protected EventProcessorChain eventProcessorChain;+ final protected RuleEngine ruleEngine;private volatile Boolean shutdownInProgress = false;public ControllerContext(String controllerID, Deployment deployment) {this.controllerID = controllerID;this.deployment = deployment;- this.eventProcessorChain = new EventProcessorChain(deployment);+ this.ruleEngine = new RuleEngine(deployment);}public String getControllerID() {@@ -41,25 +41,25 @@ public class ControllerContext {return getDeployment().getCommands();}- protected StateStorage getStateStorage() {- return getDeployment().getStateStorage();+ protected SensorStateStorage getStateStorage() {+ return getDeployment().getSensorStateStorage();}public synchronized void start() {if (shutdownInProgress)return;LOG.info("Starting context: " + getControllerID());- eventProcessorChain.start();+ ruleEngine.start();for (Sensor sensor : deployment.getSensors()) {// Put initial state "unknown" for each sensor- getStateStorage().put(new SensorState(new Sensor.UnknownEvent(sensor)));+ getStateStorage().put(new Sensor.UnknownState(sensor));sensor.start(this);}}/*** <ul>- * <li>event processors are stopped</li>+ * <li>rule engine is stopped</li>* <li>sensors are stopped</li>* <li>the current state is cleared</li>* </ul>@@ -68,7 +68,7 @@ public class ControllerContext {try {LOG.info("Stopping context: " + getControllerID());shutdownInProgress = true;- eventProcessorChain.stop();+ ruleEngine.stop();for (Sensor sensor : deployment.getSensors()) {try {sensor.stop();@@ -82,44 +82,45 @@ public class ControllerContext {}}- public synchronized void update(Event event) {- LOG.fine("==> Update from event: " + event);+ public synchronized void update(SensorState sensorState) {+ LOG.fine("==> Update: " + sensorState);if (shutdownInProgress) {- LOG.fine("<== Shutting down. Ignoring update from: " + event.getSource());+ LOG.fine("<== Shutting down. Ignoring update from: " + sensorState.getSensorName());return;}- EventProcessingContext ctx = new EventProcessingContext(this, event);- eventProcessorChain.push(ctx);+ SensorStateUpdate sensorStateUpdate = new SensorStateUpdate(this, sensorState);++ ruleEngine.process(sensorStateUpdate);// Early exist if one of the processors decided to terminate the chain- if (ctx.hasTerminated()) {- LOG.fine("<== Updating status complete, event context terminated, no update was made for event: " + ctx.getEvent());+ if (sensorStateUpdate.hasTerminated()) {+ LOG.fine("<== Update complete, processing terminated, no update was made for: " + sensorStateUpdate.getSensorState());return;}- getStateStorage().put(new SensorState(event));- LOG.fine("<== Updating status complete for event: " + event);+ getStateStorage().put(sensorState);+ LOG.fine("<== Update complete for: " + sensorState);}public String queryValue(int sensorID) {if (!getStateStorage().contains(sensorID)) {- LOG.info("Requested sensor id '" + sensorID + "' was not found. Defaulting to: " + Sensor.UNKNOWN_STATUS);- return Sensor.UNKNOWN_STATUS;+ LOG.info("Requested sensor id '" + sensorID + "' was not found. Defaulting to: " + Sensor.UNKNOWN_STATE_VALUE);+ return Sensor.UNKNOWN_STATE_VALUE;}- return getStateStorage().get(sensorID).getEvent().serialize();+ return getStateStorage().get(sensorID).serialize();}public String queryValue(String sensorName) {return queryValue(deployment.getSensorID(sensorName));}- public Event queryEvent(int sensorID) {- return getStateStorage().get(sensorID).getEvent();+ public SensorState queryState(int sensorID) {+ return getStateStorage().get(sensorID);}- public Event queryEvent(String sensorName) {+ public SensorState queryState(String sensorName) {Integer sensorID = deployment.getSensorID(sensorName);- return sensorID != null ? queryEvent(sensorID) : null;+ return sensorID != null ? queryState(sensorID) : null;}}diff --git a/controller/src/main/java/org/openremote/controller/context/InMemoryStateStorage.java b/controller/src/main/java/org/openremote/controller/context/InMemorySensorStateStorage.javasimilarity index 60%rename from controller/src/main/java/org/openremote/controller/context/InMemoryStateStorage.javarename to controller/src/main/java/org/openremote/controller/context/InMemorySensorStateStorage.javaindex 2da2b98c5..e558f84a3 100644--- a/controller/src/main/java/org/openremote/controller/context/InMemoryStateStorage.java+++ b/controller/src/main/java/org/openremote/controller/context/InMemorySensorStateStorage.java@@ -1,14 +1,14 @@package org.openremote.controller.context;-import org.openremote.controller.event.Event;+import org.openremote.controller.sensor.SensorState;import java.util.HashMap;import java.util.Map;import java.util.logging.Logger;-public class InMemoryStateStorage implements StateStorage {+public class InMemorySensorStateStorage implements SensorStateStorage {- private static final Logger LOG = Logger.getLogger(InMemoryStateStorage.class.getName());+ private static final Logger LOG = Logger.getLogger(InMemorySensorStateStorage.class.getName());final protected Map<Integer, SensorState> sensorStates = new HashMap<>();@@ -19,19 +19,18 @@ public class InMemoryStateStorage implements StateStorage {@Overridesynchronized public void put(SensorState sensorState) {- Event event = sensorState.getEvent();- int sourceID = event.getSourceID();+ int sourceID = sensorState.getSensorID();if (sensorStates.get(sourceID) == null) {- LOG.fine("Inserted: " + event);- sensorStates.put(sourceID, new SensorState(event));+ LOG.fine("Inserted: " + sensorState);+ sensorStates.put(sourceID, sensorState);} else {SensorState previousState = sensorStates.get(sourceID);- if (previousState.getEvent().equals(event)) {- LOG.fine("No change, stored state equals: " + event);+ if (previousState.equals(sensorState)) {+ LOG.fine("No change, stored state equals: " + sensorState);return;}- LOG.fine("Updated: " + event);- sensorStates.put(sourceID, new SensorState(event));+ LOG.fine("Updated: " + sensorState);+ sensorStates.put(sourceID, sensorState);}}diff --git a/controller/src/main/java/org/openremote/controller/context/SensorState.java b/controller/src/main/java/org/openremote/controller/context/SensorState.javadeleted file mode 100644index e9b1ea84c..000000000--- a/controller/src/main/java/org/openremote/controller/context/SensorState.java+++ /dev/null@@ -1,29 +0,0 @@-package org.openremote.controller.context;--import org.openremote.controller.event.Event;--public class SensorState {-- final protected long timestamp = System.currentTimeMillis();- final protected Event event;-- public SensorState(Event event) {- this.event = event;- }-- public Event getEvent() {- return event;- }-- public boolean isNewerThan(long timestamp) {- return this.timestamp < timestamp;- }-- @Override- public String toString() {- return "SensorState{" +- "timestamp=" + timestamp +- ", event=" + event +- '}';- }-}diff --git a/controller/src/main/java/org/openremote/controller/context/StateStorage.java b/controller/src/main/java/org/openremote/controller/context/SensorStateStorage.javasimilarity index 78%rename from controller/src/main/java/org/openremote/controller/context/StateStorage.javarename to controller/src/main/java/org/openremote/controller/context/SensorStateStorage.javaindex a8dc90879..6e69eb272 100644--- a/controller/src/main/java/org/openremote/controller/context/StateStorage.java+++ b/controller/src/main/java/org/openremote/controller/context/SensorStateStorage.java@@ -1,9 +1,11 @@package org.openremote.controller.context;+import org.openremote.controller.sensor.SensorState;+/*** Store controller context (sensor) state.*/-public interface StateStorage {+public interface SensorStateStorage {void clear();@@ -14,7 +16,7 @@ public interface StateStorage {SensorState get(int sensorID);- /* TODO For polling/pushing to external system we need to be able to continue processing events from a known offset+ /* TODO For polling/pushing to external system we need to be able to continue processing state from a known offsetIterator<SensorState> getSince(int timestamp);Iterator<SensorState> getSince(int timestamp, int sensorID);diff --git a/controller/src/main/java/org/openremote/controller/model/Deployment.java b/controller/src/main/java/org/openremote/controller/deploy/Deployment.javasimilarity index 74%rename from controller/src/main/java/org/openremote/controller/model/Deployment.javarename to controller/src/main/java/org/openremote/controller/deploy/Deployment.javaindex be5678a6c..0527f41aa 100644--- a/controller/src/main/java/org/openremote/controller/model/Deployment.java+++ b/controller/src/main/java/org/openremote/controller/deploy/Deployment.java@@ -1,14 +1,9 @@-package org.openremote.controller.model;--import org.openremote.controller.command.Command;-import org.openremote.controller.command.CommandBuilder;-import org.openremote.controller.command.Commands;-import org.openremote.controller.command.EventProducerCommand;-import org.openremote.controller.context.StateStorage;-import org.openremote.controller.deploy.CommandDefinition;-import org.openremote.controller.deploy.DeploymentDefinition;-import org.openremote.controller.deploy.SensorDefinition;-import org.openremote.controller.event.EventProcessor;+package org.openremote.controller.deploy;++import org.openremote.controller.command.*;+import org.openremote.controller.context.SensorStateStorage;+import org.openremote.controller.rules.RulesProvider;+import org.openremote.controller.sensor.*;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;@@ -18,7 +13,7 @@ import java.util.concurrent.ConcurrentHashMap;* <pre>* - How protocol-specific commands are build* - How controller sensor state is stored- * - How sensor events are processed+ * - Which rules process sensor state updates* - All known sensors, commands and their devices* </pre>*/@@ -26,20 +21,20 @@ public class Deployment {final protected CommandBuilder commandBuilder;final protected Commands commands;- final protected StateStorage stateStorage;- final protected EventProcessor[] eventProcessors;+ final protected SensorStateStorage sensorStateStorage;+ final protected RulesProvider rulesProvider;final protected Map<String, Device> devices = new ConcurrentHashMap<>();final protected Map<Integer, Sensor> sensors = new ConcurrentHashMap<>();public Deployment(DeploymentDefinition deploymentDefinition,CommandBuilder commandBuilder,- StateStorage stateStorage,- EventProcessor... eventProcessors) {+ SensorStateStorage sensorStateStorage,+ RulesProvider rulesProvider) {this.commandBuilder = commandBuilder;- this.stateStorage = stateStorage;- this.eventProcessors = eventProcessors;this.commands = new Commands(this);+ this.sensorStateStorage = sensorStateStorage;+ this.rulesProvider = rulesProvider;for (SensorDefinition sensorDefinition : deploymentDefinition.getSensorDefinitions()) {Sensor sensor = buildSensor(sensorDefinition);@@ -68,12 +63,12 @@ public class Deployment {return commands;}- public StateStorage getStateStorage() {- return stateStorage;+ public SensorStateStorage getSensorStateStorage() {+ return sensorStateStorage;}- public EventProcessor[] getEventProcessors() {- return eventProcessors;+ public RulesProvider getRulesProvider() {+ return rulesProvider;}public CommandDefinition getCommandDefinition(int commandID) {@@ -137,13 +132,13 @@ public class Deployment {protected Sensor buildSensor(SensorDefinition sensorDefinition) {Sensor sensor;- Command command = commandBuilder.build(sensorDefinition.getCommandDefinition());- EventProducerCommand sensorCommand;- if (command instanceof EventProducerCommand) {- sensorCommand = (EventProducerCommand) command;+ Command command = commandBuilder.build(sensorDefinition.getUpdateCommandDefinition());+ SensorUpdateCommand updateCommand;+ if (command instanceof SensorUpdateCommand) {+ updateCommand = (SensorUpdateCommand) command;} else {throw new IllegalStateException(- "Sensor must reference EventProducerCommand, not '" + command + "': " + sensorDefinition+ "Sensor must reference " + SensorUpdateCommand.class.getSimpleName() + ", not '" + command + "': " + sensorDefinition);}@@ -155,28 +150,28 @@ public class Deployment {String maxValue = sensorDefinition.getProperties().get("range-max");if (maxValue == null)throw new IllegalStateException("Sensor of range type must have min/max value defined: " + sensorDefinition);- sensor = new RangeSensor(sensorDefinition, sensorCommand, Integer.valueOf(minValue), Integer.valueOf(maxValue));+ sensor = new RangeSensor(sensorDefinition, updateCommand, Integer.valueOf(minValue), Integer.valueOf(maxValue));break;case "level":- sensor = new LevelSensor(sensorDefinition, sensorCommand);+ sensor = new LevelSensor(sensorDefinition, updateCommand);break;case "custom":- CustomStateSensor.DistinctStates distinctStates = new CustomStateSensor.DistinctStates();+ CustomSensor.DistinctStates distinctStates = new CustomSensor.DistinctStates();for (Map.Entry<String, String> entry : sensorDefinition.getProperties().entrySet()) {if (entry.getKey().startsWith("state-")) {distinctStates.addStateMapping(entry.getKey().substring(6), entry.getValue());}}- sensor = new CustomStateSensor(sensorDefinition, sensorCommand, distinctStates, false);+ sensor = new CustomSensor(sensorDefinition, updateCommand, distinctStates, false);break;case "switch":- distinctStates = new CustomStateSensor.DistinctStates();+ distinctStates = new CustomSensor.DistinctStates();for (Map.Entry<String, String> entry : sensorDefinition.getProperties().entrySet()) {if (entry.getKey().startsWith("state-")) {distinctStates.addStateMapping(entry.getKey().substring(6), entry.getValue());}}- sensor = new SwitchSensor(sensorDefinition, sensorCommand, distinctStates);+ sensor = new SwitchSensor(sensorDefinition, updateCommand, distinctStates);break;default:throw new IllegalArgumentException("Unsupported sensor type: " + sensorDefinition);diff --git a/controller/src/main/java/org/openremote/controller/model/Device.java b/controller/src/main/java/org/openremote/controller/deploy/Device.javasimilarity index 90%rename from controller/src/main/java/org/openremote/controller/model/Device.javarename to controller/src/main/java/org/openremote/controller/deploy/Device.javaindex ab1310014..3417b6586 100644--- a/controller/src/main/java/org/openremote/controller/model/Device.java+++ b/controller/src/main/java/org/openremote/controller/deploy/Device.java@@ -1,10 +1,11 @@-package org.openremote.controller.model;--import org.openremote.controller.deploy.CommandDefinition;+package org.openremote.controller.deploy;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;+/**+ * A device is simply a collection of command definitions.+ */public class Device {final protected int deviceID;diff --git a/controller/src/main/java/org/openremote/controller/deploy/SensorDefinition.java b/controller/src/main/java/org/openremote/controller/deploy/SensorDefinition.javaindex e4653dd7c..d53cebf90 100644--- a/controller/src/main/java/org/openremote/controller/deploy/SensorDefinition.java+++ b/controller/src/main/java/org/openremote/controller/deploy/SensorDefinition.java@@ -11,25 +11,25 @@ public class SensorDefinition {final protected int sensorID;final protected String name;final protected String type;- final protected CommandDefinition commandDefinition;+ final protected CommandDefinition updateCommandDefinition;final protected Map<String, String> properties;/**- * @param name Human readable name of the sensor. Used with event processors, logging, etc.- * @param sensorID A unique sensor ID. Must be unique per controller deployment.- * @param type A sensor type.- * @param commandDefinition A command definition used to update sensor values.- * @param properties Additional sensor properties. These properties can be used by the protocol- * implementors to direct their implementation according to sensor configuration.+ * @param name Human readable name of the sensor.+ * @param sensorID A unique sensor ID. Must be unique per controller deployment.+ * @param type A sensor type.+ * @param updateCommandDefinition A command definition used to update sensor values.+ * @param properties Additional sensor properties. These properties can be used by the protocol+ * implementors to direct their implementation according to sensor configuration.*/- public SensorDefinition(int sensorID, String name, String type, CommandDefinition commandDefinition, Map<String, String> properties) {+ public SensorDefinition(int sensorID, String name, String type, CommandDefinition updateCommandDefinition, Map<String, String> properties) {if (properties == null) {properties = new HashMap<>(0);}this.sensorID = sensorID;this.name = name;this.type = type;- this.commandDefinition = commandDefinition;+ this.updateCommandDefinition = updateCommandDefinition;this.properties = properties;}@@ -45,8 +45,8 @@ public class SensorDefinition {return type;}- public CommandDefinition getCommandDefinition() {- return commandDefinition;+ public CommandDefinition getUpdateCommandDefinition() {+ return updateCommandDefinition;}/**@@ -70,7 +70,7 @@ public class SensorDefinition {", name=" + getName() +", type=" + getType() +", properties=" + properties +- ", commandDefinition=" + getCommandDefinition() ++ ", updateCommandDefinition=" + getUpdateCommandDefinition() +'}';}diff --git a/controller/src/main/java/org/openremote/controller/event/CustomStateEvent.java b/controller/src/main/java/org/openremote/controller/event/CustomStateEvent.javadeleted file mode 100644index 57f37942e..000000000--- a/controller/src/main/java/org/openremote/controller/event/CustomStateEvent.java+++ /dev/null@@ -1,68 +0,0 @@-package org.openremote.controller.event;--/**- * Custom state event is a very basic event type that simply holds any arbitrary string- * as its value. No semantics or rules are applied to the value string.- * <p>- * Custom state events are associated with 'custom' sensors in controller definition.- */-public class CustomStateEvent extends Event<String> {-- private String eventValue;- private String originalState;-- /**- * Constructs a new custom state event with a given source sensor's ID, source sensors name- * and event value.- *- * @param sourceSensorID the integer ID of the sensor that originated this event- * @param sourceSensorName the human-readable name of the sensor that originated this event- * @param eventValue an arbitrary string value of this event- */- public CustomStateEvent(int sourceSensorID, String sourceSensorName, String eventValue) {- super(sourceSensorID, sourceSensorName);- this.eventValue = eventValue;- this.originalState = this.eventValue;- }-- public CustomStateEvent(int sourceSensorID, String sourceSensorName, String eventValue, String originalState) {- this(sourceSensorID, sourceSensorName, eventValue);- this.originalState = originalState;- }-- public String getOriginalState() {- return originalState;- }-- @Override- public String getValue() {- return eventValue;- }-- @Override- public void setValue(String value) {- this.eventValue = value;- }-- @Override- public String serialize() {- return eventValue;- }-- @Override- public CustomStateEvent clone(String newValue) {- // TODO What is this?- throw new Error("NYI");- }-- @Override- public String toString() {- return "CustomStateEvent{" +- "sourceId=" + getSourceID() +- ", source='" + getSource() + "'" +- ", eventValue='" + eventValue + '\'' +- ", originalState='" + originalState + '\'' +- '}';- }-}-diff --git a/controller/src/main/java/org/openremote/controller/event/Event.java b/controller/src/main/java/org/openremote/controller/event/Event.javadeleted file mode 100644index c8e650ddb..000000000--- a/controller/src/main/java/org/openremote/controller/event/Event.java+++ /dev/null@@ -1,58 +0,0 @@-package org.openremote.controller.event;--public abstract class Event<T> {-- final protected int sourceSensorID;- final protected String sourceSensorName;-- public Event(int sourceSensorID, String sourceSensorName) {- this.sourceSensorID = sourceSensorID;- this.sourceSensorName = sourceSensorName;- }-- public Integer getSourceID() {- return sourceSensorID;- }-- public String getSource() {- return sourceSensorName;- }-- public abstract Event clone(T newValue);-- public abstract T getValue();-- public abstract void setValue(T value);-- /**- * This method implementation should return an appropriate string representation of the event value.- * This string will be returned by {@link org.openremote.controller.context.ControllerContext#queryValue}.- */- public abstract String serialize();-- /**- * Events are compared by ID, source, and value.- */- @Override- public boolean equals(Object o) {- if (o == null) {- return false;- }-- if (o.getClass() != this.getClass()) {- return false;- }-- Event evt = (Event) o;-- return evt.getSourceID().equals(this.getSourceID()) &&- evt.getSource().equals(this.getSource()) &&- evt.getValue().equals(this.getValue());- }-- @Override- public int hashCode() {- return getSourceID() + getSource().hashCode() + getValue().hashCode();- }-}-diff --git a/controller/src/main/java/org/openremote/controller/event/EventProcessingContext.java b/controller/src/main/java/org/openremote/controller/event/EventProcessingContext.javadeleted file mode 100644index 523686d9c..000000000--- a/controller/src/main/java/org/openremote/controller/event/EventProcessingContext.java+++ /dev/null@@ -1,53 +0,0 @@-package org.openremote.controller.event;--import org.openremote.controller.context.ControllerContext;--import java.util.logging.Logger;--/**- * Before the {@link ControllerContext} accepts an update from an event, it executes the- * {@link EventProcessorChain} with a fresh instance of {@link EventProcessingContext}.- * The event processing context encapsulates a single event and its journey through the- * system.- *- * Processors can access the event context and if they desire, terminate it. This means the- * original event will be discarded and not make it into the {@link ControllerContext}.- *- * TODO Or, as we call it now, a Camel Exchange.- */-public class EventProcessingContext {-- private static final Logger LOG = Logger.getLogger(EventProcessingContext.class.getName());-- private ControllerContext controllerContext;- private Event event;- private boolean terminated = false;-- public EventProcessingContext(ControllerContext controllerContext, Event evt) {- this.controllerContext = controllerContext;- this.event = evt;- }-- public void terminate() {- LOG.fine("Terminating event context");- terminated = true;- }-- public boolean hasTerminated() {- return terminated;- }-- public ControllerContext getControllerContext() {- return controllerContext;- }-- public Event getEvent() {- return event;- }-- @Override- public String toString() {- return "Event Context for " + event;- }-}-diff --git a/controller/src/main/java/org/openremote/controller/event/EventProcessor.java b/controller/src/main/java/org/openremote/controller/event/EventProcessor.javadeleted file mode 100644index 78afd17dd..000000000--- a/controller/src/main/java/org/openremote/controller/event/EventProcessor.java+++ /dev/null@@ -1,20 +0,0 @@-package org.openremote.controller.event;--import org.openremote.controller.model.Deployment;--/**- * Process events before they are reaching the controller context.- */-public abstract class EventProcessor {-- public void start(Deployment deployment) throws Exception{- }-- public void stop() {- }-- public abstract void process(EventProcessingContext ctx);-- public abstract String getName();-}-diff --git a/controller/src/main/java/org/openremote/controller/event/EventProcessorChain.java b/controller/src/main/java/org/openremote/controller/event/EventProcessorChain.javadeleted file mode 100644index 278dc81fe..000000000--- a/controller/src/main/java/org/openremote/controller/event/EventProcessorChain.java+++ /dev/null@@ -1,69 +0,0 @@-package org.openremote.controller.event;--import org.openremote.controller.model.Deployment;--import java.util.logging.Level;-import java.util.logging.Logger;--/**- * A chain of event processors that incoming events (values) are passing through before- * a value might change in the {@link org.openremote.controller.context.ControllerContext}.- *- * Event processors may modify the existing event payload value, discard events- * entirely or spawn multiple other events that are interacting with the- * @{link {@link org.openremote.controller.context.ControllerContext}.- *- * TODO Or, as we call it now, a Camel route.- */-public class EventProcessorChain {-- private static final Logger LOG = Logger.getLogger(EventProcessorChain.class.getName());-- final protected Deployment deployment;-- public EventProcessorChain(Deployment deployment) {- this.deployment = deployment;- }-- public void start() {- for (EventProcessor ep : deployment.getEventProcessors()) {- try {- LOG.info("Starting event processor: " + ep.getName());- ep.start(deployment);- } catch (Throwable t) {- LOG.log(Level.SEVERE, "Cannot start event processor: " + ep.getName(), t);- }- }- }-- public void stop() {- for (EventProcessor ep : deployment.getEventProcessors()) {- try {- LOG.info("Stopping event processor: " + ep.getName());- ep.stop();- } catch (Throwable t) {- LOG.log(Level.SEVERE, "Cannot stop event processor: " + ep.getName(), t);- }- }- }-- /**- * Pushes an event through a stack of event processors. The returned event is the result of- * modifications of all configured event processors (specifically as returned by the last- * event processor in the stack).- */- public void push(EventProcessingContext ctx) {- for (EventProcessor processor : deployment.getEventProcessors()) {- LOG.fine("Processing: " + ctx.getEvent());- processor.process(ctx);- if (ctx.hasTerminated()) {- LOG.log(Level.FINE, "Ignoring original event, context was terminated (new event?), chain stopped at: " + processor);- return;- } else {- LOG.fine("Event '" + ctx.getEvent() + "' processed by: " + processor.getName());- }- }- LOG.fine("Processing of event complete: " + ctx.getEvent());- }-}-diff --git a/controller/src/main/java/org/openremote/controller/event/LevelEvent.java b/controller/src/main/java/org/openremote/controller/event/LevelEvent.javadeleted file mode 100644index 57639564e..000000000--- a/controller/src/main/java/org/openremote/controller/event/LevelEvent.java+++ /dev/null@@ -1,71 +0,0 @@-package org.openremote.controller.event;--import java.util.logging.Logger;--/**- * Level events are integer based events where values have been limited to a range of- * [0..100]- * <p>- * Level events are associated with sensors of 'level' type in controller.xml model.- */-public class LevelEvent extends RangeEvent {-- private static final Logger LOG = Logger.getLogger(LevelEvent.class.getName());-- /**- * Validate range value to [0..100].- *- * @param sensorID originating sensor ID- * @param sensorName originating sensor name- * @param value event value- * @return event value unless it is exceeding LEVEL limits in which case it has been limited- * to range [0..100]- */- private static int validate(int sensorID, String sensorName, int value) {- if (value > 100) {- value = 100;- LOG.log(java.util.logging.Level.WARNING,- "A LEVEL event was created with an invalid value : {0} (Source Sensor = {1} - {2}). " +- "The event value has been limited to maximum value of 100.", new Object[]{value, sensorID, sensorName}- );- }-- if (value < 0) {- value = 0;- LOG.log(java.util.logging.Level.WARNING,- "A LEVEL event was create with an invalid value : {0} (Source Sensor = {1} - {2}). " +- "The event value has been limited to minimum value of 0.", new Object[]{value, sensorID, sensorName}- );- }- return value;- }-- /**- * Constructs a new LEVEL event with a given originating sensor ID, originating sensor name- * and event value.- * <p>- * Level events are associated with sensors of 'level' type in controller.xml model.- * <p>- * Level event values must be restricted to a range of [0..100].- *- * @param sourceSensorID originating sensor's ID- * @param sourceSensorName originating sensor's name- * @param value level event value- */- public LevelEvent(int sourceSensorID, String sourceSensorName, int value) {- super(sourceSensorID, sourceSensorName, validate(sourceSensorID, sourceSensorName, value), 0, 100);- }-- public LevelEvent clone(int newValue) {- return new LevelEvent(getSourceID(), getSource(), newValue);- }-- @Override- public String toString() {- return "LevelEvent{" +- "sourceId=" + getSourceID() +- ", source='" + getSource() + "'" +- "}";- }-}-diff --git a/controller/src/main/java/org/openremote/controller/event/SwitchEvent.java b/controller/src/main/java/org/openremote/controller/event/SwitchEvent.javadeleted file mode 100644index d32d5552c..000000000--- a/controller/src/main/java/org/openremote/controller/event/SwitchEvent.java+++ /dev/null@@ -1,100 +0,0 @@-/*- * OpenRemote, the Home of the Digital Home.- * Copyright 2008-2011, OpenRemote Inc.- *- * See the contributors.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.controller.event;--public class SwitchEvent extends Event<String> {-- public enum State {- ON("on"),- OFF("off");-- private String serializedFormat;-- State(String serializedStringFormat) {- this.serializedFormat = serializedStringFormat;- }-- public String serialize() {- return serializedFormat;- }- }-- private String switchValue;- private State switchState;-- public SwitchEvent(int sourceID, String sourceName, String switchValue, State switchState) {- super(sourceID, sourceName);-- this.switchState = switchState;- this.switchValue = switchValue;- }-- public SwitchEvent(int sourceID, String sourceName, State switchState) {- this(sourceID, sourceName, switchState.serialize(), switchState);- }-- public State getState() {- return switchState;- }-- public SwitchEvent clone(String eventValue, SwitchEvent.State state) {- if (eventValue == null) {- eventValue = state.serialize();- }-- return new SwitchEvent(getSourceID(), getSource(), eventValue, state);- }-- @Override- public SwitchEvent clone(String newValue) {- if (newValue.equalsIgnoreCase(SwitchEvent.State.ON.serialize())) {- return clone(null, SwitchEvent.State.ON);- } else {- return clone(null, SwitchEvent.State.OFF);- }- }-- @Override- public String getValue() {- return switchValue;- }-- @Override- public void setValue(String value) {- this.switchValue = value;- }-- @Override- public String serialize() {- return getValue();- }-- @Override- public String toString() {- return "SwitchEvent{" +- "sourceId=" + getSourceID() +- ", source='" + getSource() + "'" +- ", switchValue='" + switchValue + '\'' +- ", switchState=" + switchState +- '}';- }-}-diff --git a/controller/src/main/java/org/openremote/controller/model/CustomStateSensor.java b/controller/src/main/java/org/openremote/controller/model/CustomStateSensor.javadeleted file mode 100644index 847eaaf3a..000000000--- a/controller/src/main/java/org/openremote/controller/model/CustomStateSensor.java+++ /dev/null@@ -1,221 +0,0 @@-package org.openremote.controller.model;--import org.openremote.controller.command.EventProducerCommand;-import org.openremote.controller.command.PullCommand;-import org.openremote.controller.command.PushCommand;-import org.openremote.controller.deploy.SensorDefinition;-import org.openremote.controller.event.CustomStateEvent;-import org.openremote.controller.event.Event;--import java.util.HashMap;-import java.util.Map;-import java.util.Set;-import java.util.logging.Logger;--/**- * A state sensor operates on a finite set of explicit state values that it returns.- * <p>- * Explicit state values returned from a command implementation may- * be mapped to other values to accommodate human-consumable values for the panel UI- * for example, or as a translation mechanism for localized interfaces.- * <p>- * By default the explicit state strings this sensor expects the event producers to return are- * available as sensor properties through the {@link PullCommand} and {@link PushCommand} APIs.- * <p>- * See {@link DistinctStates} for more details.- */-public class CustomStateSensor extends Sensor {-- private static final Logger LOG = Logger.getLogger(CustomStateSensor.class.getName());-- final protected DistinctStates states;- final protected boolean strictStateMapping;-- /**- * Constructs a new sensor with a given sensor ID, event producer and distinct state values- * this sensor will return.- * <p>- * This constructor allows subclasses to determine whether the distinct states are passed- * as sensor properties through the {@link PullCommand}- * and {@link PushCommand} interface -- when the sensor's- * type (such as {@link org.openremote.controller.model.SwitchSensor}) makes the available- * states explicit, it may not be necessary to pass the additional property information to- * event producer implementers.- *- * @param producer the data/event producing command implementation that backs this sensor- * @param states distinct state values and their mappings this sensor will return- * @param strictStateMapping Indicates whether this sensor instance should enforce strict state mapping rules -- when- * enabled, only state values explicitly declared for this sensor will be accepted and returned.- * If set to false, all values are allowed but those with value mappings will be converted.- */- public CustomStateSensor(SensorDefinition sensorDefinition, EventProducerCommand producer, DistinctStates states, boolean strictStateMapping) {- super(sensorDefinition, producer);- if (states == null) {- this.states = new DistinctStates();- } else {- this.states = states;- }- this.strictStateMapping = strictStateMapping;- }-- /**- * Constructs an event from the raw protocol output string. This implementation checks the- * incoming value for possible state mappings and returns an event containing the mapped- * state value where necessary. Arbitrary, non-declared states are rejected unless- * {@link #strictStateMapping} has been set to false. When set to true, an- * instance of {@link org.openremote.controller.model.Sensor.UnknownEvent} is returned- * for any non-declared state.- *- * @return An event containing the state returned by the associated event producer or- * a translated (mapped) version of the state string. Can return- * {@link org.openremote.controller.model.Sensor.UnknownEvent} in case where- * {@link #strictStateMapping} is true and a state value is returned from the- * event producer that has not been declared as a distinct state for this sensor.- */- @Override- public Event processEvent(String value) {- if (!states.hasState(value)) {- if (isUnknownSensorValue(value)) {- return new UnknownEvent(this);- }-- if (strictStateMapping) {- LOG.warning("Event producer's value is not consistent with '" + getSensorDefinition() + "': " + value);- return new UnknownEvent(this);- } else {- return createEvent(value);- }- }-- if (!states.hasMapping(value)) {- return createEvent(value);- } else {- return createEvent(states.getMapping(value), value);- }- }-- /**- * Constructs an event for this sensor with a given state value. Subclasses can override this- * implementation to provide their own specific event types.- *- * @param value event value- * @return new event instance associated with this sensor- */- protected Event createEvent(String value) {- return new CustomStateEvent(getSensorDefinition().getSensorID(), getSensorDefinition().getName(), value);- }-- /**- * Constructs an event for this sensor with a given state value, and the originating value- * when state mapping (translation) was used. Subclasses can override this implementation to- * provide their own specific event types.- *- * @param value the translated (mapped) event value- * @param originalValue the original event value returned by the associated event producer- * @return new event instance associated with this sensor- */- protected Event createEvent(String value, String originalValue) {- return new CustomStateEvent(getSensorDefinition().getSensorID(), getSensorDefinition().getName(), value, originalValue);- }-- /**- * Helper class to store the distinct state values for a state sensor and possible value- * mappings if configured.- * <p>- * Each state is available to {@link EventProducerCommand} implementers through the sensor- * properties passed via the {@link PullCommand} and {@link PushCommand} APIs. The expected- * state values can be found using a key 'state-1' for the first available state string to- * 'state-n' to the last expected state value.- */- public static class DistinctStates {-- private Map<String, String> states = new HashMap<>();-- /**- * Store an explicit state value without mapping.- *- * @param state explicit state string the event producers are expected to return from- * their {@link PullCommand} or- * {@link PushCommand} implementations.- */- public void addState(String state) {- states.put(state, null);- }-- /**- * Stores an explicit state value with mapping. When the event producer returns the state- * value, it is automatically mapped to a new value to be consumed by UI widgets and other- * users of the sensor.- *- * @param state the state string returned by event producer implementations- * @param mapping the value the state string is translated to by the sensor- */- public void addStateMapping(String state, String mapping) {- states.put(state, mapping);- }-- /**- * Indicates if the given state string is contained within this state collection- *- * @param value the requested state string- * @return true if the state string has been added, false otherwise- */- public boolean hasState(String value) {- return states.containsKey(value);- }-- /**- * Returns sensor's state mappings as a string. Implementation delegates to- * {@link Map#toString()}.- *- * @return all state mappings as a string- */- @Override- public String toString() {- return states.toString();- }-- /**- * Indicates if the given state string has a mapping in this state collection- *- * @param state the state string which mapping is requested- * @return true if the state string is mapped to another value in this state- * collection, false otherwise- */- private boolean hasMapping(String state) {- if (!hasState(state)) {- return false;- }- String mapping = states.get(state);- return mapping != null;- }-- /**- * Returns the mapped value of a state string.- *- * @param state the state string which mapping is requested- * @return returns the translated value of a given event producer state string or {@link #UNKNOWN_STATUS}- */- private String getMapping(String state) {- String mapping = states.get(state);- if (mapping == null) {- return UNKNOWN_STATUS;- }- return mapping;- }-- private Set<String> getAllStates() {- return states.keySet();- }- }-- @Override- public String toString() {- return getClass().getSimpleName() + "{" +- "sensorDefinition=" + getSensorDefinition() +- ", hasStrictStateMapping=" + strictStateMapping +- ", states=" + states +- '}';- }-}-diff --git a/controller/src/main/java/org/openremote/controller/model/SwitchSensor.java b/controller/src/main/java/org/openremote/controller/model/SwitchSensor.javadeleted file mode 100644index 2456e8e8d..000000000--- a/controller/src/main/java/org/openremote/controller/model/SwitchSensor.java+++ /dev/null@@ -1,89 +0,0 @@-package org.openremote.controller.model;--import org.bouncycastle.util.Strings;-import org.openremote.controller.command.EventProducerCommand;-import org.openremote.controller.deploy.SensorDefinition;-import org.openremote.controller.event.Event;-import org.openremote.controller.event.SwitchEvent;--import java.util.logging.Logger;--/**- * A boolean switch sensor type. This is a specific case of a state sensor with two 'on' or 'off'- * state strings. A switch sensor can be configured to map the default return values to other- * values ("open/close", "running/stoppped", etc.) or to translate return values to local- * languages.- */-public class SwitchSensor extends CustomStateSensor {-- private static final Logger LOG = Logger.getLogger(SwitchSensor.class.getName());-- /**- * Constructs a new switch sensor with given sensor ID, an event producer, and on/off state- * mapping. The distinct states should contain mapping <b>only</b> for 'on' and 'off' states- * in case of a switch.- * <p>- * The sensor implementation will return 'on or 'off' string values.- *- * @param producer the data/event producing command implementation that backs this sensor- * @param states state string mappings for the default 'on' and 'off' values- */- public SwitchSensor(SensorDefinition sensorDefinition, EventProducerCommand producer, DistinctStates states) {- super(sensorDefinition, producer, states, true);- }-- /**- * Constructs an event for this sensor instance with a given event value. Event value must be- * either 'on' or 'off' -- any other value will cause a- * {@link org.openremote.controller.model.Sensor.UnknownEvent} instance to be returned- * instead.- *- * @param value event value 'on' or 'off' -- case insensitive- * @return a new event instance for this sensor- */- @Override- protected Event createEvent(String value) {- return createEvent(value, value);- }-- /**- * Constructs an event for this sensor instance with a given mapped (translated) event value- * and the original event value which was used for the translation.- * <p>- * The original value must be either 'on' or 'off' (case insensitive), otherwise a- * {@link org.openremote.controller.model.Sensor.UnknownEvent} is returned instead. The- * translated value can be any arbitrary string value.- *- * @param value the translated (mapped) event value- * @param originalValue the original event value ('on' or 'off') returned by the associated- * event producer- * @return a new event instance for this sensor- */- @Override- protected Event createEvent(String value, String originalValue) {- try {- return new SwitchEvent(- getSensorDefinition().getSensorID(),- getSensorDefinition().getName(),- value,- SwitchEvent.State.valueOf(Strings.toUpperCase(originalValue.trim())) // TODO WTF- );- } catch (IllegalArgumentException e) {- if (!isUnknownSensorValue(originalValue)) {- LOG.warning(- "Switch event value not 'on' or 'off', got '" + originalValue + "' in: " + getSensorDefinition()- );- }- return new UnknownEvent(this);- }- }-- @Override- public String toString() {- return getClass().getSimpleName() + "{" +- "sensorDefinition=" + getSensorDefinition() +- ", states=" + states +- '}';- }-}-diff --git a/controller/src/main/java/org/openremote/controller/rules/EventFacade.java b/controller/src/main/java/org/openremote/controller/rules/EventFacade.javadeleted file mode 100644index 18b518d76..000000000--- a/controller/src/main/java/org/openremote/controller/rules/EventFacade.java+++ /dev/null@@ -1,27 +0,0 @@-package org.openremote.controller.rules;--import org.openremote.controller.event.Event;-import org.openremote.controller.event.EventProcessingContext;--import java.util.logging.Logger;--public abstract class EventFacade {-- private static final Logger LOG = Logger.getLogger(EventFacade.class.getName());-- protected EventProcessingContext eventProcessingContext;-- public void pushEventContext(EventProcessingContext ctx) {- this.eventProcessingContext = ctx;- }-- protected void dispatchEvent(final Event event) {- eventProcessingContext.terminate();- LOG.fine("Dispatching on new thread: " + event);- Thread t = new Thread(- () -> eventProcessingContext.getControllerContext().update(event)- );- t.start();- }-}-diff --git a/controller/src/main/java/org/openremote/controller/rules/LevelFacade.java b/controller/src/main/java/org/openremote/controller/rules/LevelFacade.javaindex 3348d0522..89177336f 100644--- a/controller/src/main/java/org/openremote/controller/rules/LevelFacade.java+++ b/controller/src/main/java/org/openremote/controller/rules/LevelFacade.java@@ -1,25 +1,25 @@package org.openremote.controller.rules;-import org.openremote.controller.event.LevelEvent;+import org.openremote.controller.sensor.LevelSensorState;-public class LevelFacade extends SingleValueEventFacade<LevelFacade.LevelAdapter, LevelEvent> {+public class LevelFacade extends SingleValueSensorFacade<LevelFacade.LevelAdapter, LevelSensorState> {@Override- protected LevelEvent createDefaultEvent(int sourceID, String sourceName) {- return new LevelEvent(sourceID, sourceName, 0);+ protected LevelSensorState createDefaultState(int sourceID, String sourceName) {+ return new LevelSensorState(sourceID, sourceName, 0);}@Override- protected LevelAdapter createAdapter(LevelEvent event) {- return new LevelAdapter(event);+ protected LevelAdapter createAdapter(LevelSensorState sensorState) {+ return new LevelAdapter(sensorState);}public class LevelAdapter {- private LevelEvent levelEvent;+ private LevelSensorState levelSensorState;- private LevelAdapter(LevelEvent levelEvent) {- this.levelEvent = levelEvent;+ private LevelAdapter(LevelSensorState levelSensorState) {+ this.levelSensorState = levelSensorState;}public void value(int value) {@@ -30,9 +30,8 @@ public class LevelFacade extends SingleValueEventFacade<LevelFacade.LevelAdaptervalue = 100;}- LevelEvent newLevelEventEvent = levelEvent.clone(value);-- dispatchEvent(newLevelEventEvent);+ LevelSensorState newLevelSensorState = levelSensorState.clone(value);+ terminateAndReplaceWith(newLevelSensorState);}}}diff --git a/controller/src/main/java/org/openremote/controller/rules/RangeFacade.java b/controller/src/main/java/org/openremote/controller/rules/RangeFacade.javaindex 8ee468b4d..5d342d2a4 100644--- a/controller/src/main/java/org/openremote/controller/rules/RangeFacade.java+++ b/controller/src/main/java/org/openremote/controller/rules/RangeFacade.java@@ -1,43 +1,37 @@package org.openremote.controller.rules;-import org.openremote.controller.event.RangeEvent;+import org.openremote.controller.sensor.RangeSensorState;-import java.util.logging.Logger;--public class RangeFacade extends SingleValueEventFacade<RangeFacade.RangeAdapter, RangeEvent> {-- private static final Logger LOG = Logger.getLogger(RangeFacade.class.getName());+public class RangeFacade extends SingleValueSensorFacade<RangeFacade.RangeAdapter, RangeSensorState> {@Override- protected RangeEvent createDefaultEvent(int sourceID, String sourceName) {- // TODO We drop the min/max here? This leads to events that don't restrict boundaries...- return new RangeEvent(sourceID, sourceName, 0, Integer.MIN_VALUE, Integer.MAX_VALUE);+ protected RangeSensorState createDefaultState(int sourceID, String sourceName) {+ // TODO We drop the min/max here? This leads to updates that don't restrict boundaries...+ return new RangeSensorState(sourceID, sourceName, 0, Integer.MIN_VALUE, Integer.MAX_VALUE);}@Override- protected RangeAdapter createAdapter(RangeEvent event) {- return new RangeAdapter(event);+ protected RangeAdapter createAdapter(RangeSensorState sensorState) {+ return new RangeAdapter(sensorState);}public class RangeAdapter {- private RangeEvent rangeEvent;+ final private RangeSensorState rangeSensorState;- private RangeAdapter(RangeEvent event) {- this.rangeEvent = event;+ private RangeAdapter(RangeSensorState rangeSensorState) {+ this.rangeSensorState = rangeSensorState;}public void value(int value) {- if (value < rangeEvent.getMinValue()) {- value = rangeEvent.getMinValue();- } else if (value > rangeEvent.getMaxValue()) {- value = rangeEvent.getMaxValue();+ if (value < rangeSensorState.getMinValue()) {+ value = rangeSensorState.getMinValue();+ } else if (value > rangeSensorState.getMaxValue()) {+ value = rangeSensorState.getMaxValue();}- RangeEvent newRangeEventEvent = rangeEvent.clone(value);-- LOG.fine("Dispatching event (original value was: '" + value + "'): " + newRangeEventEvent);- dispatchEvent(newRangeEventEvent);+ RangeSensorState newRangeSensorState = rangeSensorState.clone(value);+ terminateAndReplaceWith(newRangeSensorState);}}}diff --git a/controller/src/main/java/org/openremote/controller/rules/RuleEngine.java b/controller/src/main/java/org/openremote/controller/rules/RuleEngine.javaindex 7fac38e9e..172568810 100644--- a/controller/src/main/java/org/openremote/controller/rules/RuleEngine.java+++ b/controller/src/main/java/org/openremote/controller/rules/RuleEngine.java@@ -40,25 +40,25 @@ 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.controller.event.Event;-import org.openremote.controller.event.EventProcessingContext;-import org.openremote.controller.event.EventProcessor;-import org.openremote.controller.model.Deployment;+import org.openremote.controller.deploy.Deployment;+import org.openremote.controller.sensor.SensorState;+import org.openremote.controller.sensor.SensorStateUpdate;import java.util.Collection;import java.util.HashMap;import java.util.Map;import java.util.logging.Level;import java.util.logging.Logger;-import java.util.stream.Stream;-public abstract class RuleEngine extends EventProcessor {+public class RuleEngine {private static final Logger LOG = Logger.getLogger(RuleEngine.class.getName());+ final protected Deployment deployment;+private KieBase kb;private KieSession knowledgeSession;- private Map<Integer, FactHandle> eventSources = new HashMap<>();+ private Map<Integer, FactHandle> stateSources = new HashMap<>();private long currentFactCount;private SwitchFacade switchFacade;@@ -67,85 +67,11 @@ public abstract class RuleEngine extends EventProcessor {private RulePersistence rulePersistence;private RuleUtil ruleUtil;- @Override- public String getName() {- return "Drools Rule Engine";+ public RuleEngine(Deployment deployment) {+ this.deployment = deployment;}- @Override- public void process(EventProcessingContext ctx) {- // if we got no rules, just push event back to next processor...- if (kb == null) {- LOG.fine("No knowledge base configured, skipping processing of event: " + ctx.getEvent());- return;- }-- Event event = ctx.getEvent();-- switchFacade.pushEventContext(ctx);- levelFacade.pushEventContext(ctx);- rangeFacade.pushEventContext(ctx);-- try {- long newFactCount;-- // If this Event fact is not in working memory (considering its equals() method)...- if (!knowledgeSession.getObjects().contains(event)) {-- // ... update or new insert?- boolean isUpdate = true;-- // If there already is an Event in wm with the same source ID ...- if (eventSources.keySet().contains(event.getSourceID())) {- try {- // ... retract it from working memory ...- knowledgeSession.delete(eventSources.get(event.getSourceID()));- } finally {- // ... and make we don't keep a reference to a fact- eventSources.remove(event.getSourceID());- }- } else {- isUpdate = false;- }-- // Put the Event into wm and remember the handle- FactHandle handle = knowledgeSession.insert(event);- eventSources.put(event.getSourceID(), handle);-- if (isUpdate) {- LOG.fine("Inserted: " + event);- } else {- LOG.fine("Updated: " + event);- }-- newFactCount = knowledgeSession.getFactCount();- LOG.fine("New fact count: " + newFactCount);- if (newFactCount != currentFactCount) {- LOG.fine("Fact count changed from " + currentFactCount + " to " + newFactCount + " on '" + event.getSource() + "'");- }- currentFactCount = newFactCount;- }-- LOG.fine("Firing all rules");- knowledgeSession.fireAllRules();-- // TODO: This doesn't look right, why would it matter if there are 1000 facts? Who says that- newFactCount = knowledgeSession.getFactCount();- if (newFactCount >= 1000) // look for runaway insertion of facts- if (newFactCount != currentFactCount) {- LOG.fine("Fact count changed from " + currentFactCount + " to " + newFactCount + " on '" + event.getSource() + "'");- }- currentFactCount = newFactCount;- } catch (Throwable t) {- LOG.log(Level.SEVERE, "Error in executing rule : evt.getSource() + \":\" + t.getMessage()\n\tEvent " + ctx.getEvent() + " not processed!", t);- if (t.getCause() != null) {- LOG.log(Level.SEVERE, "Root Cause: \n", t.getCause());- }- }- }-- @Override- public void start(Deployment deployment) throws Exception {+ public void start() {KieServices kieServices = KieServices.Factory.get();KieModuleModel kieModuleModel = kieServices.newKieModuleModel();@@ -159,7 +85,9 @@ public abstract class RuleEngine extends EventProcessor {KieFileSystem kfs = kieServices.newKieFileSystem();kfs.writeKModuleXML(kieModuleModel.toXML());- addResources(kieServices, kfs);+ deployment.getRulesProvider().getResources(kieServices).forEach(resource ->+ addResource(resource, kieServices, kfs)+ );KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());@@ -190,7 +118,7 @@ public abstract class RuleEngine extends EventProcessor {RuleExecutionLogger ruleExecutionLogger = new RuleExecutionLogger();knowledgeSession.addEventListener(ruleExecutionLogger);} catch (Throwable t) {- throw new Exception(t);+ throw new RuntimeException(t);}LOG.fine("Rule engine started");@@ -198,21 +126,91 @@ public abstract class RuleEngine extends EventProcessor {knowledgeSession.fireAllRules();}- @Overridepublic void stop() {LOG.fine("Stopping RuleEngine");if (knowledgeSession != null) {knowledgeSession.dispose();LOG.fine("Knowledge session disposed");}- eventSources.clear();+ stateSources.clear();// We're disposing of the knowledge base, don't keep references to any facts (ORCJAVA-407)- eventSources.clear();+ stateSources.clear();kb = null;}+ public void process(SensorStateUpdate sensorStateUpdate) {+ if (kb == null) {+ LOG.fine("No knowledge base configured, skipping processing of: " + sensorStateUpdate);+ return;+ }++ SensorState sensorState = sensorStateUpdate.getSensorState();++ switchFacade.process(sensorStateUpdate);+ levelFacade.process(sensorStateUpdate);+ rangeFacade.process(sensorStateUpdate);++ try {+ long newFactCount;++ // If this fact is not in working memory (considering its equals() method)...+ if (!knowledgeSession.getObjects().contains(sensorState)) {++ // ... update or new insert?+ boolean isUpdate = true;++ // If there already is a fact in wm with the same sensor ID ...+ if (stateSources.keySet().contains(sensorState.getSensorID())) {+ try {+ // ... retract it from working memory ...+ knowledgeSession.delete(stateSources.get(sensorState.getSensorID()));+ } finally {+ // ... and make we don't keep a reference to a fact+ stateSources.remove(sensorState.getSensorID());+ }+ } else {+ isUpdate = false;+ }++ // Put the fact into wm and remember the handle+ FactHandle handle = knowledgeSession.insert(sensorState);+ stateSources.put(sensorState.getSensorID(), handle);++ if (isUpdate) {+ LOG.fine("Inserted: " + sensorState);+ } else {+ LOG.fine("Updated: " + sensorState);+ }++ newFactCount = knowledgeSession.getFactCount();+ LOG.fine("New fact count: " + newFactCount);+ if (newFactCount != currentFactCount) {+ LOG.fine("Fact count changed from " + currentFactCount + " to " + newFactCount + " on '" + sensorState.getSensorName() + "'");+ }+ currentFactCount = newFactCount;+ }++ LOG.fine("Firing all rules");+ knowledgeSession.fireAllRules();++ // TODO: This doesn't look right, why would it matter if there are 1000 facts? Who says that+ newFactCount = knowledgeSession.getFactCount();+ if (newFactCount >= 1000) // look for runaway insertion of facts+ if (newFactCount != currentFactCount) {+ LOG.fine("Fact count changed from " + currentFactCount + " to " + newFactCount + " on '" + sensorState.getSensorName() + "'");+ }+ currentFactCount = newFactCount;++ } catch (Throwable t) {+ LOG.log(Level.SEVERE, "Error executing rules for: " + sensorStateUpdate.getSensorState(), t);+ if (t.getCause() != null) {+ LOG.log(Level.SEVERE, "Root Cause: \n", t.getCause());+ }+ }+ }+protected void setGlobal(String identifier, Object object) {try {knowledgeSession.setGlobal(identifier, object);@@ -221,55 +219,51 @@ public abstract class RuleEngine extends EventProcessor {}}- protected void addResources(KieServices kieServices, KieFileSystem kfs) {- getResources(kieServices).forEach(resource -> {- String sourcePath = resource.getSourcePath();- if (sourcePath == null) {- throw new IllegalArgumentException("Resource definition must have source path: " + resource);- }- LOG.fine("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);- }+ protected void 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();+ 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);+ 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());}- } 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 anykfs.delete("src/main/resources/" + sourcePath);+ } else {+ LOG.info("Added rule definition: " + resource);}- });+ } 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);+ }}- abstract protected Stream<Resource> getResources(KieServices kieServices);-@Overridepublic String toString() {return "RuleEngine{" +diff --git a/controller/src/main/java/org/openremote/controller/rules/RuleExecutionLogger.java b/controller/src/main/java/org/openremote/controller/rules/RuleExecutionLogger.javaindex 2443dcd9e..0fadb071c 100644--- a/controller/src/main/java/org/openremote/controller/rules/RuleExecutionLogger.java+++ b/controller/src/main/java/org/openremote/controller/rules/RuleExecutionLogger.java@@ -4,8 +4,8 @@ import org.kie.api.definition.rule.Rule;import org.kie.api.event.rule.BeforeMatchFiredEvent;import org.kie.api.event.rule.DefaultAgendaEventListener;import org.kie.api.runtime.rule.Match;-import org.openremote.controller.event.Event;-import org.openremote.controller.model.Sensor;+import org.openremote.controller.sensor.SensorState;+import org.openremote.controller.sensor.Sensor;import java.util.List;import java.util.Map;@@ -47,7 +47,7 @@ public class RuleExecutionLogger extends DefaultAgendaEventListener {for (String declarationID : declarationIDs) {Object declarationValue = matchEvent.getDeclarationValue(declarationID);String declarationValueString = this.declarationValueToString(declarationValue);- if (declarationValue instanceof Sensor || declarationValue instanceof Event) {+ if (declarationValue instanceof Sensor || declarationValue instanceof SensorState) {declarationLog = String.format("%s\t\tDeclaration: \"%s\"\n\t\tValue:\n\t\t\t%s\n", declarationLog, declarationID, declarationValueString);} else {declarationLog = String.format("%s\t\tDeclaration: \"%s: %s\"\n", declarationLog, declarationID, declarationValueString);@@ -94,11 +94,11 @@ public class RuleExecutionLogger extends DefaultAgendaEventListener {theValue = String.format("%sName: \t\"%s\"\n\t\t\tValue: \t\"%s\"", theValue, entryName, entryValue);}}- if (antecedent instanceof Event) {- Event theEvent = (Event) antecedent;- String sourceName = theEvent.getSource();- String eventValue = theEvent.getValue().toString(); //assumes all values can directly cast to String- theValue = String.format("Event Name: \t\"%s\"\n\t\t\tEvent Value: \t\"%s\"", sourceName, eventValue);+ if (antecedent instanceof SensorState) {+ SensorState theSensorState = (SensorState) antecedent;+ String sensorName = theSensorState.getSensorName();+ String stateValue = theSensorState.getValue().toString(); //assumes all values can directly cast to String+ theValue = String.format("Sensor name: \t\"%s\"\n\t\t\tState value: \t\"%s\"", sensorName, stateValue);}return theValue;@@ -121,9 +121,9 @@ public class RuleExecutionLogger extends DefaultAgendaEventListener {{convertedDeclarationValue = ((Sensor) declarationValue).getSensorDefinition().getName();}- if (declarationValue instanceof Event) {- String sensorName = ((Event) declarationValue).getSource();- String sensorValue = ((Event) declarationValue).getValue().toString();+ if (declarationValue instanceof SensorState) {+ String sensorName = ((SensorState) declarationValue).getSensorName();+ String sensorValue = ((SensorState) declarationValue).getValue().toString();convertedDeclarationValue = String.format("Sensor Name: \"%s\"\n\t\t\tSensor Value: \"%s\"", sensorName, sensorValue);}diff --git a/controller/src/main/java/org/openremote/controller/rules/RulesProvider.java b/controller/src/main/java/org/openremote/controller/rules/RulesProvider.javanew file mode 100644index 000000000..f3ca3c1d4--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/rules/RulesProvider.java@@ -0,0 +1,12 @@+package org.openremote.controller.rules;++import org.kie.api.KieServices;+import org.kie.api.io.Resource;++import java.util.stream.Stream;++public interface RulesProvider {++ Stream<Resource> getResources(KieServices kieServices);++}diff --git a/controller/src/main/java/org/openremote/controller/rules/SensorFacade.java b/controller/src/main/java/org/openremote/controller/rules/SensorFacade.javanew file mode 100644index 000000000..6ca305416--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/rules/SensorFacade.java@@ -0,0 +1,32 @@+package org.openremote.controller.rules;++import org.openremote.controller.sensor.SensorState;+import org.openremote.controller.sensor.SensorStateUpdate;++import java.util.logging.Logger;++/**+ * Provide access to all sensors from rules through {@link #name}.+ */+public abstract class SensorFacade<T> {++ private static final Logger LOG = Logger.getLogger(SensorFacade.class.getName());++ protected SensorStateUpdate sensorStateUpdate;++ public void process(SensorStateUpdate sensorStateUpdate) {+ this.sensorStateUpdate = sensorStateUpdate;+ }++ protected void terminateAndReplaceWith(final SensorState newSensorState) {+ sensorStateUpdate.terminate();+ LOG.fine("Terminated sensor state update, dispatching new update: " + newSensorState);+ Thread t = new Thread(+ () -> sensorStateUpdate.getControllerContext().update(newSensorState)+ );+ t.start();+ }++ protected abstract T name(String sensorName) throws Exception;+}+diff --git a/controller/src/main/java/org/openremote/controller/rules/SingleValueEventFacade.java b/controller/src/main/java/org/openremote/controller/rules/SingleValueEventFacade.javadeleted file mode 100644index ed38284d8..000000000--- a/controller/src/main/java/org/openremote/controller/rules/SingleValueEventFacade.java+++ /dev/null@@ -1,26 +0,0 @@-package org.openremote.controller.rules;--import org.openremote.controller.event.Event;-import org.openremote.controller.model.Sensor;--public abstract class SingleValueEventFacade<T, U extends Event> extends EventFacade {-- public T name(String sensorName) throws Exception {- Event evt = eventProcessingContext.getControllerContext().queryEvent(sensorName);-- if (evt instanceof Sensor.UnknownEvent) {- evt = createDefaultEvent(evt.getSourceID(), evt.getSource());- }-- try {- return createAdapter((U) evt);- } catch (ClassCastException e) {- throw new Exception("event class mismatch");- }- }-- protected abstract U createDefaultEvent(int sourceID, String sourceName);-- protected abstract T createAdapter(U event);-}-diff --git a/controller/src/main/java/org/openremote/controller/rules/SingleValueSensorFacade.java b/controller/src/main/java/org/openremote/controller/rules/SingleValueSensorFacade.javanew file mode 100644index 000000000..6f0b6b30b--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/rules/SingleValueSensorFacade.java@@ -0,0 +1,27 @@+package org.openremote.controller.rules;++import org.openremote.controller.sensor.SensorState;+import org.openremote.controller.sensor.Sensor;++public abstract class SingleValueSensorFacade<T, U extends SensorState> extends SensorFacade<T> {++ @Override+ public T name(String sensorName) throws Exception {+ SensorState sensorState = sensorStateUpdate.getControllerContext().queryState(sensorName);++ if (sensorState instanceof Sensor.UnknownState) {+ sensorState = createDefaultState(sensorState.getSensorID(), sensorState.getSensorName());+ }++ try {+ return createAdapter((U) sensorState);+ } catch (ClassCastException ex) {+ throw new Exception("Sensor type mismatch: " + sensorState, ex);+ }+ }++ protected abstract U createDefaultState(int sourceID, String sourceName);++ protected abstract T createAdapter(U sensorState);+}+diff --git a/controller/src/main/java/org/openremote/controller/rules/SwitchFacade.java b/controller/src/main/java/org/openremote/controller/rules/SwitchFacade.javaindex 839fca922..cabe7c81e 100644--- a/controller/src/main/java/org/openremote/controller/rules/SwitchFacade.java+++ b/controller/src/main/java/org/openremote/controller/rules/SwitchFacade.java@@ -1,25 +1,26 @@package org.openremote.controller.rules;-import org.openremote.controller.event.Event;-import org.openremote.controller.model.Sensor;-import org.openremote.controller.event.SwitchEvent;+import org.openremote.controller.sensor.SensorState;+import org.openremote.controller.sensor.Sensor;+import org.openremote.controller.sensor.SwitchSensorState;-public class SwitchFacade extends EventFacade {+public class SwitchFacade extends SensorFacade<SwitchFacade.SwitchAdapter> {+ @Overridepublic SwitchAdapter name(String sensorName) throws Exception {- Event evt = eventProcessingContext.getControllerContext().queryEvent(sensorName);-- if (evt instanceof Sensor.UnknownEvent) {- evt = new SwitchEvent(- evt.getSourceID(),- evt.getSource(),- SwitchEvent.State.OFF.serialize(),- SwitchEvent.State.OFF+ SensorState evt = sensorStateUpdate.getControllerContext().queryState(sensorName);++ if (evt instanceof Sensor.UnknownState) {+ evt = new SwitchSensorState(+ evt.getSensorID(),+ evt.getSensorName(),+ SwitchSensorState.State.OFF.serialize(),+ SwitchSensorState.State.OFF);}- if (evt instanceof SwitchEvent) {- return new SwitchAdapter((SwitchEvent) evt);+ if (evt instanceof SwitchSensorState) {+ return new SwitchAdapter((SwitchSensorState) evt);} else {throw new Exception("Sensor is not switch type: " + sensorName);}@@ -27,34 +28,34 @@ public class SwitchFacade extends EventFacade {public class SwitchAdapter {- private SwitchEvent switchEvent;+ private SwitchSensorState switchSensorState;- private SwitchAdapter(SwitchEvent switchEvent) {- this.switchEvent = switchEvent;+ private SwitchAdapter(SwitchSensorState switchSensorState) {+ this.switchSensorState = switchSensorState;}public void off() {off(null);}- public void off(String eventValue) {- if (eventValue == null) {- eventValue = SwitchEvent.State.OFF.serialize();+ public void off(String value) {+ if (value == null) {+ value = SwitchSensorState.State.OFF.serialize();}- SwitchEvent newSwitchEvent = switchEvent.clone(eventValue, SwitchEvent.State.OFF);- dispatchEvent(newSwitchEvent);+ SwitchSensorState newSwitchSensorState = switchSensorState.clone(value, SwitchSensorState.State.OFF);+ terminateAndReplaceWith(newSwitchSensorState);}public void on() {on(null);}- public void on(String eventValue) {- if (eventValue == null) {- eventValue = SwitchEvent.State.ON.serialize();+ public void on(String value) {+ if (value == null) {+ value = SwitchSensorState.State.ON.serialize();}- SwitchEvent newSwitchEvent = switchEvent.clone(eventValue, SwitchEvent.State.ON);- dispatchEvent(newSwitchEvent);+ SwitchSensorState newSwitchSensorState = switchSensorState.clone(value, SwitchSensorState.State.ON);+ terminateAndReplaceWith(newSwitchSensorState);}}}diff --git a/controller/src/main/java/org/openremote/controller/sensor/CustomSensor.java b/controller/src/main/java/org/openremote/controller/sensor/CustomSensor.javanew file mode 100644index 000000000..69cbc73cb--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/sensor/CustomSensor.java@@ -0,0 +1,196 @@+package org.openremote.controller.sensor;++import org.openremote.controller.command.SensorUpdateCommand;+import org.openremote.controller.command.PullCommand;+import org.openremote.controller.command.PushCommand;+import org.openremote.controller.deploy.SensorDefinition;++import java.util.HashMap;+import java.util.Map;+import java.util.Set;+import java.util.logging.Logger;++/**+ * A custom sensor operates on a finite set of explicit state values that it returns, see {@link DistinctStates}.+ * TODO: Write more docs+ */+public class CustomSensor extends Sensor {++ private static final Logger LOG = Logger.getLogger(CustomSensor.class.getName());++ final protected DistinctStates states;+ final protected boolean strictStateMapping;++ /**+ * This constructor allows subclasses to determine whether the distinct states are passed+ * as sensor properties through the {@link PullCommand} and {@link PushCommand} interface.+ * When the sensor's type (such as {@link SwitchSensor}) makes the available states explicit,+ * it may not be necessary to pass the additional property information to+ * {@link SensorUpdateCommand} implementations.+ *+ * @param updateCommand the command implementation that backs this sensor and can produce the current state+ * @param states distinct state values and their mappings this sensor will return+ * @param strictStateMapping Indicates whether this sensor instance should enforce strict state mapping rules -- when+ * enabled, only state values explicitly declared for this sensor will be accepted and returned.+ * If set to false, all values are allowed but those with value mappings will be converted.+ */+ public CustomSensor(SensorDefinition sensorDefinition, SensorUpdateCommand updateCommand, DistinctStates states, boolean strictStateMapping) {+ super(sensorDefinition, updateCommand);+ if (states == null) {+ this.states = new DistinctStates();+ } else {+ this.states = states;+ }+ this.strictStateMapping = strictStateMapping;+ }++ /**+ * Constructs the state from the raw command output string. This implementation checks the+ * incoming value for possible state mappings and returns the mapped state value where necessary.+ * Arbitrary, non-declared states are rejected unless {@link #strictStateMapping} has been set+ * to false. When set to true, an instance of {@link UnknownState} is returned for any+ * non-declared state.+ */+ @Override+ public SensorState process(String value) {+ if (!states.hasState(value)) {+ if (isUnknownSensorValue(value)) {+ return new UnknownState(this);+ }++ if (strictStateMapping) {+ LOG.warning("Update command's value is not consistent with '" + getSensorDefinition() + "': " + value);+ return new UnknownState(this);+ } else {+ return createSensorState(value);+ }+ }++ if (!states.hasMapping(value)) {+ return createSensorState(value);+ } else {+ return createSensorState(states.getMapping(value), value);+ }+ }++ /**+ * Constructs state for this sensor with a given state value. Subclasses can override this+ * implementation to provide their own specific state types.+ *+ * @param value state value+ * @return new state instance associated with this sensor+ */+ protected SensorState createSensorState(String value) {+ return new CustomSensorState(getSensorDefinition().getSensorID(), getSensorDefinition().getName(), value);+ }++ /**+ * Constructs state for this sensor with a given state value, and the originating value+ * when state mapping (translation) was used. Subclasses can override this implementation to+ * provide their own specific state types.+ *+ * @param value the translated (mapped) state value+ * @param originalValue the original state value returned by the associated update command+ * @return new state instance associated with this sensor+ */+ protected SensorState createSensorState(String value, String originalValue) {+ return new CustomSensorState(getSensorDefinition().getSensorID(), getSensorDefinition().getName(), value, originalValue);+ }++ /**+ * Holds the distinct state values for a custom sensor and possible value mappings if configured.+ * <p>+ * Each state is available to {@link SensorUpdateCommand} implementers through the sensor+ * properties passed via the {@link PullCommand} and {@link PushCommand} APIs. The expected+ * state values can be found using a key 'state-1' for the first available state string to+ * 'state-n' to the last expected state value.+ * TODO This is no longer true, why would the implementers need that info anyway? It's the job of this class to shield them from state mappings!+ */+ public static class DistinctStates {++ private Map<String, String> states = new HashMap<>();++ /**+ * Store an explicit state value without mapping.+ */+ public void addState(String state) {+ states.put(state, null);+ }++ /**+ * Stores an explicit state value with mapping. When the update command returns the state+ * value, it is automatically mapped to a new value to be consumed by UI widgets and other+ * users of the sensor.+ *+ * @param state the state string returned by update command implementations+ * @param mapping the value the state string is translated to by the sensor+ */+ public void addStateMapping(String state, String mapping) {+ states.put(state, mapping);+ }++ /**+ * Indicates if the given state string is contained within this state collection+ *+ * @param value the requested state string+ * @return true if the state string has been added, false otherwise+ */+ public boolean hasState(String value) {+ return states.containsKey(value);+ }++ /**+ * Returns sensor's state mappings as a string. Implementation delegates to+ * {@link Map#toString()}.+ *+ * @return all state mappings as a string+ */+ @Override+ public String toString() {+ return states.toString();+ }++ /**+ * Indicates if the given state string has a mapping in this state collection+ *+ * @param state the state string which mapping is requested+ * @return true if the state string is mapped to another value in this state+ * collection, false otherwise+ */+ public boolean hasMapping(String state) {+ if (!hasState(state)) {+ return false;+ }+ String mapping = states.get(state);+ return mapping != null;+ }++ /**+ * Returns the mapped value of a state string.+ *+ * @param state the state string which mapping is requested+ * @return returns the translated value of a given state string or {@link #UNKNOWN_STATE_VALUE}+ */+ public String getMapping(String state) {+ String mapping = states.get(state);+ if (mapping == null) {+ return UNKNOWN_STATE_VALUE;+ }+ return mapping;+ }++ public Set<String> getAllStates() {+ return states.keySet();+ }+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "sensorDefinition=" + getSensorDefinition() ++ ", hasStrictStateMapping=" + strictStateMapping ++ ", states=" + states ++ '}';+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/sensor/CustomSensorState.java b/controller/src/main/java/org/openremote/controller/sensor/CustomSensorState.javanew file mode 100644index 000000000..ad370282c--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/sensor/CustomSensorState.java@@ -0,0 +1,58 @@+package org.openremote.controller.sensor;++/**+ * Holds the original raw value and the result of processing {@link CustomSensor.DistinctStates}.+ */+public class CustomSensorState extends SensorState<String> {++ private String value;+ private String originalValue;++ public CustomSensorState(int sourceSensorID, String sourceSensorName, String value) {+ super(sourceSensorID, sourceSensorName);+ this.value = value;+ this.originalValue = this.value;+ }++ public CustomSensorState(int sourceSensorID, String sourceSensorName, String value, String originalValue) {+ this(sourceSensorID, sourceSensorName, value);+ this.originalValue = originalValue;+ }++ public String getOriginalValue() {+ return originalValue;+ }++ @Override+ public String getValue() {+ return value;+ }++ @Override+ public void setValue(String value) {+ this.value = value;+ }++ @Override+ public String serialize() {+ return value;+ }++ @Override+ public CustomSensorState clone(String newValue) {+ // TODO What is this?+ throw new Error("NYI");+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "sensorID=" + getSensorID() ++ ", sensorName='" + getSensorName() + "'" ++ ", timestamp=" + getTimestamp() ++ ", value='" + getValue() + '\'' ++ ", originalState='" + getOriginalValue() + '\'' ++ '}';+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/model/LevelSensor.java b/controller/src/main/java/org/openremote/controller/sensor/LevelSensor.javasimilarity index 65%rename from controller/src/main/java/org/openremote/controller/model/LevelSensor.javarename to controller/src/main/java/org/openremote/controller/sensor/LevelSensor.javaindex 57bbc374a..4dd712daa 100644--- a/controller/src/main/java/org/openremote/controller/model/LevelSensor.java+++ b/controller/src/main/java/org/openremote/controller/sensor/LevelSensor.java@@ -1,9 +1,7 @@-package org.openremote.controller.model;+package org.openremote.controller.sensor;-import org.openremote.controller.command.EventProducerCommand;+import org.openremote.controller.command.SensorUpdateCommand;import org.openremote.controller.deploy.SensorDefinition;-import org.openremote.controller.event.Event;-import org.openremote.controller.event.LevelEvent;import java.util.logging.Logger;@@ -11,14 +9,14 @@ public class LevelSensor extends RangeSensor {private static final Logger LOG = Logger.getLogger(LevelSensor.class.getName());- public LevelSensor(SensorDefinition sensorDefinition, EventProducerCommand eventProducerCommand) {- super(sensorDefinition, eventProducerCommand, 0, 100);+ public LevelSensor(SensorDefinition sensorDefinition, SensorUpdateCommand sensorUpdateCommand) {+ super(sensorDefinition, sensorUpdateCommand, 0, 100);}@Override- public Event processEvent(String value) {+ public SensorState process(String value) {try {- return new LevelEvent(+ return new LevelSensorState(getSensorDefinition().getSensorID(),getSensorDefinition().getName(),new Integer(value.trim())@@ -27,7 +25,7 @@ public class LevelSensor extends RangeSensor {if (!isUnknownSensorValue(value)) {LOG.warning("Level sensor '" + getSensorDefinition() + "' produced a non-integer value: " + value);}- return new UnknownEvent(this);+ return new UnknownState(this);}}diff --git a/controller/src/main/java/org/openremote/controller/sensor/LevelSensorState.java b/controller/src/main/java/org/openremote/controller/sensor/LevelSensorState.javanew file mode 100644index 000000000..22c757479--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/sensor/LevelSensorState.java@@ -0,0 +1,57 @@+package org.openremote.controller.sensor;++import java.util.logging.Logger;++/**+ * Level sensor state is an integer value in the range of [0..100].+ */+public class LevelSensorState extends RangeSensorState {++ private static final Logger LOG = Logger.getLogger(LevelSensorState.class.getName());++ public LevelSensorState(int sourceSensorID, String sourceSensorName, int value) {+ super(sourceSensorID, sourceSensorName, validate(sourceSensorID, sourceSensorName, value), 0, 100);+ }++ public LevelSensorState clone(int newValue) {+ return new LevelSensorState(getSensorID(), getSensorName(), newValue);+ }++ /**+ * Validate range value to [0..100].+ *+ * @param sensorID originating sensor ID+ * @param sensorName originating sensor name+ * @return sensor value unless it is exceeding LEVEL limits in which case it has been limited+ * to range [0..100]+ */+ static protected int validate(int sensorID, String sensorName, int value) {+ if (value > 100) {+ value = 100;+ LOG.log(java.util.logging.Level.WARNING,+ "A level sensor update was created with an invalid value : {0} (source = {1} - {2}). " ++ "The value should be limited to maximum value of 100.", new Object[]{value, sensorID, sensorName}+ );+ }++ if (value < 0) {+ value = 0;+ LOG.log(java.util.logging.Level.WARNING,+ "A level sensor udpatewas created with an invalid value : {0} (source = {1} - {2}). " ++ "The value should be limited to minimum value of 0.", new Object[]{value, sensorID, sensorName}+ );+ }+ return value;+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "sensorID=" + getSensorID() ++ ", sensorName='" + getSensorName() + "'" ++ ", timestamp=" + getTimestamp() ++ ", value='" + getValue() + "'" ++ "}";+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/model/RangeSensor.java b/controller/src/main/java/org/openremote/controller/sensor/RangeSensor.javasimilarity index 73%rename from controller/src/main/java/org/openremote/controller/model/RangeSensor.javarename to controller/src/main/java/org/openremote/controller/sensor/RangeSensor.javaindex ff9ab88f1..c3ec73e84 100644--- a/controller/src/main/java/org/openremote/controller/model/RangeSensor.java+++ b/controller/src/main/java/org/openremote/controller/sensor/RangeSensor.java@@ -1,9 +1,7 @@-package org.openremote.controller.model;+package org.openremote.controller.sensor;-import org.openremote.controller.command.EventProducerCommand;+import org.openremote.controller.command.SensorUpdateCommand;import org.openremote.controller.deploy.SensorDefinition;-import org.openremote.controller.event.Event;-import org.openremote.controller.event.RangeEvent;import java.util.logging.Logger;@@ -14,8 +12,8 @@ public class RangeSensor extends Sensor {private int minValue;private int maxValue;- public RangeSensor(SensorDefinition sensorDefinition, EventProducerCommand eventProducerCommand, int minValue, int maxValue) {- super(sensorDefinition, eventProducerCommand);+ public RangeSensor(SensorDefinition sensorDefinition, SensorUpdateCommand sensorUpdateCommand, int minValue, int maxValue) {+ super(sensorDefinition, sensorUpdateCommand);if (minValue > maxValue)throw new IllegalArgumentException("Sensor value min '" + minValue + "' is larger than max '" + maxValue + "'");this.minValue = minValue;@@ -31,9 +29,9 @@ public class RangeSensor extends Sensor {}@Override- protected Event processEvent(String value) {+ protected SensorState process(String value) {try {- return new RangeEvent(+ return new RangeSensorState(getSensorDefinition().getSensorID(),getSensorDefinition().getName(),new Integer(value.trim()),@@ -44,7 +42,7 @@ public class RangeSensor extends Sensor {if (!isUnknownSensorValue(value)) {LOG.warning("Range sensor '" + getSensorDefinition() + "' produced a non-integer value: " + value);}- return new UnknownEvent(this);+ return new UnknownState(this);}}diff --git a/controller/src/main/java/org/openremote/controller/event/RangeEvent.java b/controller/src/main/java/org/openremote/controller/sensor/RangeSensorState.javasimilarity index 56%rename from controller/src/main/java/org/openremote/controller/event/RangeEvent.javarename to controller/src/main/java/org/openremote/controller/sensor/RangeSensorState.javaindex 5a85da179..5a5560216 100644--- a/controller/src/main/java/org/openremote/controller/event/RangeEvent.java+++ b/controller/src/main/java/org/openremote/controller/sensor/RangeSensorState.java@@ -1,12 +1,12 @@-package org.openremote.controller.event;+package org.openremote.controller.sensor;-public class RangeEvent extends Event<Integer> {+public class RangeSensorState extends SensorState<Integer> {private Integer rangeValue;private Integer min;private Integer max;- public RangeEvent(int sourceID, String sourceName, Integer value, Integer min, Integer max) {+ public RangeSensorState(int sourceID, String sourceName, Integer value, Integer min, Integer max) {super(sourceID, sourceName);this.min = min;this.max = max;@@ -28,7 +28,7 @@ public class RangeEvent extends Event<Integer> {@Overridepublic void setValue(Integer value) {- // TODO: The LevelEvent logs when boundaries are breached, why don't we log here?+ // TODO: The LevelSensorState logs when boundaries are breached, why don't we log here?if (value > max) {this.rangeValue = max;} else if (value < min) {@@ -39,14 +39,14 @@ public class RangeEvent extends Event<Integer> {}@Override- public RangeEvent clone(Integer newValue) {+ public RangeSensorState clone(Integer newValue) {if (newValue < getMinValue()) {newValue = getMinValue();} else if (newValue > getMaxValue()) {newValue = getMaxValue();}- return new RangeEvent(this.getSourceID(), this.getSource(), newValue, getMinValue(), getMaxValue());+ return new RangeSensorState(this.getSensorID(), this.getSensorName(), newValue, getMinValue(), getMaxValue());}@Override@@ -56,12 +56,13 @@ public class RangeEvent extends Event<Integer> {@Overridepublic String toString() {- return "RangeEvent{" +- "sourceId=" + getSourceID() +- ", source='" + getSource() + "'" +- ", rangeValue=" + rangeValue +- ", min=" + min +- ", max=" + max ++ return getClass().getSimpleName() + "{" ++ "sensorID=" + getSensorID() ++ ", sensorName='" + getSensorName() + "'" ++ ", timestamp=" + getTimestamp() ++ ", value=" + getValue() ++ ", min=" + getMinValue() ++ ", max=" + getMaxValue() +'}';}}diff --git a/controller/src/main/java/org/openremote/controller/model/Sensor.java b/controller/src/main/java/org/openremote/controller/sensor/Sensor.javasimilarity index 65%rename from controller/src/main/java/org/openremote/controller/model/Sensor.javarename to controller/src/main/java/org/openremote/controller/sensor/Sensor.javaindex c702f50ef..669b44aae 100644--- a/controller/src/main/java/org/openremote/controller/model/Sensor.java+++ b/controller/src/main/java/org/openremote/controller/sensor/Sensor.java@@ -1,11 +1,10 @@-package org.openremote.controller.model;+package org.openremote.controller.sensor;-import org.openremote.controller.command.EventProducerCommand;+import org.openremote.controller.command.SensorUpdateCommand;import org.openremote.controller.command.PullCommand;import org.openremote.controller.command.PushCommand;import org.openremote.controller.context.ControllerContext;import org.openremote.controller.deploy.SensorDefinition;-import org.openremote.controller.event.Event;import java.security.AccessController;import java.security.PrivilegedAction;@@ -13,55 +12,49 @@ import java.util.logging.Level;import java.util.logging.Logger;/**- * Sensors abstract incoming events from devices, either through pulling/polling or- * listening to devices that actively push their state changes. Sensors operate on- * commands to execute pull or push operations with devices.+ * Sensors create {@link SensorState}s, which represent the data obtained from devices.* <p>- * Each pulling sensor (for passive devices) has a thread associated with it. Sensors- * bound to push commands do not create threads of their own but the command- * implementations themselves are usually multi-threaded.+ * A sensor is registered with a {@link ControllerContext}. State updates are obtained+ * either through pulling/polling or listening to devices that actively push their state+ * changes.* <p>- * Each sensor can have list of properties which it makes available to implementations of- * push or pull commands. These properties may be used by protocol implementers to- * direct their event producer output values to suit the sensor's configuration.+ * A sensor linked with a {@link PullCommand} runs a new thread when started, and executes+ * a periodic read.* <p>- * Sensors are registered with {@link ControllerContext}.- * Sensors create {@link org.openremote.controller.event.Event}s, which represent the- * data from devices.+ * A sensor linked with a {@link PushCommand} does not create threads, but delegates+ * threading and calling back with values to the command implementation.+ * <p>+ * Each sensor can have list of meta-data properties, used by command implementors.*/public abstract class Sensor {private static final Logger LOG = Logger.getLogger(Sensor.class.getName());- public static final String UNKNOWN_STATUS = "N/A";+ public static final String UNKNOWN_STATE_VALUE = "N/A";/*** Helper method to allow subclasses to check if a given value matches the 'N/A' string that* is used for uninitialized or error states in sensor implementations.- *- * @param value value to compare to- * @return true if value matches the string representation of- * {@link org.openremote.controller.model.Sensor.UnknownEvent}, false otherwise*/public static boolean isUnknownSensorValue(String value) {- return value.equals(UNKNOWN_STATUS);+ return value.equals(UNKNOWN_STATE_VALUE);}- private SensorDefinition sensorDefinition;- private ControllerContext controllerContext;- private EventProducerCommand eventProducerCommand;+ protected SensorDefinition sensorDefinition;+ protected ControllerContext controllerContext;+ protected SensorUpdateCommand sensorUpdateCommand;/*** This is a polling thread implementation for sensors that use {@link PullCommand}.*/- private SensorReader sensorReader;+ protected SensorReader sensorReader;- protected Sensor(SensorDefinition sensorDefinition, EventProducerCommand eventProducerCommand) {- if (eventProducerCommand == null) {- throw new IllegalArgumentException("Event producer command required: " + sensorDefinition);+ protected Sensor(SensorDefinition sensorDefinition, SensorUpdateCommand sensorUpdateCommand) {+ if (sensorUpdateCommand == null) {+ throw new IllegalArgumentException("Sensor update command required: " + sensorDefinition);}this.sensorDefinition = sensorDefinition;- this.eventProducerCommand = eventProducerCommand;+ this.sensorUpdateCommand = sensorUpdateCommand;}public SensorDefinition getSensorDefinition() {@@ -69,26 +62,16 @@ public abstract class Sensor {}/**- * Call path for push commands. Allow direct update of the sensor's value in- * the {@link ControllerContext}.- *- * Before updating the context, the value is first validated by concrete sensor- * implementation's {@link Sensor#processEvent(String)} method.- *- * @param state the new value for this sensor+ * Callback for {@link PushCommand} implementations. Before updating the controller context, the+ * given value is first validated and/or transformed by concrete sensor implementation's+ * {@link Sensor#process} method.*/public void update(String state) {if (controllerContext == null) {LOG.fine("Ignoring update, sensor is not running: " + getSensorDefinition());return;}-- /*- * Allow for sensor type specific processing of the value. This can be used for- * mappings, validating value ranges, etc. before the value is pushed through- * the event processor chain and ultimately into context.- */- Event evt = processEvent(state);+ SensorState evt = process(state);LOG.fine("Update on ID " + getSensorDefinition().getSensorID() + ", processed '" + state + "', created: " + evt);controllerContext.update(evt);}@@ -97,30 +80,30 @@ public abstract class Sensor {* Indicates if this sensor is bound to a command that actively pushes new data.*/public boolean isPushCommand() {- return eventProducerCommand instanceof PushCommand;+ return sensorUpdateCommand instanceof PushCommand;}/**- * Starts this sensor. When this sensor is bound to push command, will invoke its+ * Starts this sensor. When this sensor is bound to a push command, this invokes the* {@link PushCommand#start(Sensor)} method. For {@link PullCommand} implementations,- * this will start a polling thread to invoke their {@link PullCommand#read(Sensor)} method.+ * this will start a polling thread to invoke the {@link PullCommand#read(Sensor)} method.*/public void start(ControllerContext controllerContext) {LOG.info("Starting sensor: " + this);this.controllerContext = controllerContext;if (isPushCommand()) {- PushCommand pushCommand = (PushCommand) eventProducerCommand;+ PushCommand pushCommand = (PushCommand) sensorUpdateCommand;try {pushCommand.start(this);} catch (Throwable t) {LOG.log(Level.SEVERE, "There was an implementation error in the push command associated with " +" sensor '" + this + "'. The command implementation may not have started correctly.", t);}- } else if (eventProducerCommand instanceof PullCommand) {- sensorReader = new SensorReader((PullCommand) eventProducerCommand);+ } else if (sensorUpdateCommand instanceof PullCommand) {+ sensorReader = new SensorReader((PullCommand) sensorUpdateCommand);sensorReader.start();} else {- LOG.info("No action implemented for command type: " + eventProducerCommand);+ LOG.info("No action implemented for command type: " + sensorUpdateCommand);}}@@ -133,7 +116,7 @@ public abstract class Sensor {LOG.info("Stopping sensor: " + this);controllerContext = null;if (isPushCommand()) {- PushCommand pushCommand = (PushCommand) eventProducerCommand;+ PushCommand pushCommand = (PushCommand) sensorUpdateCommand;try {pushCommand.stop(this);} catch (Throwable t) {@@ -150,18 +133,15 @@ public abstract class Sensor {}/**- * Callback to subclasses to apply their event validations and other processing+ * Callback to subclasses to apply their state validations and other processing* if necessary. This method is called both when a value is pulled and when a* command pushes a new sensor value into {@link ControllerContext} state.- *- * @param value value returned by the event producer- * @return validated and processed value of the event producer*/- protected abstract Event processEvent(String value);+ protected abstract SensorState process(String value);/*** Handles the {@link PullCommand#read(Sensor)} polling.- *+ * <p>* TODO This is a major problem, every PullCommand uses a separate thread, we have hundreds of threads!*/private class SensorReader implements Runnable {@@ -241,37 +221,37 @@ public abstract class Sensor {* this may yield an active request using the connecting transport to device unless the* command implementation caches certain values and returns them from memory.* <p>- * In case of errors, {@link #UNKNOWN_STATUS} is returned.+ * In case of errors, {@link #UNKNOWN_STATE_VALUE} is returned.* <p>* This default read() implementation does not validate the input from protocol pull commands* in any way (other than handling implementation errors that yield runtime exceptions).- * concrete subclasses should override and implement {@link Sensor#processEvent(String)}+ * concrete subclasses should override and implement {@link Sensor#process(String)}* to validate the inputs from commands and to ensure the sensor returns values that* adhere to its datatype.** @return sensor's value, according to its datatype and provided by commands or- * {@link #UNKNOWN_STATUS} if value cannot be found.+ * {@link #UNKNOWN_STATE_VALUE} if value cannot be found.*/private String read() {try {return pullCommand.read(Sensor.this);} catch (Throwable t) {- LOG.log(Level.SEVERE, "Implementation error in pull command: " + eventProducerCommand, t);- return UNKNOWN_STATUS;+ LOG.log(Level.SEVERE, "Implementation error in pull command: " + sensorUpdateCommand, t);+ return UNKNOWN_STATE_VALUE;}}}/**- * A definition of an event that can be used when either an error occurs in sensor implementation- * (or in the underlying protocol implementation) or if the initial device state has not been- * fetched yet.+ * A definition of a sensor state that can be used when either an error occurs in sensor+ * implementation (or in the underlying protocol implementation) or if the initial device+ * state has not been fetched yet.* <p>- * The value returned by this event is defined in {@link #UNKNOWN_STATUS}.+ * The value returned by this state is defined in {@link #UNKNOWN_STATE_VALUE}.*/- public static class UnknownEvent extends Event<String> {+ public static class UnknownState extends SensorState<String> {- public UnknownEvent(Sensor sensor) {+ public UnknownState(Sensor sensor) {super(sensor.getSensorDefinition().getSensorID(), sensor.getSensorDefinition().getName());}@@ -286,20 +266,20 @@ public abstract class Sensor {}@Override- public UnknownEvent clone(String ignored) {+ public UnknownState clone(String ignored) {return this;}@Overridepublic String serialize() {- return UNKNOWN_STATUS;+ return UNKNOWN_STATE_VALUE;}@Overridepublic String toString() {- return "UnknownEvent{" +- "sourceId=" + getSourceID() +- ", source='" + getSource() + "'" ++ return getClass().getSimpleName() + "{" ++ "sourceId=" + getSensorID() ++ ", source='" + getSensorName() + "'" +"}";}}diff --git a/controller/src/main/java/org/openremote/controller/sensor/SensorState.java b/controller/src/main/java/org/openremote/controller/sensor/SensorState.javanew file mode 100644index 000000000..df0bc75e4--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/sensor/SensorState.java@@ -0,0 +1,68 @@+package org.openremote.controller.sensor;++/**+ * A state snapshot of a sensor, at a particular moment in time.+ *+ * @param <T> The type of value of this state snapshot.+ */+public abstract class SensorState<T> {++ final protected long timestamp = System.currentTimeMillis();+ final public int sensorID;+ final public String sensorName;++ public SensorState(int sensorID, String sensorName) {+ this.sensorID = sensorID;+ this.sensorName = sensorName;+ }++ public long getTimestamp() {+ return timestamp;+ }++ public Integer getSensorID() {+ return sensorID;+ }++ public String getSensorName() {+ return sensorName;+ }++ public abstract SensorState clone(T newValue);++ public abstract T getValue();++ public abstract void setValue(T value);++ /**+ * This method implementation should return an appropriate string representation of the state value.+ * This string will be returned by {@link org.openremote.controller.context.ControllerContext#queryValue}.+ */+ public abstract String serialize();++ /**+ * Two sensor states are equal if they have the same sensor ID, sensor name, and value.+ */+ @Override+ public boolean equals(Object o) {+ if (o == null) {+ return false;+ }++ if (o.getClass() != this.getClass()) {+ return false;+ }++ SensorState that = (SensorState) o;++ return that.getSensorID().equals(this.getSensorID()) &&+ that.getSensorName().equals(this.getSensorName()) &&+ that.getValue().equals(this.getValue());+ }++ @Override+ public int hashCode() {+ return getSensorID() + getSensorName().hashCode() + getValue().hashCode();+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/sensor/SensorStateUpdate.java b/controller/src/main/java/org/openremote/controller/sensor/SensorStateUpdate.javanew file mode 100644index 000000000..0281ec7fe--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/sensor/SensorStateUpdate.java@@ -0,0 +1,53 @@+package org.openremote.controller.sensor;++import org.openremote.controller.context.ControllerContext;++import java.util.logging.Logger;++/**+ * Before the {@link ControllerContext} accepts a sensor state update, it+ * executes all rules with a fresh instance of {@link SensorStateUpdate}.+ * <p>+ * Rules can terminate the update of the context, effectively cancelling the+ * original sensor state update. This is the regular behavior when your rules+ * write a sensor value through any {@link org.openremote.controller.rules.SensorFacade}.+ */+public class SensorStateUpdate {++ private static final Logger LOG = Logger.getLogger(SensorStateUpdate.class.getName());++ private ControllerContext controllerContext;+ private SensorState sensorState;+ private boolean terminated = false;++ public SensorStateUpdate(ControllerContext controllerContext, SensorState evt) {+ this.controllerContext = controllerContext;+ this.sensorState = evt;+ }++ public void terminate() {+ LOG.fine("Terminating state update");+ terminated = true;+ }++ public boolean hasTerminated() {+ return terminated;+ }++ public ControllerContext getControllerContext() {+ return controllerContext;+ }++ public SensorState getSensorState() {+ return sensorState;+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "sensorState=" + sensorState ++ ", terminated=" + terminated ++ '}';+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/sensor/SwitchSensor.java b/controller/src/main/java/org/openremote/controller/sensor/SwitchSensor.javanew file mode 100644index 000000000..54c98b4a6--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/sensor/SwitchSensor.java@@ -0,0 +1,76 @@+package org.openremote.controller.sensor;++import org.bouncycastle.util.Strings;+import org.openremote.controller.command.SensorUpdateCommand;+import org.openremote.controller.deploy.SensorDefinition;++import java.util.logging.Logger;++/**+ * A boolean switch sensor type. This is a specific case of a state sensor with two 'on' or 'off'+ * state strings. A switch sensor can be configured to map the default return values to other+ * values ("open/close", "running/stoppped", etc.) or to translate return values to local+ * languages.+ */+public class SwitchSensor extends CustomSensor {++ private static final Logger LOG = Logger.getLogger(SwitchSensor.class.getName());++ /**+ * Constructs a new switch sensor with given on/off state mapping. The distinct states should+ * contain mapping <b>only</b> for 'on' and 'off' value in case of a switch.+ * <p>+ * The sensor implementation will return 'on or 'off' string values.+ *+ * @param producer the udpate command implementation that backs this sensor+ * @param states state string mappings for the default 'on' and 'off' values+ */+ public SwitchSensor(SensorDefinition sensorDefinition, SensorUpdateCommand producer, DistinctStates states) {+ super(sensorDefinition, producer, states, true);+ }++ /**+ * Constructs state with a given value, which must be either 'on' or 'off'.+ * Any other value will cause {@link UnknownState} instance to be returned instead.+ */+ @Override+ protected SensorState createSensorState(String value) {+ return createSensorState(value, value);+ }++ /**+ * Constructs state with a given mapped (translated) value and the original+ * value which was used for the translation.+ * <p>+ * The original value must be either 'on' or 'off' (case insensitive), otherwise a+ * {@link UnknownState} is returned instead. The translated value can be any+ * arbitrary string value.+ */+ @Override+ protected SensorState createSensorState(String value, String originalValue) {+ try {+ return new SwitchSensorState(+ getSensorDefinition().getSensorID(),+ getSensorDefinition().getName(),+ value,+ SwitchSensorState.State.valueOf(Strings.toUpperCase(originalValue.trim())) // TODO WTF+ );+ } catch (IllegalArgumentException e) {+ if (!isUnknownSensorValue(originalValue)) {+ LOG.warning(+ "Switch sensor value must be 'on' or 'off', got '" + originalValue + "' in: " + getSensorDefinition()+ );+ }+ return new UnknownState(this);+ }+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "sensorDefinition=" + getSensorDefinition() ++ ", states=" + states ++ '}';+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/sensor/SwitchSensorState.java b/controller/src/main/java/org/openremote/controller/sensor/SwitchSensorState.javanew file mode 100644index 000000000..37d3631b4--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/sensor/SwitchSensorState.java@@ -0,0 +1,80 @@+package org.openremote.controller.sensor;++public class SwitchSensorState extends SensorState<String> {++ public enum State {++ ON("on"),+ OFF("off");++ final private String serializedValue;++ State(String serializedValue) {+ this.serializedValue = serializedValue;+ }++ public String serialize() {+ return serializedValue;+ }+ }++ private String value;+ private State switchState;++ public SwitchSensorState(int sourceID, String sourceName, String value, State switchState) {+ super(sourceID, sourceName);++ this.switchState = switchState;+ this.value = value;+ }++ public SwitchSensorState(int sourceID, String sourceName, State switchState) {+ this(sourceID, sourceName, switchState.serialize(), switchState);+ }++ public State getState() {+ return switchState;+ }++ public SwitchSensorState clone(String value, SwitchSensorState.State state) {+ if (value == null) {+ value = state.serialize();+ }+ return new SwitchSensorState(getSensorID(), getSensorName(), value, state);+ }++ @Override+ public SwitchSensorState clone(String newValue) {+ if (newValue.equalsIgnoreCase(SwitchSensorState.State.ON.serialize())) {+ return clone(null, SwitchSensorState.State.ON);+ } else {+ return clone(null, SwitchSensorState.State.OFF);+ }+ }++ @Override+ public String getValue() {+ return value;+ }++ @Override+ public void setValue(String value) {+ this.value = value;+ }++ @Override+ public String serialize() {+ return getValue();+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "sensorID=" + getSensorID() ++ ", sensorName='" + getSensorName() + "'" ++ ", value='" + getValue() + '\'' ++ ", switchState=" + switchState ++ '}';+ }+}+diff --git a/controller/src/test/groovy/org/openremote/test/rules/ClimateControlTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/ClimateControlTest.groovyindex 7cd55626c..32360f01d 100644--- a/controller/src/test/groovy/org/openremote/test/rules/ClimateControlTest.groovy+++ b/controller/src/test/groovy/org/openremote/test/rules/ClimateControlTest.groovy@@ -3,7 +3,7 @@ package org.openremote.test.rulesimport org.kie.api.KieServicesimport org.kie.api.io.Resourceimport org.openremote.controller.ControllerService-import org.openremote.controller.rules.RuleEngine+import org.openremote.controller.rules.RulesProviderimport org.openremote.test.ContainerTraitimport spock.lang.Specification@@ -13,15 +13,15 @@ class ClimateControlTest extends Specification implements ContainerTrait {def "Climate control basic test"() {- given: "a controller deployment"+ given: "a controller deployment with commands and sensors"def controllerDeploymentXml = getClass().getResourceAsStream("/org/openremote/test/rules/climatecontrol/controller.xml")- and: "event processors and rules"- def ruleEngineProcessor = new RuleEngine() {+ and: "some rules"+ def rulesProvider = new RulesProvider() {@Override- protected Stream<Resource> getResources(KieServices kieServices) {+ Stream<Resource> getResources(KieServices kieServices) {Stream.of(kieServices.getResources().newClassPathResource("org/openremote/test/rules/climatecontrol/ClimateControl.drl"@@ -35,7 +35,7 @@ class ClimateControlTest extends Specification implements ContainerTrait {def controllerService = new ControllerService(controllerDeploymentXml,testCommandBuilder,- ruleEngineProcessor+ rulesProvider)def services = Stream.of(controllerService)def serverPort = findEphemeralPort()diff --git a/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovyindex f26d41383..43bd58dac 100644--- a/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovy+++ b/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovy@@ -3,7 +3,7 @@ package org.openremote.test.rulesimport org.kie.api.KieServicesimport org.kie.api.io.Resourceimport org.openremote.controller.ControllerService-import org.openremote.controller.rules.RuleEngine+import org.openremote.controller.rules.RulesProviderimport org.openremote.test.ContainerTraitimport spock.lang.Specification@@ -18,15 +18,15 @@ class MixedWithErrorsTest extends Specification implements ContainerTrait {def "Execute good rules - ignore broken rules"() {- given: "a controller deployment"+ given: "a controller deployment with commands and sensors"def controllerDeploymentXml = getClass().getResourceAsStream("/org/openremote/test/rules/mixed-with-errors/controller.xml")- and: "some sensor event processors and rules"- def ruleEngineProcessor = new RuleEngine() {+ and: "some rules"+ def rulesProvider = new RulesProvider() {@Override- protected Stream<Resource> getResources(KieServices kieServices) {+ Stream<Resource> getResources(KieServices kieServices) {Stream.of(kieServices.getResources().newClassPathResource("org/openremote/test/rules/mixed-with-errors/EventMod.drl"@@ -49,7 +49,7 @@ class MixedWithErrorsTest extends Specification implements ContainerTrait {def controllerService = new ControllerService(controllerDeploymentXml,testCommandBuilder,- ruleEngineProcessor+ rulesProvider)def services = Stream.of(controllerService)def serverPort = findEphemeralPort()diff --git a/controller/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovyindex fdaa3bfad..d5aeb5886 100644--- a/controller/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovy+++ b/controller/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovy@@ -7,7 +7,7 @@ import org.kie.api.builder.model.KieSessionModelimport org.kie.api.runtime.KieContainerimport org.kie.api.runtime.KieSessionimport org.kie.internal.io.ResourceFactory-import org.openremote.controller.event.CustomStateEvent+import org.openremote.controller.sensor.CustomSensorStateimport org.openremote.controller.rules.RuleExecutionLoggerimport org.openremote.test.ContainerTraitimport spock.lang.Shared@@ -65,7 +65,7 @@ class RuleExecutionLoggerTest extends Specification implements ContainerTrait {*/def "Event listener plumbing"() {given: "a custom state event"- CustomStateEvent newState = new CustomStateEvent(1, TEST_SENSOR_NAME, "ON");+ CustomSensorState newState = new CustomSensorState(1, TEST_SENSOR_NAME, "ON");ksession.insert(newState)and: "a logger of rule execution"@@ -82,7 +82,7 @@ class RuleExecutionLoggerTest extends Specification implements ContainerTrait {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: \"CustomStateEvent\"\n\t\tFields: \n\t\t\tEvent Name: \t\"%s\"\n\t\t\tEvent Value: \t\"ON\"\n", "TestRuleFiring", TEST_SENSOR_NAME, TEST_SENSOR_NAME);+ "\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.FINEdiff --git a/controller/src/test/groovy/org/openremote/test/rules/SimpleRuleTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/SimpleRuleTest.groovyindex c6f956a6d..6584495ee 100644--- a/controller/src/test/groovy/org/openremote/test/rules/SimpleRuleTest.groovy+++ b/controller/src/test/groovy/org/openremote/test/rules/SimpleRuleTest.groovy@@ -3,10 +3,8 @@ package org.openremote.test.rulesimport org.kie.api.KieServicesimport org.kie.api.io.Resourceimport org.openremote.controller.ControllerService-import org.openremote.controller.event.SwitchEvent-import org.openremote.controller.rules.RuleEngine+import org.openremote.controller.rules.RulesProviderimport org.openremote.test.ContainerTrait-import org.openremote.test.util.EventGrabProcessorimport spock.lang.Specificationimport java.util.stream.Stream@@ -19,15 +17,15 @@ class SimpleRuleTest extends Specification implements ContainerTrait {def "Sensor event replaced by rule-triggered event"() {- given: "a controller deployment"+ given: "a controller deployment with commands and sensors"def controllerDeploymentXml = getClass().getResourceAsStream("/org/openremote/test/rules/simple/controller.xml")- and: "event processors and rules"- def ruleEngineProcessor = new RuleEngine() {+ and: "some rules"+ def rulesProvider = new RulesProvider() {@Override- protected Stream<Resource> getResources(KieServices kieServices) {+ Stream<Resource> getResources(KieServices kieServices) {Stream.of(kieServices.getResources().newClassPathResource("org/openremote/test/rules/simple/EventMod.drl"@@ -35,14 +33,12 @@ class SimpleRuleTest extends Specification implements ContainerTrait {)}}- def grabProcessor = new EventGrabProcessor();and: "the started controller server"def controllerService = new ControllerService(controllerDeploymentXml,new TestCommandBuilder(),- ruleEngineProcessor,- grabProcessor+ rulesProvider)def services = Stream.of(controllerService)def serverPort = findEphemeralPort()@@ -52,18 +48,6 @@ class SimpleRuleTest extends Specification implements ContainerTrait {Thread.sleep(500);then: "the rules should immediately switch the sensor off again"- def lastEvent = grabProcessor.lastEvent;- lastEvent.getSourceID() == 123- lastEvent.getSource() == "TestSensor"- lastEvent instanceof SwitchEvent- def grabbedSwitchEvent = (SwitchEvent) lastEvent;- grabbedSwitchEvent.getValue() == "off"- grabbedSwitchEvent.getState() == SwitchEvent.State.OFF-- and: "the total event count is 1, as the event fired in the rule terminates processing of our switch event"- grabProcessor.totalEventCount == 1-- and: "the context state of the sensor should be 'off'"controllerService.getContext().queryValue(123) == "off"and: "the deployment model should work"diff --git a/controller/src/test/groovy/org/openremote/test/rules/VacationTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/VacationTest.groovyindex 940e40209..ddc6186c2 100644--- a/controller/src/test/groovy/org/openremote/test/rules/VacationTest.groovy+++ b/controller/src/test/groovy/org/openremote/test/rules/VacationTest.groovy@@ -3,9 +3,9 @@ package org.openremote.test.rulesimport org.kie.api.KieServicesimport org.kie.api.io.Resourceimport org.openremote.controller.ControllerService-import org.openremote.controller.event.CustomStateEvent-import org.openremote.controller.event.SwitchEvent-import org.openremote.controller.rules.RuleEngine+import org.openremote.controller.rules.RulesProvider+import org.openremote.controller.sensor.CustomSensorState+import org.openremote.controller.sensor.SwitchSensorStateimport org.openremote.test.ContainerTraitimport spock.lang.Specification@@ -17,15 +17,15 @@ class VacationTest extends Specification implements ContainerTrait {def "Vacation example"() {- given: "a controller deployment"+ given: "a controller deployment with commands and sensors"def controllerDeploymentXml = getClass().getResourceAsStream("/org/openremote/test/rules/vacation/controller.xml")- and: "event processors and rules"- def ruleEngineProcessor = new RuleEngine() {+ and: "some rules"+ def rulesProvider = new RulesProvider() {@Override- protected Stream<Resource> getResources(KieServices kieServices) {+ Stream<Resource> getResources(KieServices kieServices) {Stream.of(kieServices.getResources().newClassPathResource("org/openremote/test/rules/vacation/Vacation.drl"@@ -39,14 +39,14 @@ class VacationTest extends Specification implements ContainerTrait {def controllerService = new ControllerService(controllerDeploymentXml,testCommandBuilder,- ruleEngineProcessor+ rulesProvider)def services = Stream.of(controllerService)def serverPort = findEphemeralPort()def container = startContainer(defaultConfig(serverPort), services)when: "the time of day is day"- def customStateEvent = new CustomStateEvent(123, "time of day", "day");+ def customStateEvent = new CustomSensorState(123, "time of day", "day");controllerService.getContext().update(customStateEvent);and: "we wait a bit for the rules to fire"@@ -56,7 +56,7 @@ class VacationTest extends Specification implements ContainerTrait {testCommandBuilder.lastExecutionArgument == "21"when: "the time of day is night"- customStateEvent = new CustomStateEvent(123, "time of day", "night");+ customStateEvent = new CustomSensorState(123, "time of day", "night");controllerService.getContext().update(customStateEvent);and: "we wait a bit for the rules to fire"@@ -66,7 +66,7 @@ class VacationTest extends Specification implements ContainerTrait {testCommandBuilder.lastExecutionArgument == "18"when: "we go on vacation"- def switchEvent = new SwitchEvent(789, "vacation start", "on", SwitchEvent.State.ON);+ def switchEvent = new SwitchSensorState(789, "vacation start", "on", SwitchSensorState.State.ON);controllerService.getContext().update(switchEvent);and: "we wait a bit for the rules to fire"@@ -76,7 +76,7 @@ class VacationTest extends Specification implements ContainerTrait {testCommandBuilder.lastExecutionArgument == "15"when: "the time of day is day"- customStateEvent = new CustomStateEvent(123, "time of day", "day");+ customStateEvent = new CustomSensorState(123, "time of day", "day");controllerService.getContext().update(customStateEvent);and: "we wait a bit for the rules to fire"diff --git a/controller/src/test/groovy/org/openremote/test/util/EventGrabProcessor.java b/controller/src/test/groovy/org/openremote/test/util/EventGrabProcessor.javadeleted file mode 100644index bd4b5d91e..000000000--- a/controller/src/test/groovy/org/openremote/test/util/EventGrabProcessor.java+++ /dev/null@@ -1,38 +0,0 @@-package org.openremote.test.util;--import org.openremote.controller.event.Event;-import org.openremote.controller.event.EventProcessingContext;-import org.openremote.controller.event.EventProcessor;--public class EventGrabProcessor extends EventProcessor {-- public Event lastEvent;- public int totalEventCount = 0;-- @Override- public void process(EventProcessingContext ctx) {- this.lastEvent = ctx.getEvent();- totalEventCount++;- }-- @Override- public String getName() {- return "Event Grab";- }-- public Event getLastEvent() {- return lastEvent;- }-- public int getTotalEventCount() {- return totalEventCount;- }-- @Override- public String toString() {- return "EventGrabProcessor{" +- "lastEvent=" + lastEvent +- ", totalEventCount=" + totalEventCount +- "}";- }-}diff --git a/controller/src/test/resources/org/openremote/test/rules/climatecontrol/ClimateControl.drl b/controller/src/test/resources/org/openremote/test/rules/climatecontrol/ClimateControl.drlindex 96e78a33f..956d06fc3 100644--- a/controller/src/test/resources/org/openremote/test/rules/climatecontrol/ClimateControl.drl+++ b/controller/src/test/resources/org/openremote/test/rules/climatecontrol/ClimateControl.drl@@ -4,8 +4,7 @@ import java.util.concurrent.*;import java.util.Date;import java.text.SimpleDateFormat;import java.io.*;-import org.openremote.controller.model.*;-import org.openremote.controller.event.*;+import org.openremote.controller.sensor.*;global org.openremote.controller.command.Commands commands;global org.openremote.controller.rules.RulePersistence persistence;@@ -13,7 +12,7 @@ global org.openremote.controller.rules.RuleUtil util;global com.fasterxml.jackson.databind.ObjectMapper JSON;global java.util.logging.Logger LOG;-declare Event+declare SensorState@role(event)end@@ -35,7 +34,7 @@ thencommands.execute("VR1.TEMPERATURE.dec","OFF");commands.execute("VNEXTACTION",persistence.readData("VNEXTACTION","-")); // Earlier arrive with resetcommands.execute("VPERSONSENSETIME","-");- commands.execute("VLEAVES", "1.0");+ commands.execute("VLEAVES", "1.0");commands.execute("VSCORE", "0");commands.execute("VHEATINGSETPOINT", "16");commands.execute("VWINDOW","Closed");@@ -60,7 +59,7 @@ endrule "PSB: Init ETA when empty"salience 9when- Event(source matches "VETA.*", $s: source, value=="")+ SensorState(sensorName matches "VETA.*", $s: sensorName, value=="")thencommands.execute($s, persistence.readData($s, "09:00"));end@@ -68,7 +67,7 @@ endrule "PSB: Init ETD when empty"salience 8when- Event(source matches "VETD.*", $s: source, value=="")+ SensorState(sensorName matches "VETD.*", $s: sensorName, value=="")thencommands.execute($s, persistence.readData($s, "17:00"));end@@ -77,29 +76,29 @@ rule "PSB: store values"timer(int: 2s)when(- Event($s:source matches "VET.*", $v:value!="", eval(!persistence.readData($s,"").equals($v))) ||- Event($s:source=="VACATION", $v:value, eval(!persistence.readData($s,"").equals($v))) ||- Event($s:source=="VTOTALSCORE", $v:value, eval(!persistence.readData($s,"").equals($v))) ||- Event($s:source=="VLEVEL", $v:value, eval(!persistence.readData($s,"").equals($v))) ||- Event($s:source=="VR1.COMFORT", $v:value, eval(!persistence.readData($s,"").equals($v))) ||- Event($s:source=="VATA", $v:value, eval(!persistence.readData($s,"").equals($v))) ||- Event($s:source=="VATD", $v:value, eval(!persistence.readData($s,"").equals($v))) ||- Event($s:source=="VNEXTACTION", $v:value, eval(!persistence.readData($s,"").equals($v))) ||- Event($s:source=="VR1.ET", $v:value, eval(!persistence.readData($s,"").equals($v))) ||- Event($s:source=="VETA", $v:value, eval(!persistence.readData($s,"").equals($v))) ||- Event($s:source=="VETD", $v:value, eval(!persistence.readData($s,"").equals($v))) ||- Event($s:source matches "^GV.*", $v:value, eval(!persistence.readData($s,"").equals($v)))+ 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);+then+ LOG.fine($s+" old value: "+persistence.readData($s,"||")+"; new value:"+$v.toString());+ persistence.writeData($s, $v);endrule "-PSB: VR1.ET Inc"timer(int:300ms) // debounce & protect double clickwhen- Event(source == "VR1.ET", $v: value)- Event(source == "VR1.ET.inc" , value == "ON")+ SensorState(sensorName == "VR1.ET", $v: value)+ SensorState(sensorName == "VR1.ET.inc" , value == "ON")thencommands.execute("VR1.ET", util.shiftTime($v.toString(), 5));commands.execute("VR1.ET.inc", "off");@@ -109,8 +108,8 @@ endrule "-PSB: VETA Inc"timer(int:300ms) // debounce & protect double clickwhen- Event(source == "VETA", $v: value)- Event(source == "VETA.inc" , value == "ON")+ SensorState(sensorName == "VETA", $v: value)+ SensorState(sensorName == "VETA.inc" , value == "ON")thencommands.execute("VETA", util.shiftTime($v.toString(), 5));commands.execute("VETA.inc", "off");@@ -120,8 +119,8 @@ endrule "-PSB: VETD Inc"timer(int:300ms) // debounce & protect double clickwhen- Event(source == "VETD", $v: value)- Event(source == "VETD.inc" , value == "ON")+ SensorState(sensorName == "VETD", $v: value)+ SensorState(sensorName == "VETD.inc" , value == "ON")thencommands.execute("VETD", util.shiftTime($v.toString(), 5));commands.execute("VETD.inc", "off");@@ -131,8 +130,8 @@ endrule "-PSB: VR1.ET Dec"timer(int:300ms)when- Event(source == "VR1.ET", $v: value)- Event(source == "VR1.ET.dec" , value == "ON")+ SensorState(sensorName == "VR1.ET", $v: value)+ SensorState(sensorName == "VR1.ET.dec" , value == "ON")thencommands.execute("VR1.ET", util.shiftTime($v.toString(), -15));commands.execute("VR1.ET.inc", "OFF");@@ -142,8 +141,8 @@ endrule "-PSB: VETA Dec"timer(int:300ms)when- Event(source == "VETA", $v: value)- Event(source == "VETA.dec" , value == "ON")+ SensorState(sensorName == "VETA", $v: value)+ SensorState(sensorName == "VETA.dec" , value == "ON")thencommands.execute("VETA", util.shiftTime($v.toString(), -15));commands.execute("VETA.inc", "OFF");@@ -153,8 +152,8 @@ endrule "-PSB: VETD Dec"timer(int:300ms)when- Event(source == "VETD", $v: value)- Event(source == "VETD.dec" , value == "ON")+ SensorState(sensorName == "VETD", $v: value)+ SensorState(sensorName == "VETD.dec" , value == "ON")thencommands.execute("VETD", util.shiftTime($v.toString(), -15));commands.execute("VETD.inc", "OFF");@@ -165,12 +164,12 @@ rule "PSB: VUSERSCHEDULECHANGES change counter"timer(int: 30s) // Wait 30s to mark user's schedule changewhen(- Event($s:source == "VR1.ET.inc" , value == "off") ||- Event($s:source == "VR1.ET.dec" , value == "off") ||- Event($s:source == "VETA.inc" , value == "off") ||- Event($s:source == "VETA.dec" , value == "off") ||- Event($s:source == "VETD.inc" , value == "off") ||- Event($s:source == "VETD.dec" , value == "off")+ 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@@ -189,14 +188,14 @@ rule "PSB: set departure time on manual VR1.ET change"salience 10timer(int: 300ms)when- Event(source == "VR1.ET", $v: value)+ SensorState(sensorName == "VR1.ET", $v: value)(- Event(source == "VR1.ET.inc" , value == "ON") ||- Event(source == "VR1.ET.dec" , value == "ON") ||- Event(source == "VETD.inc", value == "ON") ||- Event(source == "VETD.dec", value == "ON")+ 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"))- Event(source == "VNEXTACTION", value == "-")+ SensorState(sensorName == "VNEXTACTION", value == "-")thencommands.execute("VNEXTACTION", "Departure");end@@ -204,8 +203,8 @@ endrule "PSB: VR1.COMFORT inc"timer(int:300ms)when- Event(source == "VR1.COMFORT", $v: value, eval(util.parseDouble(value) < 24))- Event(source == "VR1.COMFORT.inc" , value == "ON")+ SensorState(sensorName == "VR1.COMFORT", $v: value, eval(util.parseDouble(value) < 24))+ SensorState(sensorName == "VR1.COMFORT.inc" , value == "ON")thencommands.execute("VR1.COMFORT.inc","off");commands.execute("VR1.COMFORT.dec","OFF");@@ -215,8 +214,8 @@ endrule "PSB: VR1.COMFORT dec"timer(int:300ms)when- Event(source == "VR1.COMFORT", $v: value, eval(util.parseDouble(value) > 18))- Event(source == "VR1.COMFORT.dec" , value == "ON")+ SensorState(sensorName == "VR1.COMFORT", $v: value, eval(util.parseDouble(value) > 18))+ SensorState(sensorName == "VR1.COMFORT.dec" , value == "ON")thencommands.execute("VR1.COMFORT.inc","OFF");commands.execute("VR1.COMFORT.dec","off");@@ -227,7 +226,7 @@ rule "PSB: VR1.COMFORT INC/dec" // needed when change on the boundarysalience -10timer(int:300ms)when- Event(source == "VR1.COMFORT.inc" , value == "ON")+ SensorState(sensorName == "VR1.COMFORT.inc" , value == "ON")thencommands.execute("VR1.COMFORT.inc","off");commands.execute("VR1.COMFORT.dec","OFF");@@ -237,7 +236,7 @@ rule "PSB: VR1.COMFORT inc/DEC" // needed when change on the boundarysalience -10timer(int:300ms)when- Event(source == "VR1.COMFORT.dec" , value == "ON")+ SensorState(sensorName == "VR1.COMFORT.dec" , value == "ON")thencommands.execute("VR1.COMFORT.inc","OFF");commands.execute("VR1.COMFORT.dec","off");@@ -246,9 +245,9 @@ endrule "PSB: VR1.TEMPERATURE inc"timer(int:300ms)when- Event(source=="VSUMMER", value=="No")- Event(source == "VR1.TEMPERATURE", $v: value, eval(util.parseDouble(value) <26))- Event(source == "VR1.TEMPERATURE.inc" , value == "ON")+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName == "VR1.TEMPERATURE", $v: value, eval(util.parseDouble(value) <26))+ SensorState(sensorName == "VR1.TEMPERATURE.inc" , value == "ON")thencommands.execute("VR1.TEMPERATURE.inc","off");commands.execute("VR1.TEMPERATURE.dec","OFF"); // Do not increase change counter@@ -258,9 +257,9 @@ endrule "PSB: VR1.TEMPERATURE dec"timer(int:300ms)when- Event(source=="VSUMMER", value=="No")- Event(source == "VR1.TEMPERATURE", $v: value, eval(util.parseDouble(value) > 16)) // Lower temp limit- Event(source == "VR1.TEMPERATURE.dec" , value == "ON")+ 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")thencommands.execute("VR1.TEMPERATURE.inc","OFF");commands.execute("VR1.TEMPERATURE.dec","off");@@ -271,7 +270,7 @@ rule "PSB: VR1.TEMPERATURE INC/dec" // needed when on the boundary and in summersalience -10timer(int:300ms)when- Event(source == "VR1.TEMPERATURE.inc" , value == "ON")+ SensorState(sensorName == "VR1.TEMPERATURE.inc" , value == "ON")thencommands.execute("VR1.TEMPERATURE.inc","off");commands.execute("VR1.TEMPERATURE.dec","OFF");@@ -281,7 +280,7 @@ rule "PSB: VR1.TEMPERATURE inc/DEC" // needed when on the boundary and in summersalience -10timer(int:300ms)when- Event(source == "VR1.TEMPERATURE.dec" , value == "ON")+ SensorState(sensorName == "VR1.TEMPERATURE.dec" , value == "ON")thencommands.execute("VR1.TEMPERATURE.inc","OFF");commands.execute("VR1.TEMPERATURE.dec","off");@@ -291,10 +290,10 @@ rule "PSB: VR1.TEMPERATURE change counter"timer(int: 30s) // Wait 30s to mark user's temperature changewhen(- Event($s:source == "VR1.TEMPERATURE.inc" , value == "off") ||- Event($s:source == "VR1.TEMPERATURE.dec" , value == "off") ||- Event($s:source == "VR1.COMFORT.inc" , value == "off") ||- Event($s:source == "VR1.COMFORT.dec" , value == "off")+ 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@@ -312,10 +311,10 @@ endrule "PSB: VR1.TEMPERATURE change summer"salience 10when- Event(source=="VSUMMER", value=="Yes")+ SensorState(sensorName=="VSUMMER", value=="Yes")(- Event(source == "VR1.TEMPERATURE.inc" , $s: source, value == "ON") ||- Event(source == "VR1.TEMPERATURE.dec", $s: source, value == "ON")+ SensorState(sensorName == "VR1.TEMPERATURE.inc" , $s: sensorName, value == "ON") ||+ SensorState(sensorName == "VR1.TEMPERATURE.dec", $s: sensorName, value == "ON"))thencommands.execute($s, "OFF");@@ -325,13 +324,13 @@ rule "PSB: set departure on manual TEMPERATURE change after expected attendance"salience 10timer(int:300ms)when- Event(source=="VSUMMER", value=="No")- Event(source == "VR1.ET", $et: value)+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName == "VR1.ET", $et: value)(- Event(source == "VR1.TEMPERATURE.inc" , value == "ON") ||- Event(source == "VR1.TEMPERATURE.dec" , value == "ON")+ SensorState(sensorName == "VR1.TEMPERATURE.inc" , value == "ON") ||+ SensorState(sensorName == "VR1.TEMPERATURE.dec" , value == "ON"))- Event(source == "VNEXTACTION", value == "-")+ SensorState(sensorName == "VNEXTACTION", value == "-")then// Set departure time when temp manually adjusted after leavecommands.execute("VNEXTACTION", "Departure");@@ -341,12 +340,12 @@ endrule "PSB: Move ETA to ET at midnight"when- Event(source=="TimerEEE", $e:value)- Event(source=="TimerHH",$h:value,eval(util.parseTimestamp(value) >= util.parseTimestamp("00:02"))) // Wait 2 minutes to be sure that $e is OK- Event(source matches ("VETA."+$e), eval(util.parseTimestamp(value) > util.parseTimestamp($h)), $va:value)- Event(source matches ("VETD."+$e), $vd: value)- Event(source=="VNEXTACTION", value=="-")- Event(source=="VACATION", eval(Integer.parseInt(value.toString())==0))+ 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))thencommands.execute("VR1.ET", $va.toString());commands.execute("VETA", $va.toString());@@ -356,9 +355,9 @@ endrule "Move ETA ETD for current day"when- Event(source=="TimerEEE", $e:value)- Event(source matches ("VETA."+$e), $va:value)- Event(source matches ("VETD."+$e), $vd: value)+ SensorState(sensorName=="TimerEEE", $e:value)+ SensorState(sensorName matches ("VETA."+$e), $va:value)+ SensorState(sensorName matches ("VETD."+$e), $vd: value)thencommands.execute("VETA", $va.toString());commands.execute("VETD", $vd.toString());@@ -366,29 +365,29 @@ endrule "PSB: reset VATA"when- Event(source=="VNEXTACTION", value=="Arrive")+ SensorState(sensorName=="VNEXTACTION", value=="Arrive")thencommands.execute("VATA","-");endrule "PSB: reset VATD"when- Event(source=="VATA",value=="-")+ SensorState(sensorName=="VATA",value=="-")thencommands.execute("VATD","-");endrule "PSB: decrease vacation counter at midnight"when- $timer: Event(source=="TimerHH", eval(value.toString().substring(0,5).equals("00:00"))) // more reliable than timer(cron: )- Event(source=="VACATION", $v: value, eval(Integer.parseInt(value.toString())>0), this before $timer)+ $timer: SensorState(sensorName=="TimerHH", 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 $timer)thencommands.execute("VACATION", Integer.parseInt($v.toString())-1);endrule "PSB: reset action at midnight"when- Event(source=="TimerHH", eval(value.toString().substring(0,5).equals("00:00"))) // more reliable than timer(cron: )+ SensorState(sensorName=="TimerHH", eval(value.toString().substring(0,5).equals("00:00"))) // more reliable than timer(cron: )thencommands.execute("VR1.ET", "-");commands.execute("VNEXTACTION", "-");@@ -397,12 +396,12 @@ endrule "PSB: Move ETD to ET at arrive init"// This one is needed for cases when system is restart after arrive timewhen- Event(source=="TimerEEE",$e:value)- Event(source=="TimerHH",$h:value)- Event(source matches ("VETA."+$e), eval(util.parseTimestamp(value) <= util.parseTimestamp($h)), eval(value.toString().length()==5))- Event(source matches ("VETD."+$e), $vd:value, eval(value.toString().length()==5))-// Event(source=="VNEXTACTION", value=="-")- Event(source=="VR1.ET", value == "--:--")+ 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 == "--:--")thencommands.execute("VR1.ET", $vd.toString());commands.execute("VETD", $vd.toString());@@ -411,13 +410,13 @@ endrule "PSB: Move ETD to ET at arrive"when- Event(source=="TimerEEE",$e:value)- Event(source=="TimerHH",$h:value)- Event(source=="VNEXTACTION", value=="Arrive")- Event(source matches ("VETD."+$e), $vd:value)- Event(source=="VETA", value != "-", value != "--:--")- Event(source=="VETA", eval(util.parseTimestamp(value) < util.parseTimestamp($h)))- Event(source=="VACATION", eval(Integer.parseInt(value.toString())==0))+ 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 != "--:--")+ SensorState(sensorName=="VETA", eval(util.parseTimestamp(value) < util.parseTimestamp($h)))+ SensorState(sensorName=="VACATION", eval(Integer.parseInt(value.toString())==0))thencommands.execute("VR1.ET", $vd.toString());commands.execute("VNEXTACTION", "Departure");@@ -427,37 +426,37 @@ rule "PSB: actual arrival time earlier when temperature increased and person dettimer(int: 10s) // Prevent glitch at midnight resetwhen// Before attendance schedule- Event(source=="TimerHH",$h:value)- Event(source=="VNEXTACTION", value=="Arrive")+ SensorState(sensorName=="TimerHH",$h:value)+ SensorState(sensorName=="VNEXTACTION", value=="Arrive")// Temperature increased manually (higher than ECO)- Event(source=="VSUMMER", value=="No")- Event(source=="VR1.COMFORT", $vc: value)- Event(source=="VR1.TEMPERATURE", eval(util.parseDouble(value) > java.lang.Math.max(util.parseDouble($vc)-5.0, 16.0)))+ 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- Event(source=="VPERSONSENSE", value == "1")- Event(source=="VATA",value=="-")+ SensorState(sensorName=="VPERSONSENSE", value == "1")+ SensorState(sensorName=="VATA",value=="-")thencommands.execute("VR1.ET", $h.toString().substring(0,5));endrule "PSB: fetch actual arrival time"when- Event(source=="TimerHH", $h:value)- Event(source=="VATA", value == "-")- Event(source=="VNEXTACTION", value=="Departure")- Event(source=="VPERSONSENSE", value=="1")+ SensorState(sensorName=="TimerHH", $h:value)+ SensorState(sensorName=="VATA", value == "-")+ SensorState(sensorName=="VNEXTACTION", value=="Departure")+ SensorState(sensorName=="VPERSONSENSE", value=="1")thencommands.execute("VATA", $h.toString().substring(0,5));endrule "PSB: fetch earlier actual arrival time up to 30 min v02"when- Event(source=="TimerHH", $h:value, eval(util.parseTimestamp(value) >= util.parseTimestamp("04:30"))) // Earliest time of arrival is 4:30 AM- Event(source=="VATA", value == "-")- Event(source=="VNEXTACTION", value=="Arrive")- Event(source=="VPERSONSENSE", value=="1")- Event(source=="VETA", value != "-", value != "--:--")- Event(source=="VETA", eval(util.parseTimestamp(util.shiftTime(value,-30)) <= util.parseTimestamp($h)))+ 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)))thencommands.execute("VATA", $h.toString().substring(0,5));end@@ -465,10 +464,10 @@ endrule "PSB: Move - to ET at end of work"timer(int: 1s) // avoid racingwhen- Event(source=="TimerHH",$h:value)- Event(source=="VETD", value != "-", value != "--:--")- Event(source=="VETD", eval(util.parseTimestamp(value) < util.parseTimestamp($h)))- Event(source=="VNEXTACTION", value=="Departure")+ 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")thencommands.execute("VR1.ET", "-");commands.execute("VNEXTACTION", "-");@@ -476,7 +475,7 @@ endrule "PSB: Move - to ET on vacation"when- Event(source=="VACATION", eval(Integer.parseInt(value.toString())>0))+ SensorState(sensorName=="VACATION", eval(Integer.parseInt(value.toString())>0))thencommands.execute("VR1.ET", "-");commands.execute("VNEXTACTION", "-");@@ -484,10 +483,10 @@ endrule "PSB: fetch actual departure time"when- Event(source=="VATA", value != "-")- Event(source=="VATD", value == "-")- Event(source=="VNEXTACTION", value=="-")- Event(source=="VPERSONSENSETIME", $v:value, eval(value.toString().length()>4))+ SensorState(sensorName=="VATA", value != "-")+ SensorState(sensorName=="VATD", value == "-")+ SensorState(sensorName=="VNEXTACTION", value=="-")+ SensorState(sensorName=="VPERSONSENSETIME", $v:value, eval(value.toString().length()>4))thencommands.execute("VATD", $v.toString().substring(0,5));commands.execute("VPERSONSENSETIME","-");@@ -495,15 +494,15 @@ endrule "PSB: fetch later departure time"when- Event(source=="TimerEEE",$e:value)- Event(source=="VNEXTACTION", value=="-")- Event(source matches ("VETD."+$e), $vd:value)- Event(source=="VATA", value != "-")- Event(source=="VATD", value != "-")- Event(source=="VPERSONSENSETIME", $v:value, eval(value.toString().length()>4),+ 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 departureeval(util.parseTimestamp(value)<=util.parseTimestamp("23:55"))) // Till 23:55 - does not wrap on midnight- Event(source=="VACATION", eval(Integer.parseInt(value.toString())==0))+ SensorState(sensorName=="VACATION", eval(Integer.parseInt(value.toString())==0))thencommands.execute("VATD", $v.toString().substring(0,5));commands.execute("VPERSONSENSETIME","-");@@ -511,13 +510,13 @@ endrule "PSB: adjust estimated times at midnight"when- Event(source=="TimerEEE", $e: value)- $timer: Event(source=="TimerHH", eval(value.toString().substring(0,5).equals("23:58"))) // more reliable than timer(cron: )- Event(source matches ("VETD."+$e), $ved:value, this before $timer) // Loop cut- Event(source matches ("VETA."+$e), $vea:value, this before $timer)- Event(source=="VATD", $vd:value, value!="-")- Event(source=="VATA", $va:value, value!="-")- Event(source=="VACATION", eval(Integer.parseInt(value.toString())==0))+ SensorState(sensorName=="TimerEEE", $e: value)+ $timer: SensorState(sensorName=="TimerHH", eval(value.toString().substring(0,5).equals("23:58"))) // more reliable than timer(cron: )+ SensorState(sensorName matches ("VETD."+$e), $ved:value, this before $timer) // Loop cut+ SensorState(sensorName matches ("VETA."+$e), $vea:value, this before $timer)+ SensorState(sensorName=="VATD", $vd:value, value!="-")+ SensorState(sensorName=="VATA", $va:value, value!="-")+ SensorState(sensorName=="VACATION", eval(Integer.parseInt(value.toString())==0))thenDouble alpha = 2.0/(3+1); // 3 stays for 3 days exponential averagelong nt = (long) (alpha*util.parseTimestamp($va) + (1-alpha)*util.parseTimestamp($vea));@@ -530,8 +529,8 @@ endrule "--PSB: move sense"when- Event($s:source=="FS.PIR", value=="on")- Event(source=="TimerHH", $h:value)+ SensorState($s:sensorName=="FS.PIR", value=="on")+ SensorState(sensorName=="TimerHH", $h:value)thenLOG.fine("Move sense on "+$s);commands.execute("VPERSONSENSETIME", $h.toString());@@ -539,8 +538,8 @@ endrule "-PSB: person sense"when- Event($s:source=="FS.PIR", value=="on")- Event(source=="VPERSONSENSE", value!="1")+ SensorState($s:sensorName=="FS.PIR", value=="on")+ SensorState(sensorName=="VPERSONSENSE", value!="1")thencommands.execute("VPERSONSENSE", "1");end@@ -548,29 +547,29 @@ endrule "-PSB: no person sense"timer(int: 2s)when- Event(source=="FS.PIR", value!="on")- Event(source=="VPERSONSENSE", value!="0")+ SensorState(sensorName=="FS.PIR", value!="on")+ SensorState(sensorName=="VPERSONSENSE", value!="0")thencommands.execute("VPERSONSENSE", "0");endrule "-PSB: window open sense"when- Event(source=="FS.Window", value=="on")+ SensorState(sensorName=="FS.Window", value=="on")thencommands.execute("VWINDOW","Open");endrule "-PSB: window closed sense"when- Event(source=="FS.Window", value=="off")+ SensorState(sensorName=="FS.Window", value=="off")thencommands.execute("VWINDOW","Closed");endrule "--FS outside temperature sense"when- Event(source=="FS.Toutside", $v: value)+ SensorState(sensorName=="FS.Toutside", $v: value)thencommands.execute("VOUTSIDE", $v.toString() );LOG.fine("Fake outside temperature: "+$v.toString() );@@ -578,7 +577,7 @@ endrule "--FS inside temperature sense"when- Event(source=="FS.Tinside", $v: value)+ SensorState(sensorName=="FS.Tinside", $v: value)thenLOG.fine("Fake inside temperature: "+ $v.toString() );commands.execute("VROOMTEMPERATURE", $v.toString() );@@ -586,8 +585,8 @@ endrule "PSB: Presence"when- Event(source == "VPERSONSENSE", value == "1")- Event(source=="VNEXTACTION", value=="Departure") // within expected attendance schedule+ SensorState(sensorName == "VPERSONSENSE", value == "1")+ SensorState(sensorName=="VNEXTACTION", value=="Departure") // within expected attendance schedulethencommands.execute("VPRESENCE","Yes");end@@ -595,8 +594,8 @@ endrule "PSB: Absence when 30 min no movement"timer(int: 30m)when- Event(source == "VPERSONSENSE", value == "0")- Event(source=="VNEXTACTION", value=="Departure") // within expected attendance schedule+ SensorState(sensorName == "VPERSONSENSE", value == "0")+ SensorState(sensorName=="VNEXTACTION", value=="Departure") // within expected attendance schedulethencommands.execute("VPRESENCE","No");end@@ -604,14 +603,14 @@ endrule "PSB: Absence after 15 min v02"timer(int: 15m)when- Event(source == "VPERSONSENSE", value == "0")+ SensorState(sensorName == "VPERSONSENSE", value == "0")thencommands.execute("VPRESENCE","No");endrule "PSB: Absence after scheduled presence time"when- Event(source=="VNEXTACTION", value!="Departure") // outsidse expected attendance schedule+ SensorState(sensorName=="VNEXTACTION", value!="Departure") // outsidse expected attendance schedulethencommands.execute("VPRESENCE","No");end@@ -619,8 +618,8 @@ endrule "-PSB: heating ECO"when(- Event(source=="VNEXTACTION", value!="Departure") || // outsidse expected attendance schedule- Event(source=="VSUMMER", value=="Yes")+ SensorState(sensorName=="VNEXTACTION", value!="Departure") || // outsidse expected attendance schedule+ SensorState(sensorName=="VSUMMER", value=="Yes"))thencommands.execute("VHEATING","ECO");@@ -628,11 +627,11 @@ endrule "-PSB: heating Stand-by from ECO"when- Event(source=="VSUMMER", value=="No")- Event(source=="VNEXTACTION", value=="Departure") // within expected attendance schedule- Event(source=="VPRESENCE", value=="No")- Event(source=="VHEATING", value == "ECO")- Event(source=="VR1.COMFORT", $vc: value)+ 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)thencommands.execute("VR1.TEMPERATURE", $vc.toString());commands.execute("VHEATING", "Stand-by");@@ -640,14 +639,14 @@ endrule "-PSB: heating Stand-by from ECO preheating 30 min v02"when- Event(source=="VSUMMER", value=="No")- Event(source=="VNEXTACTION", value=="Arrive") // within expected attendance schedule- Event(source=="VHEATING", value == "ECO")- Event(source=="VR1.COMFORT", $vc: value)-- Event(source=="TimerHH", $h:value, eval(util.parseTimestamp(value) >= util.parseTimestamp("04:30"))) // Earliest time of arrival is 4:30 AM- Event(source=="VETA", value != "-", value != "--:--")- Event(source=="VETA", eval(util.parseTimestamp(util.shiftTime(value,-30)) <= util.parseTimestamp($h)))+ 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)))thencommands.execute("VR1.TEMPERATURE", $vc.toString());commands.execute("VHEATING", "Stand-by");@@ -655,21 +654,21 @@ endrule "-PSB: heating Stand-by from Comfort"when- Event(source=="VSUMMER", value=="No")- Event(source=="VNEXTACTION", value=="Departure") // within expected attendance schedule- Event(source=="VPRESENCE", value=="No")- Event(source=="VHEATING", value == "Comfort")- Event(source=="VR1.COMFORT", $vc: value)- Event(source=="VR1.TEMPERATURE", value==$vc) // Only when no manual temperature increase+ 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 increasethencommands.execute("VHEATING","Stand-by");endrule "-PSB: heating Comfort on presence"when- Event(source=="VSUMMER", value=="No")- Event(source=="VPRESENCE", value=="Yes")- Event(source=="VR1.COMFORT", $v: value)+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VPRESENCE", value=="Yes")+ SensorState(sensorName=="VR1.COMFORT", $v: value)thencommands.execute("VHEATING","Comfort");commands.execute("VR1.TEMPERATURE", $v.toString());@@ -678,19 +677,19 @@ endrule "-PSB: heating Comfort on temperature increase"timer(int: 1s) // debouncewhen- Event(source=="VSUMMER", value=="No")- Event(source=="VR1.COMFORT", $vc: value)- Event(source=="VR1.TEMPERATURE", eval(util.parseDouble(value) > util.parseDouble($vc)))- Event(source=="VHEATING", value != "Comfort")+ 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")thencommands.execute("VHEATING","Comfort");endrule "-PSB: heating setpoint ECO"when- Event(source=="VSUMMER", value=="No")- Event(source=="VHEATING", value=="ECO")- Event(source=="VR1.COMFORT", $v: value)+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VHEATING", value=="ECO")+ SensorState(sensorName=="VR1.COMFORT", $v: value)thenString s = $v.toString();Double t;@@ -705,9 +704,9 @@ endrule "-PSB: heating setpoint ECO summer"when- Event(source=="VSUMMER", value=="Yes")- Event(source=="VHEATING", value=="ECO")- Event(source=="VR1.COMFORT", $v: value)+ SensorState(sensorName=="VSUMMER", value=="Yes")+ SensorState(sensorName=="VHEATING", value=="ECO")+ SensorState(sensorName=="VR1.COMFORT", $v: value)thenString s = $v.toString();Double t = java.lang.Math.max(16.0, Double.parseDouble(s.substring(0,s.length()-1))-5); // 5 degrees below comfort@@ -717,10 +716,10 @@ endrule "-PSB: heating setpoint Stand-by"when- Event(source=="VSUMMER", value=="No")- Event(source=="VHEATING", value=="Stand-by")- Event(source=="VR1.COMFORT", $v: value)- Event(source=="VR1.TEMPERATURE", value==$v) // When temperature changed manually keep it till ECO+ 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 ECOthenString s = $v.toString();Double t = java.lang.Math.max(16.0, Double.parseDouble(s.substring(0,s.length()-1))-1); // 1 degree below comfort@@ -731,9 +730,9 @@ endrule "-PSB: heating setpoint Comfort"timer(int: 1s) // avoid race between "VHEATING" & "VR1.TEMPERATURE"when- Event(source=="VSUMMER", value=="No")- Event(source=="VHEATING", value=="Comfort")- Event(source=="VR1.TEMPERATURE", $v: value) // set by rule "PSB: heating Comfort" to VR1.COMFORT or manually+ 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 manuallythenString s = $v.toString();Double t = java.lang.Math.max(16.0, Double.parseDouble(s.substring(0,s.length()-1)));@@ -742,61 +741,61 @@ endrule "-PSB: leaves 0"when- Event(source=="VLEAVES", value=="0.0")+ SensorState(sensorName=="VLEAVES", value=="0.0")thencommands.execute("VLEAF1", "l0.png");commands.execute("VLEAF2", "l0.png");commands.execute("VLEAF3", "l0.png");end-+rule "-PSB: leaves 0.5"when- Event(source=="VLEAVES", value=="0.5")+ SensorState(sensorName=="VLEAVES", value=="0.5")thencommands.execute("VLEAF1", "l1.png");commands.execute("VLEAF2", "l0.png");commands.execute("VLEAF3", "l0.png");end-+rule "-PSB: leaves 1"when- Event(source=="VLEAVES", value=="1.0")+ SensorState(sensorName=="VLEAVES", value=="1.0")thencommands.execute("VLEAF1", "l2.png");commands.execute("VLEAF2", "l0.png");commands.execute("VLEAF3", "l0.png");end-+rule "-PSB: leaves 1.5"when- Event(source=="VLEAVES", value=="1.5")+ SensorState(sensorName=="VLEAVES", value=="1.5")thencommands.execute("VLEAF1", "l2.png");commands.execute("VLEAF2", "l1.png");commands.execute("VLEAF3", "l0.png");end-+rule "-PSB: leaves 2"when- Event(source=="VLEAVES", value=="2.0")+ SensorState(sensorName=="VLEAVES", value=="2.0")thencommands.execute("VLEAF1", "l2.png");commands.execute("VLEAF2", "l2.png");commands.execute("VLEAF3", "l0.png");end-+rule "-PSB: leaves 2.5"when- Event(source=="VLEAVES", value=="2.5")+ SensorState(sensorName=="VLEAVES", value=="2.5")thencommands.execute("VLEAF1", "l2.png");commands.execute("VLEAF2", "l2.png");commands.execute("VLEAF3", "l1.png");end-+rule "-PSB: leaves 3"when- Event(source=="VLEAVES", value=="3.0")+ SensorState(sensorName=="VLEAVES", value=="3.0")thencommands.execute("VLEAF1", "l2.png");commands.execute("VLEAF2", "l2.png");@@ -805,10 +804,10 @@ endrule "-PSB: energy efficiency 1"when- Event(source=="VSUMMER", value=="No")- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 23)) // Comfort+- Event(source=="VHEATING", value!="ECO") // needed because of race- Event(source=="VPRESENCE", value=="No")+ 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")thencommands.execute("VLEAVES", "0.0");commands.execute("VSCORE", 0);@@ -816,11 +815,11 @@ endrule "-PSB: energy efficiency 2"when- Event(source=="VSUMMER", value=="No")- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 23)) // Comfort+- Event(source=="VHEATING", value!="ECO") // needed because of race- Event(source=="VPRESENCE", value=="Yes")- Event(source=="VWINDOW", value=="Open")+ 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")thencommands.execute("VLEAVES", "0.5");commands.execute("VSCORE", 0);@@ -829,13 +828,13 @@ end// v02rule "-PSB: energy efficiency 2-1 v02"when- Event(source=="VSUMMER", value=="No")- Event(source=="VWINDOW", value=="Open")- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) < 23)) // Comfort, Comfort-, Comfort--- Event(source=="VHEATING", value!="ECO") // needed because of race- Event(source=="VPRESENCE", value=="No")- Event(source=="VOUTSIDE", $t: value)- Event(source=="VR1.TEMPERATURE", eval(util.parseDouble($t) < util.parseDouble(value))) // Lower outside temperature+ 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 temperaturethencommands.execute("VLEAVES", "0.5");commands.execute("VSCORE", 0);@@ -843,11 +842,11 @@ endrule "-PSB: energy efficiency 2-2 v02"when- Event(source=="VSUMMER", value=="No")- Event(source=="VWINDOW", value=="Closed")- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 23)) // Comfort+- Event(source=="VHEATING", value!="ECO") // needed because of race- Event(source=="VPRESENCE", value=="No")+ 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")thencommands.execute("VLEAVES", "0.5");commands.execute("VSCORE", 0);@@ -855,35 +854,35 @@ endrule "-PSB: energy efficiency 2-3 v02"when- Event(source=="VSUMMER", value=="No")- Event(source=="VWINDOW", value=="Closed")- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) < 23), eval(Double.parseDouble(value.toString()) >= 18)) // Comfort, Comfort-, Comfort--, not eco- Event(source=="VHEATING", value!="ECO") // needed because of race- Event(source=="VPRESENCE", value=="No")+ 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")thencommands.execute("VLEAVES", "1.0");commands.execute("VSCORE", 0);end// v02-+rule "-PSB: energy efficiency 3"when- Event(source=="VSUMMER", value=="No")- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 21), eval(Double.parseDouble(value.toString()) < 23)) // Comfort- Event(source=="VHEATING", value!="ECO") // needed because of race- Event(source=="VPRESENCE", value=="No")+ 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")thencommands.execute("VLEAVES", "1.0");commands.execute("VSCORE", 0);end-+rule "-PSB: energy efficiency 4"when- Event(source=="VSUMMER", value=="No")- Event(source=="VWINDOW", value=="Open") // Added because otherwise it overrules efficiency 11- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 21), eval(Double.parseDouble(value.toString()) < 23)) // Comfort- Event(source=="VHEATING", value!="ECO") // needed because of race- Event(source=="VPRESENCE", value=="Yes")+ 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")thencommands.execute("VLEAVES", "1.0");commands.execute("VSCORE", 0);@@ -891,112 +890,112 @@ endrule "-PSB: energy efficiency 5"when- Event(source=="VSUMMER", value=="No")- Event(source=="VHEATING", value=="Stand-by")- Event(source=="VPRESENCE", value=="No")- Event(source=="VWINDOW", value=="Open")+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VHEATING", value=="Stand-by")+ SensorState(sensorName=="VPRESENCE", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Open")thencommands.execute("VLEAVES", "1.0");commands.execute("VSCORE", 0);end-+rule "-PSB: energy efficiency 6"when- Event(source=="VSUMMER", value=="No")- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 23)) // Comfort+- Event(source=="VHEATING", value!="ECO") // needed because of race- Event(source=="VPRESENCE", value=="Yes")- Event(source=="VWINDOW", value=="Open")+ 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")thencommands.execute("VLEAVES", "1.0");commands.execute("VSCORE", 0);end-+rule "-PSB: energy efficiency 7"when- Event(source=="VSUMMER", value=="No")- Event(source=="VWINDOW", value=="Open")- Event(source=="VHEATING", value=="Stand-by")- Event(source=="VPRESENCE", value=="No")- Event(source=="VOUTSIDE", $t: value)- Event(source=="VR1.TEMPERATURE", eval(util.parseDouble($t) < util.parseDouble(value))) // Lower outside temperature+ 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 temperaturethencommands.execute("VLEAVES", "1.5");commands.execute("VSCORE", 1);end-+rule "-PSB: energy efficiency 8"when- Event(source=="VSUMMER", value=="No")- Event(source=="VWINDOW", value=="Open")- Event(source=="VHEATING", value=="ECO")- Event(source=="VPRESENCE", value=="No")- Event(source=="VOUTSIDE", $t: value)- Event(source=="VR1.TEMPERATURE", eval(util.parseDouble($t) < util.parseDouble(value))) // Lower outside temperature+ 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 temperaturethencommands.execute("VLEAVES", "1.5");commands.execute("VSCORE", 1);end-+rule "-PSB: energy efficiency 9"when- Event(source=="VSUMMER", value=="No")- Event(source=="VWINDOW", value=="Closed")- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 23)) // Comfort+- Event(source=="VHEATING", value!="ECO") // needed because of race- Event(source=="VPRESENCE", value=="Yes")+ 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")thencommands.execute("VLEAVES", "1.5");commands.execute("VSCORE", 1);end-+rule "-PSB: energy efficiency 10"when- Event(source=="VSUMMER", value=="No")- Event(source=="VWINDOW", value=="Open")- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 20), eval(Double.parseDouble(value.toString()) < 21)) // Comfort-- Event(source=="VHEATING", value!="ECO") // needed because of race- Event(source=="VPRESENCE", value=="Yes")- Event(source=="VOUTSIDE", $t: value)- Event(source=="VR1.TEMPERATURE", eval(util.parseDouble($t) < util.parseDouble(value))) // Lower outside temperature+ 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 temperaturethencommands.execute("VLEAVES", "1.5");commands.execute("VSCORE", 1);end-+rule "-PSB: energy efficiency 11"when- Event(source=="VSUMMER", value=="No")- Event(source=="VWINDOW", value=="Closed")- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 21), eval(Double.parseDouble(value.toString()) < 23)) // Comfort- Event(source=="VHEATING", value!="ECO") // needed because of race- Event(source=="VPRESENCE", value=="Yes")+ 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")thencommands.execute("VLEAVES", "2.0");commands.execute("VSCORE", 2);end-+rule "-PSB: energy efficiency 12 v02"when- Event(source=="VSUMMER", value=="No")- Event(source=="VWINDOW", value=="Closed")- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) >= 20), eval(Double.parseDouble(value.toString()) < 21)) // Comfort-- Event(source=="VHEATING", value!="ECO") // needed because of race- Event(source=="VPRESENCE", value=="Yes") // v02+ 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") // v02thencommands.execute("VLEAVES", "2.5");commands.execute("VSCORE", 3);end-+rule "-PSB: energy efficiency 13"when- Event(source=="VSUMMER", value=="No")- Event(source=="VWINDOW", value=="Open")- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) < 20)) // Comfort--- Event(source=="VHEATING", value!="ECO") // needed because of race- Event(source=="VPRESENCE", value=="Yes")- Event(source=="VOUTSIDE", $t: value)- Event(source=="VR1.TEMPERATURE", eval(util.parseDouble($t) >= util.parseDouble(value))) // Higher outside temperature+ 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 temperaturethencommands.execute("VLEAVES", "3.0");commands.execute("VSCORE", 4);@@ -1004,10 +1003,10 @@ endrule "-PSB: energy efficiency 14"when- Event(source=="VSUMMER", value=="No")- Event(source=="VWINDOW", value=="Closed")- Event(source=="VHEATING", value=="ECO")- Event(source=="VPRESENCE", value=="No")+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VWINDOW", value=="Closed")+ SensorState(sensorName=="VHEATING", value=="ECO")+ SensorState(sensorName=="VPRESENCE", value=="No")thencommands.execute("VLEAVES", "3.0");commands.execute("VSCORE", 4);@@ -1015,10 +1014,10 @@ endrule "-PSB: energy efficiency 15"when- Event(source=="VSUMMER", value=="No")- Event(source=="VWINDOW", value=="Closed")- Event(source=="VHEATINGSETPOINT", eval(Double.parseDouble(value.toString()) < 20)) // Comfort--- Event(source=="VPRESENCE", value=="Yes") // No important IMHO+ 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 IMHOthencommands.execute("VLEAVES", "3.0");commands.execute("VSCORE", 4);@@ -1026,7 +1025,7 @@ endrule "-PSB: energy efficiency Summer"when- Event(source=="VSUMMER", value=="Yes")+ SensorState(sensorName=="VSUMMER", value=="Yes")thencommands.execute("VLEAVES", "3.0");commands.execute("VSCORE", 4);@@ -1034,17 +1033,17 @@ endrule "--PSB: increase total score every 15m"when- $timer: Event(source=="TimerHH", eval(Integer.parseInt(value.toString().substring(3,5)) % 15 == 0)) // more reliable than timer(cron: )- Event(source=="VSCORE", $s: value)- Event(source=="VTOTALSCORE", $ts: value, this before $timer)+ $timer: SensorState(sensorName=="TimerHH", 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 $timer)thencommands.execute("VTOTALSCORE", Integer.parseInt($ts.toString())+Integer.parseInt($s.toString()));endrule "PSB: reward"when- $ts: Event(source=="VTOTALSCORE", $s: value, eval(Integer.parseInt(value.toString()) >= 1000))- Event(source=="VLEVEL", $l: value, this before $ts)+ $ts: SensorState(sensorName=="VTOTALSCORE", $s: value, eval(Integer.parseInt(value.toString()) >= 1000))+ SensorState(sensorName=="VLEVEL", $l: value, this before $ts)thenInteger i = Integer.parseInt($s.toString());commands.execute("VTOTALSCORE", i-1000); // Reset score@@ -1053,7 +1052,7 @@ endrule "--PSB: display totalscore"when- Event(source=="VTOTALSCORE", $ts: value)+ SensorState(sensorName=="VTOTALSCORE", $ts: value)thencommands.execute("VTOTALSCOREdisp", $ts+" / 1000");end@@ -1061,11 +1060,11 @@ endrule "PSB: summer"timer(int: 1h)when-// Event(source=="VR1.COMFORT", $sp: value)-// Event(source=="VOUTSIDE", value!="", eval(util.parseDouble($sp) <= util.parseDouble(value) )) // Outside temp higher than set point- Event(source=="VOUTSIDE", $o:value) // Only for logging- Event(source=="YT.summer", value=="0") // Y-con test- Event(source=="VSUMMER", value!="Yes")+// 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")thenLOG.fine("Summer is ON; outside="+$o.toString());commands.execute("VSUMMER", "Yes");@@ -1074,11 +1073,11 @@ endrule "PSB: no summer"timer(int: 1h)when-// Event(source=="VR1.COMFORT", $sp: value)-// Event(source=="VOUTSIDE", value!="", eval(util.parseDouble($sp) > util.parseDouble(value) )) // Outside temp lower than set point- Event(source=="VOUTSIDE", $o:value) // Only for logging- Event(source=="YT.summer", value=="1") // Y-con test- Event(source=="VSUMMER", value!="No")+// 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")thenLOG.fine("Summer is OFF; outside="+$o.toString());commands.execute("VSUMMER", "No");@@ -1086,10 +1085,10 @@ endrule "-PSB: advice 1"when- Event(source=="VWINDOW", value=="Open")- Event(source=="VSUMMER", value=="No")- Event(source=="VHEATINGSETPOINT", $sp: value)- Event(source=="VOUTSIDE", value!="", eval(Double.parseDouble($sp.toString()) > util.parseDouble(value) )) // Outside temp lower than set point+ 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 pointthencommands.execute("VADVICE", "It's more energy efficient to close the windows when it is colder outside than it is inside");commands.execute("VADVICEDONE", "OFF");@@ -1098,12 +1097,12 @@ endrule "-PSB: advice 1 done"when- Event(source=="VHEATINGSETPOINT", $sp: value)+ SensorState(sensorName=="VHEATINGSETPOINT", $sp: value)(- Event(source=="VWINDOW", value=="Closed") ||- Event(source=="VOUTSIDE", value!="", eval(Double.parseDouble($sp.toString()) <= util.parseDouble(value) )) // Outside temp lower than set point+ SensorState(sensorName=="VWINDOW", value=="Closed") ||+ SensorState(sensorName=="VOUTSIDE", value!="", eval(Double.parseDouble($sp.toString()) <= util.parseDouble(value) )) // Outside temp lower than set point)- Event(source=="VADVICE",eval(value.toString().substring(0,9).equals("It's more")))+ SensorState(sensorName=="VADVICE",eval(value.toString().substring(0,9).equals("It's more")))thencommands.execute("VADVICE", "You're doing great!");commands.execute("VADVICEDONE", "OFF");@@ -1111,8 +1110,8 @@ endrule "-PSB: advice 2"when- Event(source=="VSUMMER", value=="No")- Event(source=="VR1.COMFORT", eval(util.parseDouble(value) > 20.5)) // Average is 20 hardcoded or from sensor?+ SensorState(sensorName=="VSUMMER", value=="No")+ SensorState(sensorName=="VR1.COMFORT", eval(util.parseDouble(value) > 20.5)) // Average is 20 hardcoded or from sensor?thencommands.execute("VADVICE", "Your comfort temperature is set higher than average. You can adjust it on the settings page.");commands.execute("VADVICEDONE", "OFF");@@ -1121,8 +1120,8 @@ endrule "-PSB: advice 2 done"when- Event(source=="VR1.COMFORT", eval(util.parseDouble(value) <= 20.5)) // Average is 20 hardcoded or from sensor?- Event(source=="VADVICE",eval(value.toString().substring(0,12).equals("Your comfort")))+ 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")))thencommands.execute("VADVICE", "You're doing great!");commands.execute("VADVICEDONE", "OFF");@@ -1134,12 +1133,12 @@ whenthencommands.execute("VADVICEDONE", "OFF");end-+rule "-PSB: advice 4"when(- Event(source=="VADVICEDONE", value=="ON") ||- Event(source=="VSUMMER", value=="Yes")+ SensorState(sensorName=="VADVICEDONE", value=="ON") ||+ SensorState(sensorName=="VSUMMER", value=="Yes"))thencommands.execute("VADVICE", "You're doing great!");@@ -1155,7 +1154,7 @@ endrule "-PSB: advices given counter"when- Event(source=="VADVICE", value!="", value!="You're doing great!")+ SensorState(sensorName=="VADVICE", value!="", value!="You're doing great!")//AdviceGiven(advice!="You're doing great!") // This one fires with the same advicethenint cnt = 0;@@ -1170,8 +1169,8 @@ endrule "-PSB: vacation inc"timer(int:300ms)when- Event(source=="VACATION", $v: value)- Event(source=="VACATION.inc", value=="ON")+ SensorState(sensorName=="VACATION", $v: value)+ SensorState(sensorName=="VACATION.inc", value=="ON")thencommands.execute("VACATION", Integer.parseInt($v.toString())+1);commands.execute("VACATION.inc", "OFF");@@ -1180,8 +1179,8 @@ endrule "-PSB: vacation dec"timer(int:300ms)when- Event(source=="VACATION", $v: value, eval(Integer.parseInt(value.toString()) > 0))- Event(source=="VACATION.dec", value=="ON")+ SensorState(sensorName=="VACATION", $v: value, eval(Integer.parseInt(value.toString()) > 0))+ SensorState(sensorName=="VACATION.dec", value=="ON")thencommands.execute("VACATION", Integer.parseInt($v.toString())-1);commands.execute("VACATION.dec", "OFF");@@ -1191,7 +1190,7 @@ rule "-PSB: vacation inc/dec" // needed so the ON value does not hangsalience -10timer(int:300ms)when- Event(source matches "VACATION...c", $s: source, value=="ON")+ SensorState(sensorName matches "VACATION...c", $s: sensorName, value=="ON")thencommands.execute($s, "OFF");end@@ -1200,8 +1199,8 @@ rule "PSB: start next week stats"timer(cron: 0 0 0 ? * 1) // Every Sunday morning at midnightwhen// Time scheduled- Number($arrive: longValue>0) from accumulate(Event(source matches "VETA.*", $a:value), sum(util.parseTimestamp($a)))- Number($departure: longValue>0) from accumulate(Event(source matches "VETD.*", $d:value), sum(util.parseTimestamp($d)))+ 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)))thenpersistence.writeData("VSETTEMPCHANGES4" ,persistence.readData("VSETTEMPCHANGES3","0"));persistence.writeData("VSETTEMPCHANGES3" ,persistence.readData("VSETTEMPCHANGES2","0"));@@ -1214,7 +1213,7 @@ thenpersistence.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"));@@ -1235,45 +1234,45 @@ endrule "-PSB16: Full Timer"when- Event(source=="TimerEEEE", $EEEE:value)- Event(source=="Timerd", $d: value)- Event(source=="TimerMMM", $MMM:value)+ SensorState(sensorName=="TimerEEEE", $EEEE:value)+ SensorState(sensorName=="Timerd", $d: value)+ SensorState(sensorName=="TimerMMM", $MMM:value)thencommands.execute("VTimer", $EEEE.toString()+" "+$d.toString()+" "+$MMM.toString()+". I will be:");endrule "-PSB16: background arrival on"when- Event(source=="TimerHH", $h:value)- Event(source=="VETA", eval(util.parseTimestamp(value) > util.parseTimestamp($h)) )- Event(source=="VArrivalBackground", value!="on")+ SensorState(sensorName=="TimerHH", $h:value)+ SensorState(sensorName=="VETA", eval(util.parseTimestamp(value) > util.parseTimestamp($h)) )+ SensorState(sensorName=="VArrivalBackground", value!="on")thencommands.execute("VArrivalBackground", "on");endrule "-PSB16: background departure on"when- Event(source=="TimerHH", $h:value)- Event(source=="VETD", eval(util.parseTimestamp(value) > util.parseTimestamp($h)) )- Event(source=="VDepartureBackground", value!="on")+ SensorState(sensorName=="TimerHH", $h:value)+ SensorState(sensorName=="VETD", eval(util.parseTimestamp(value) > util.parseTimestamp($h)) )+ SensorState(sensorName=="VDepartureBackground", value!="on")thencommands.execute("VDepartureBackground", "on");endrule "-PSB16: background arrival off"when- Event(source=="TimerHH", $h:value)- Event(source=="VETA", eval(util.parseTimestamp(value) <= util.parseTimestamp($h)) )- Event(source=="VArrivalBackground", value!="off")+ SensorState(sensorName=="TimerHH", $h:value)+ SensorState(sensorName=="VETA", eval(util.parseTimestamp(value) <= util.parseTimestamp($h)) )+ SensorState(sensorName=="VArrivalBackground", value!="off")thencommands.execute("VArrivalBackground", "off");endrule "-PSB16: background departure off"when- Event(source=="TimerHH", $h:value)- Event(source=="VETD", eval(util.parseTimestamp(value) <= util.parseTimestamp($h)) )- Event(source=="VDepartureBackground", value!="off")+ SensorState(sensorName=="TimerHH", $h:value)+ SensorState(sensorName=="VETD", eval(util.parseTimestamp(value) <= util.parseTimestamp($h)) )+ SensorState(sensorName=="VDepartureBackground", value!="off")thencommands.execute("VDepartureBackground", "off");end@@ -1294,8 +1293,8 @@ endrule "-PID: increase Kp"timer(int:300ms)when- Event(source=="GV.PID.Kp", $v: value)- Event($s:source=="PID.kp.inc", value=="ON")+ SensorState(sensorName=="GV.PID.Kp", $v: value)+ SensorState($s:sensorName=="PID.kp.inc", value=="ON")thencommands.execute("GV.PID.Kp", String.format("%.1f", Double.parseDouble($v.toString())+0.1) );commands.execute($s, "off");@@ -1304,8 +1303,8 @@ endrule "-PID: decrease Kp"timer(int:300ms)when- Event(source=="GV.PID.Kp", $v: value)- Event($s:source=="PID.kp.dec", value=="ON")+ SensorState(sensorName=="GV.PID.Kp", $v: value)+ SensorState($s:sensorName=="PID.kp.dec", value=="ON")thencommands.execute("GV.PID.Kp", String.format("%.1f", Double.parseDouble($v.toString())-0.1) );commands.execute($s, "off");@@ -1314,8 +1313,8 @@ endrule "-PID: increase Ki"timer(int:300ms)when- Event(source=="GV.PID.Ki", $v: value)- Event($s:source=="PID.ki.inc", value=="ON")+ SensorState(sensorName=="GV.PID.Ki", $v: value)+ SensorState($s:sensorName=="PID.ki.inc", value=="ON")thencommands.execute("GV.PID.Ki", String.format("%.1f", Double.parseDouble($v.toString())+0.1) );commands.execute($s, "off");@@ -1324,8 +1323,8 @@ endrule "-PID: decrease Ki"timer(int:300ms)when- Event(source=="GV.PID.Ki", $v: value)- Event($s:source=="PID.ki.dec", value=="ON")+ SensorState(sensorName=="GV.PID.Ki", $v: value)+ SensorState($s:sensorName=="PID.ki.dec", value=="ON")thencommands.execute("GV.PID.Ki", String.format("%.1f", Double.parseDouble($v.toString())-0.1) );commands.execute($s, "off");@@ -1334,8 +1333,8 @@ endrule "-PID: increase Kd"timer(int:300ms)when- Event(source=="GV.PID.Kd", $v: value)- Event($s:source=="PID.kd.inc", value=="ON")+ SensorState(sensorName=="GV.PID.Kd", $v: value)+ SensorState($s:sensorName=="PID.kd.inc", value=="ON")thencommands.execute("GV.PID.Kd", String.format("%.1f", Double.parseDouble($v.toString())+0.1) );commands.execute($s, "off");@@ -1344,8 +1343,8 @@ endrule "-PID: decrease Kd"timer(int:300ms)when- Event(source=="GV.PID.Kd", $v: value)- Event($s:source=="PID.kd.dec", value=="ON")+ SensorState(sensorName=="GV.PID.Kd", $v: value)+ SensorState($s:sensorName=="PID.kd.dec", value=="ON")thencommands.execute("GV.PID.Kd", String.format("%.1f", Double.parseDouble($v.toString())-0.1) );commands.execute($s, "off");@@ -1354,8 +1353,8 @@ endrule "-PID: increase Db"timer(int:300ms)when- Event(source=="GV.PID.Db", $v: value)- Event($s:source=="PID.db.inc", value=="ON")+ SensorState(sensorName=="GV.PID.Db", $v: value)+ SensorState($s:sensorName=="PID.db.inc", value=="ON")thencommands.execute("GV.PID.Db", String.format("%.1f", Double.parseDouble($v.toString())+0.1) );commands.execute($s, "off");@@ -1364,8 +1363,8 @@ endrule "-PID: decrease Db"timer(int:300ms)when- Event(source=="GV.PID.Db", $v: value)- Event($s:source=="PID.db.dec", value=="ON")+ SensorState(sensorName=="GV.PID.Db", $v: value)+ SensorState($s:sensorName=="PID.db.dec", value=="ON")thencommands.execute("GV.PID.Db", String.format("%.1f", Double.parseDouble($v.toString())-0.1) );commands.execute($s, "off");@@ -1374,8 +1373,8 @@ endrule "-PID: increase Sp"timer(int:300ms)when- Event(source=="GV.PID.Sp", $v: value)- Event($s:source=="PID.sp.inc", value=="ON")+ SensorState(sensorName=="GV.PID.Sp", $v: value)+ SensorState($s:sensorName=="PID.sp.inc", value=="ON")thencommands.execute("GV.PID.Sp", String.format("%.1f", Double.parseDouble($v.toString())+0.5) );commands.execute($s, "off");@@ -1384,8 +1383,8 @@ endrule "-PID: decrease Sp"timer(int:300ms)when- Event(source=="GV.PID.Sp", $v: value)- Event($s:source=="PID.sp.dec", value=="ON")+ SensorState(sensorName=="GV.PID.Sp", $v: value)+ SensorState($s:sensorName=="PID.sp.dec", value=="ON")thencommands.execute("GV.PID.Sp", String.format("%.1f", Double.parseDouble($v.toString())-0.5) );commands.execute($s, "off");@@ -1395,7 +1394,7 @@ rule "-PID: reset inc/dec"salience -10timer(int: 1s)when- Event($s: source matches "^PID......c$", value!="off")+ SensorState($s: sensorName matches "^PID......c$", value!="off")thencommands.execute($s, "off");end@@ -1425,11 +1424,11 @@ rule "--PID: compute"timer(int: 0 1s)when$pv: PIDVars(active==true)- Event(source=="GV.PID.Kp", $kp: value)- Event(source=="GV.PID.Ki", $ki: value)- Event(source=="GV.PID.Kd", $kd: value)- Event(source=="GV.PID.Sp", $sp: value)- Event(source=="GV.PID.Db", $db: value)+ SensorState(sensorName=="GV.PID.Kp", $kp: value)+ SensorState(sensorName=="GV.PID.Ki", $ki: value)+ SensorState(sensorName=="GV.PID.Kd", $kd: value)+ SensorState(sensorName=="GV.PID.Sp", $sp: value)+ SensorState(sensorName=="GV.PID.Db", $db: value)thendouble error = Double.parseDouble($sp.toString() ) - $pv.getOutput();double kp = Double.parseDouble($kp.toString());@@ -1438,7 +1437,7 @@ thendouble sp = Double.parseDouble($sp.toString());double db = Double.parseDouble($db.toString());- double iterm = $pv.getIterm() + (ki * error);+ double iterm = $pv.getIterm() + (ki * error);if(iterm > $pv.getOutMax() ) iterm = $pv.getOutMax();else if(iterm < $pv.getOutMin() ) iterm = $pv.getOutMin();$pv.setIterm( iterm );@@ -1446,7 +1445,7 @@ then//double dInput = (Input - lastInput);double dInput = ($pv.getOutput() - $pv.getPrevInput() );$pv.setPrevInput($pv.getOutput());-+// Compute PID Outputdouble output = kp * error + $pv.getIterm()- kd * dInput;if(output > $pv.getOutMax()) output = $pv.getOutMax();@@ -1473,8 +1472,8 @@ endrule "--Fake sensors Toutside inc"timer(int:300ms)when- Event(source == "FS.Toutside", $v: value, eval(util.parseDouble(value) < 50))- Event(source == "FS.Toutside.inc" , value == "on")+ SensorState(sensorName == "FS.Toutside", $v: value, eval(util.parseDouble(value) < 50))+ SensorState(sensorName == "FS.Toutside.inc" , value == "on")thencommands.execute("FS.Toutside.inc","off");commands.execute("FS.Toutside", util.shiftDouble($v.toString(), 0.1, "\u00B0"));@@ -1483,8 +1482,8 @@ endrule "--Fake sensors Toutside dec"timer(int:300ms)when- Event(source == "FS.Toutside", $v: value, eval(util.parseDouble(value) > -40))- Event(source == "FS.Toutside.dec" , value == "on")+ SensorState(sensorName == "FS.Toutside", $v: value, eval(util.parseDouble(value) > -40))+ SensorState(sensorName == "FS.Toutside.dec" , value == "on")thencommands.execute("FS.Toutside.dec","off");commands.execute("FS.Toutside", util.shiftDouble($v.toString(), -0.1, "\u00B0"));@@ -1493,8 +1492,8 @@ endrule "--Fake sensors Tinside inc"timer(int:300ms)when- Event(source == "FS.Tinside", $v: value, eval(util.parseDouble(value) < 40))- Event(source == "FS.Tinside.inc" , value == "on")+ SensorState(sensorName == "FS.Tinside", $v: value, eval(util.parseDouble(value) < 40))+ SensorState(sensorName == "FS.Tinside.inc" , value == "on")thencommands.execute("FS.Tinside.inc","off");commands.execute("FS.Tinside", util.shiftDouble($v.toString(), 0.1, "\u00B0"));@@ -1503,8 +1502,8 @@ endrule "--Fake sensors Tinside dec"timer(int:300ms)when- Event(source == "FS.Tinside", $v: value, eval(util.parseDouble(value) > 0))- Event(source == "FS.Tinside.dec" , value == "on")+ SensorState(sensorName == "FS.Tinside", $v: value, eval(util.parseDouble(value) > 0))+ SensorState(sensorName == "FS.Tinside.dec" , value == "on")thencommands.execute("FS.Tinside.dec","off");commands.execute("FS.Tinside", util.shiftDouble($v.toString(), -0.1, "\u00B0"));@@ -1513,7 +1512,7 @@ endrule "--Fake sensors PIR off"timer(int: 2s)when- Event(source=="FS.PIR", value=="on")+ SensorState(sensorName=="FS.PIR", value=="on")thencommands.execute("FS.PIR", "off");enddiff --git a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/BrokenDTable.csv b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/BrokenDTable.csvindex 2cd505cb7..abd748fe8 100644--- a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/BrokenDTable.csv+++ b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/BrokenDTable.csv@@ -1,14 +1,14 @@, ,Ruleset, Cannot find the ruleset on this one-, ,Import, org.openremote.controller.event.Event+, ,Import, org.openremote.controller.sensors.SensorState,RuleTable,Event Mod, ,CONDITION,ACTION-, ,evt: Event,-,(descriptions),sourceID,evt.setSourceID($param);-,Case, Event Source ID, New Source ID+, ,sensorState: SensorState,+,(descriptions),sensorID,sensorState.setSensorID($param);+,Case, Sensor Source ID, New Source ID,Fire Alarm,555,5555,Ice Age,666,6666,Comfort,777,7777diff --git a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/DTableTest.csv b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/DTableTest.csvindex 77680ed3b..31b5776d6 100644--- a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/DTableTest.csv+++ b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/DTableTest.csv@@ -1,15 +1,15 @@Ruleset, My CSV Rules Examples-Import, org.openremote.controller.event.Event+Import, org.openremote.controller.sensor.SensorStateVariables, org.openremote.controller.rules.RangeFacade ranges,RuleTable,Modify Range Values in Decision Table,CONDITION,ACTION-,evt: Event,-(descriptions),$name : source,"ranges.name($name).value($param);"-Case, Event Source, New Value+,sensorState: SensorState,+(descriptions),$name : sensorName,"ranges.name($name).value($param);"+Case, SensorState Source, New ValueFire Alarm,"TestSensor555",55Ice Age,"TestSensor666",6666Comfort,"TestSensor777",-77diff --git a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/EventMod.drl b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/EventMod.drlindex 1106922d7..3a9c171ae 100644--- a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/EventMod.drl+++ b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/EventMod.drl@@ -1,12 +1,12 @@package org.openremote.test.rules;-import org.openremote.controller.event.*;+import org.openremote.controller.sensor.*;global org.openremote.controller.rules.RangeFacade ranges;rule "Modify Level State Above Max"when- Event( sourceID == 444, $name : source )+ SensorState( sensorID == 444, $name : sensorName )thenranges.name($name).value( 12345 );enddiff --git a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/IncorrectRule.drl b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/IncorrectRule.drlindex be2aaa740..ff96f2c2e 100644--- a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/IncorrectRule.drl+++ b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/IncorrectRule.drl@@ -1,10 +1,10 @@package org.openremote.test.rules;-import org.openremote.controller.event.*;+import org.openremote.controller.sensor.*;rule "Incorrect Event Modification Attempt"when- $event : Event( sourceID == 123 )+ $sensorState : SensorState( sensorID == 123 )then- $event.setSourceID( 321 );+ $sensorState.setFooBarBazOoops( 321 );enddiff --git a/controller/src/test/resources/org/openremote/test/rules/simple/EventMod.drl b/controller/src/test/resources/org/openremote/test/rules/simple/EventMod.drlindex 393db05ad..629534317 100644--- a/controller/src/test/resources/org/openremote/test/rules/simple/EventMod.drl+++ b/controller/src/test/resources/org/openremote/test/rules/simple/EventMod.drl@@ -1,12 +1,12 @@package org.openremote.test.rules;-import org.openremote.controller.event.*;+import org.openremote.controller.sensor.*;global org.openremote.controller.rules.SwitchFacade switches;rule "Modify Switch State"when- $switch : SwitchEvent(sourceID == 123)+ $switch : SwitchSensorState(sensorID == 123)then- switches.name($switch.getSource()).off();+ switches.name($switch.getSensorName()).off();enddiff --git a/controller/src/test/resources/org/openremote/test/rules/simple/TestRuleFiring.drl b/controller/src/test/resources/org/openremote/test/rules/simple/TestRuleFiring.drlindex 03a322f30..a40b3995b 100644--- a/controller/src/test/resources/org/openremote/test/rules/simple/TestRuleFiring.drl+++ b/controller/src/test/resources/org/openremote/test/rules/simple/TestRuleFiring.drl@@ -1,12 +1,11 @@package org.openremote.test.rules;-import org.openremote.controller.command.*;-import org.openremote.controller.event.*;+import org.openremote.controller.sensor.*;import org.openremote.controller.rules.*rule "TestRuleFiring"when- $e: Event(source == RuleExecutionLoggerTest.TEST_SENSOR_NAME)+ $e: SensorState(sensorName == RuleExecutionLoggerTest.TEST_SENSOR_NAME)then// Do Nothingenddiff --git a/controller/src/test/resources/org/openremote/test/rules/vacation/Vacation.drl b/controller/src/test/resources/org/openremote/test/rules/vacation/Vacation.drlindex f7bdf023e..d5646a571 100644--- a/controller/src/test/resources/org/openremote/test/rules/vacation/Vacation.drl+++ b/controller/src/test/resources/org/openremote/test/rules/vacation/Vacation.drl@@ -2,9 +2,7 @@ package org.openremote.test.rules;global org.openremote.controller.command.Commands commands;-import org.openremote.controller.command.*;-import org.openremote.controller.event.*;-import org.openremote.controller.model.*;+import org.openremote.controller.sensor.*;/** This example demonstrates creation of new facts from within the rules, in this@@ -20,7 +18,7 @@ endrule "I'm going on vacation"when- Event ( source == "vacation start" )+ SensorState ( sensorName == "vacation start" )thenVacation vacation = new Vacation();insert ( vacation );@@ -30,7 +28,7 @@ endrule "I'm back from vacation"when- Event ( source == "vacation end" )+ SensorState ( sensorName == "vacation end" )$vacation : Vacation()thenretract ( $vacation );@@ -40,14 +38,14 @@ endrule "Set Night Temperature"when- CustomStateEvent( source == "time of day", value == "night" ) and not Vacation()+ CustomSensorState( sensorName == "time of day", value == "night" ) and not Vacation()thencommands.execute("temp", 18);endrule "Set Night Temperature when on Vacation"when- CustomStateEvent ( source == "time of day", value == "night" ) and exists Vacation()+ CustomSensorState ( sensorName == "time of day", value == "night" ) and exists Vacation()thencommands.execute("temp", 15);end@@ -56,14 +54,14 @@ endrule "Set Day Temperature"when- CustomStateEvent ( source == "time of day", value == "day" ) and not Vacation()+ CustomSensorState ( sensorName == "time of day", value == "day" ) and not Vacation()thencommands.execute("temp", 21);endrule "Set Day Temperature when on Vacation"when- Event ( source == "time of day", value == "day" ) and exists Vacation()+ SensorState ( sensorName == "time of day", value == "day" ) and exists Vacation()thencommands.execute("temp", 15);end