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
Started migration of controller to v3
Christian Bauer3c0f4d6f3f50
diff --git a/container/build.gradle b/container/build.gradleindex 35d14a529..1776fe84d 100644--- a/container/build.gradle+++ b/container/build.gradle@@ -1,7 +1,10 @@apply plugin: "java"+apply plugin: "groovy"dependencies {+ compile "org.codehaus.groovy:groovy-all:$groovyVersion"+compile "org.slf4j:slf4j-api:$slf4jVersion"compile "org.slf4j:slf4j-jdk14:$slf4jVersion"compile "org.slf4j:jcl-over-slf4j:$slf4jVersion"@@ -47,4 +50,10 @@ dependencies {compile "org.apache.camel:camel-jackson:$camelVersion"compile "org.apache.camel:camel-script:$camelVersion"compile "org.apache.camel:camel-groovy:$camelVersion"++ // Test environment dependencies+ compile "org.glassfish.tyrus:tyrus-client:$tyrusVersion"+ compile "org.glassfish.tyrus:tyrus-container-grizzly-client:$tyrusVersion"+ compile "org.objenesis:objenesis:$objenesisVersion"+}diff --git a/manager/test/src/main/groovy/org/openremote/test/BlockingWebsocketEndpoint.groovy b/container/src/main/groovy/org/openremote/test/BlockingWebsocketEndpoint.groovysimilarity index 98%rename from manager/test/src/main/groovy/org/openremote/test/BlockingWebsocketEndpoint.groovyrename to container/src/main/groovy/org/openremote/test/BlockingWebsocketEndpoint.groovyindex 712db877b..65c3131d2 100644--- a/manager/test/src/main/groovy/org/openremote/test/BlockingWebsocketEndpoint.groovy+++ b/container/src/main/groovy/org/openremote/test/BlockingWebsocketEndpoint.groovy@@ -26,7 +26,7 @@ import javax.websocket.MessageHandlerimport javax.websocket.Sessionimport java.util.concurrent.TimeoutException-public class BlockingWebsocketEndpoint extends Endpoint {+class BlockingWebsocketEndpoint extends Endpoint {static final def DEFAULT_TIMEOUT_MILLIS = 5000diff --git a/manager/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy b/container/src/main/groovy/org/openremote/test/ContainerTrait.groovysimilarity index 50%rename from manager/test/src/main/groovy/org/openremote/test/ContainerTrait.groovyrename to container/src/main/groovy/org/openremote/test/ContainerTrait.groovyindex 4350b54bb..fcc9d596f 100644--- a/manager/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy+++ b/container/src/main/groovy/org/openremote/test/ContainerTrait.groovy@@ -19,8 +19,6 @@*/package org.openremote.test-import com.fasterxml.jackson.databind.ObjectMapper-import elemental.json.JsonValueimport org.apache.camel.ProducerTemplateimport org.apache.camel.builder.RouteBuilderimport org.glassfish.tyrus.client.ClientManager@@ -31,62 +29,23 @@ import org.keycloak.representations.AccessTokenResponseimport org.openremote.container.Containerimport org.openremote.container.ContainerServiceimport org.openremote.container.message.MessageBrokerService-import org.openremote.container.persistence.PersistenceServiceimport org.openremote.container.security.AuthFormimport org.openremote.container.security.IdentityServiceimport org.openremote.container.web.WebClientimport org.openremote.container.web.WebService-import org.openremote.manager.server.DemoDataService-import org.openremote.manager.server.agent.AgentService-import org.openremote.manager.server.agent.ConnectorService-import org.openremote.manager.server.asset.AssetService-import org.openremote.manager.server.event.EventService-import org.openremote.manager.server.i18n.I18NService-import org.openremote.manager.server.map.MapService-import org.openremote.manager.server.security.ManagerIdentityService-import org.openremote.manager.server.web.ManagerWebService-import org.openremote.manager.shared.http.Request-import org.openremote.manager.shared.http.RequestParams-import org.openremote.manager.shared.http.SuccessStatusCode-import org.spockframework.mock.IMockMethodimport javax.websocket.ClientEndpointConfigimport javax.websocket.Endpointimport javax.websocket.Sessionimport javax.websocket.WebSocketContainer-import javax.ws.rs.ClientErrorException-import javax.ws.rs.Producesimport javax.ws.rs.client.WebTarget-import javax.ws.rs.core.Responseimport javax.ws.rs.core.UriBuilder-import java.lang.reflect.Methodimport java.util.stream.Streamimport static java.util.concurrent.TimeUnit.SECONDS-import static javax.ws.rs.core.MediaType.APPLICATION_JSONtrait ContainerTrait {- static class UnsupportedXMLHttpRequest implements Request.XMLHttpRequest {- @Override- String getResponseHeader(String header) {- throw new UnsupportedOperationException("Can't access response headers in test framework")- }- }-- static class ResponseWrapperXMLHttpRequest implements Request.XMLHttpRequest {- final Response response-- ResponseWrapperXMLHttpRequest(Response response) {- this.response = response- }-- @Override- String getResponseHeader(String header) {- return response.getHeaderString(header)- }- }-static Map<String, String> defaultConfig(int serverPort) {[(WebService.WEBSERVER_LISTEN_PORT) : Integer.toString(serverPort),@@ -95,25 +54,6 @@ trait ContainerTrait {]}- static Stream<ContainerService> defaultServices(ContainerService... additionalServices) {- Stream.concat(- Arrays.stream(additionalServices),- Stream.of(- new I18NService(),- new ManagerWebService(),- new ManagerIdentityService(),- new MessageBrokerService(),- new PersistenceService(),- new EventService(),- new ConnectorService(),- new AgentService(),- new AssetService(),- new MapService(),- new DemoDataService()- )- )- }-static Container startContainer(Map<String, String> config, Stream<ContainerService> services) {def container = new Container(config, services)container.startBackground()@@ -164,7 +104,7 @@ trait ContainerTrait {}static AccessTokenResponse authenticate(Container container, String realm, String clientId, String username, String password) {- container.getService(ManagerIdentityService.class).getKeycloak()+ container.getService(IdentityService.class).getKeycloak().getAccessToken(realm, new AuthForm(clientId, username, password))}@@ -194,72 +134,4 @@ trait ContainerTrait {def config = ClientEndpointConfig.Builder.create().build()websocketContainer.connectToServer(endpoint, config, websocketUrl.build())}-- // This emulates how a GWT client calls a REST service, we intercept and route through Resteasy Client proxy- static void callResourceProxy(ObjectMapper jsonMapper, ResteasyWebTarget clientTarget, def mockInvocation) {- // If the first parameter of the method we want to call is RequestParams- List<Object> args = mockInvocation.getArguments()- if (!(args[0] instanceof RequestParams)) {- throw new UnsupportedOperationException("Don't know how to handle service API: " + mockInvocation.getMethod)- }-- RequestParams requestParams = (RequestParams) args[0]- IMockMethod mockMethod = mockInvocation.getMethod()-- // Get a Resteasy client proxy for the resource- Class mockedResourceType = mockInvocation.getMockObject().getType()- Method mockedResourceMethod = mockedResourceType.getDeclaredMethod(- mockMethod.name,- mockMethod.parameterTypes.toArray(new Class[mockMethod.parameterTypes.size()])- )- def resourceProxy = clientTarget.proxy(mockedResourceType)-- // Try to find out what the expected success status code is- SuccessStatusCode successStatusCode =- mockedResourceMethod.getDeclaredAnnotation(SuccessStatusCode.class)- int statusCode = successStatusCode != null ? successStatusCode.value() : 200-- // Call the proxy- Object result- boolean resultPassthrough = false- // Fake an XMLHttpRequest for later (we want to access headers if there is an exception...)- Request.XMLHttpRequest xmlHttpRequest = new UnsupportedXMLHttpRequest()- try {- result = resourceProxy."$mockMethod.name"(args)- } catch (ClientErrorException ex) {- statusCode = ex.getResponse().getStatus()- xmlHttpRequest = new ResponseWrapperXMLHttpRequest(ex.getResponse())- try {- result = ex.getResponse().readEntity(String.class)- } catch (IllegalStateException ise) {- // Ignore, this happens when the response is closed already- }- resultPassthrough = true- }-- String responseText = null-- if (result != null) {- // If the method produces JSON, we need to turn whatever the proxy delivered back into JSON string- Produces producesAnnotation = mockedResourceMethod.getDeclaredAnnotation(Produces.class)- if (!resultPassthrough- && producesAnnotation != null- && Arrays.asList(producesAnnotation.value()).contains(APPLICATION_JSON)) {- // Handle elemental JsonValue special, don't use Jackson- if (result instanceof JsonValue) {- JsonValue jsonValue = (JsonValue) result- responseText = jsonValue.toJson()- } else {- responseText = jsonMapper.writeValueAsString(result)- }- } else {- responseText = result.toString()- }- }-- // Pass the result to the callback, so it looks asynchronous for client code- requestParams.callback.call(statusCode, xmlHttpRequest, responseText)- }--}diff --git a/manager/test/src/main/groovy/org/openremote/test/TestUtil.groovy b/container/src/main/groovy/org/openremote/test/TestUtil.groovysimilarity index 100%rename from manager/test/src/main/groovy/org/openremote/test/TestUtil.groovyrename to container/src/main/groovy/org/openremote/test/TestUtil.groovydiff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.javaindex 8ef5388d8..c2d744bed 100644--- a/container/src/main/java/org/openremote/container/Container.java+++ b/container/src/main/java/org/openremote/container/Container.java@@ -27,8 +27,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializationFeature;import com.fasterxml.jackson.databind.node.ObjectNode;import org.openremote.container.json.ElementalJsonModule;+import org.openremote.container.util.LogUtil;-import java.io.IOException;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Paths;@@ -43,30 +43,9 @@ import java.util.stream.StreamSupport;public class Container {public static final Logger LOG;- public static final String LOGGING_CONFIG_FILE = "LOGGING_CONFIG_FILE";static {- // If no JUL configuration is provided- if (System.getProperty("java.util.logging.config.file") == null) {- // Load the logging configuration file specified with an environment variable- if (System.getenv(LOGGING_CONFIG_FILE) != null) {- try (InputStream is = Files.newInputStream(Paths.get(System.getenv(LOGGING_CONFIG_FILE)))) {- LogManager.getLogManager().readConfiguration(is);- } catch (Exception ex) {- throw new ExceptionInInitializerError(ex);- }- // Or load a default configuration from the classpath- } else {- try (InputStream is = Container.class.getClassLoader().getResourceAsStream("logging.properties")) {- if (is != null) {- LogManager.getLogManager().readConfiguration(is);- }- } catch (Exception ex) {- throw new ExceptionInInitializerError(ex);- }- }- }-+ LogUtil.configureLogging("logging.properties");LOG = Logger.getLogger(Container.class.getName());}@@ -78,6 +57,7 @@ public class Container {protected final ObjectNode config;protected final boolean devMode;+ protected boolean running;protected final Map<Class<? extends ContainerService>, ContainerService> services = new LinkedHashMap<>();public Container() {@@ -161,45 +141,56 @@ public class Container {return devMode;}- synchronized public CompletableFuture start() {+ public CompletableFuture start() {return CompletableFuture.runAsync(() -> {- LOG.info(">>> Starting runtime container...");- try {- for (ContainerService service : getServices()) {- LOG.fine("Initializing service: " + service);- service.init(Container.this);- }- for (int counter = getServices().length - 1; counter >= 0; counter--) {- ContainerService service = getServices()[counter];- LOG.fine("Configuring service: " + service);- service.configure(Container.this);- }- for (ContainerService service : getServices()) {- LOG.fine("Starting service: " + service);- service.start(Container.this);+ synchronized (services) {+ if (running)+ return;+ LOG.info(">>> Starting runtime container...");+ try {+ for (ContainerService service : getServices()) {+ LOG.fine("Initializing service: " + service);+ service.init(Container.this);+ }+ for (int counter = getServices().length - 1; counter >= 0; counter--) {+ ContainerService service = getServices()[counter];+ LOG.fine("Configuring service: " + service);+ service.configure(Container.this);+ }+ for (ContainerService service : getServices()) {+ LOG.fine("Starting service: " + service);+ service.start(Container.this);+ }+ } catch (RuntimeException ex) {+ throw ex;+ } catch (Exception ex) {+ throw new RuntimeException(ex);}- } catch (RuntimeException ex) {- throw ex;- } catch (Exception ex) {- throw new RuntimeException(ex);+ running = true;+ LOG.info(">>> Runtime container startup complete");}- LOG.info(">>> Runtime container startup complete");});}- synchronized public void stop() {- LOG.info("<<< Stopping runtime container...");- List<ContainerService> servicesToStop = Arrays.asList(getServices());- Collections.reverse(servicesToStop);- for (ContainerService service : servicesToStop) {- LOG.fine("Stopping service: " + service);+ public void stop() {+ synchronized (services) {+ if (!running)+ return;+ LOG.info("<<< Stopping runtime container...");+ List<ContainerService> servicesToStop = Arrays.asList(getServices());+ Collections.reverse(servicesToStop);try {- service.stop(this);+ for (ContainerService service : servicesToStop) {+ LOG.fine("Stopping service: " + service);+ service.stop(this);+ }} catch (Exception ex) {throw new RuntimeException(ex);+ } finally {+ running = false;}+ LOG.info("<<< Runtime container stopped");}- LOG.info("<<< Runtime container stopped");}/**@@ -222,33 +213,39 @@ public class Container {containerThread.start();}- synchronized public void addService(ContainerService service) {- services.put(service.getClass(), service);+ public void addService(ContainerService service) {+ synchronized (service) {+ services.put(service.getClass(), service);+ }}- synchronized public ContainerService[] getServices() {- return services.values().toArray(new ContainerService[services.size()]);+ public ContainerService[] getServices() {+ synchronized (services) {+ return services.values().toArray(new ContainerService[services.size()]);+ }}/*** Get a service instance matching the specified type exactly, or if that yields* no result, try to get the first service instance that has a matching interface.*/- synchronized public <T extends ContainerService> T getService(Class<T> type) {- //noinspection unchecked- T service = (T) services.get(type);- if (service == null) {- for (ContainerService containerService : services.values()) {- if (type.isAssignableFrom(containerService.getClass())) {- //noinspection unchecked- service = (T) containerService;- break;+ public <T extends ContainerService> T getService(Class<T> type) {+ synchronized (services) {+ //noinspection unchecked+ T service = (T) services.get(type);+ if (service == null) {+ for (ContainerService containerService : services.values()) {+ if (type.isAssignableFrom(containerService.getClass())) {+ //noinspection unchecked+ service = (T) containerService;+ break;+ }}}+ if (service == null)+ throw new IllegalStateException("Missing required service: " + type);+ return service;}- if (service == null)- throw new IllegalStateException("Missing required service: " + type);- return service;}}diff --git a/container/src/main/java/org/openremote/container/util/LogUtil.java b/container/src/main/java/org/openremote/container/util/LogUtil.javanew file mode 100644index 000000000..d796dd618--- /dev/null+++ b/container/src/main/java/org/openremote/container/util/LogUtil.java@@ -0,0 +1,55 @@+/*+ * Copyright 2016, 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.container.util;++import org.openremote.container.Container;++import java.io.InputStream;+import java.nio.file.Files;+import java.nio.file.Paths;+import java.util.logging.LogManager;++public class LogUtil {++ public static final String LOGGING_CONFIG_FILE = "LOGGING_CONFIG_FILE";++ public static void configureLogging(String defaultLoggingProperties) {+ // If no JUL configuration is provided+ if (System.getProperty("java.util.logging.config.file") == null) {+ // Load the logging configuration file specified with an environment variable+ if (System.getenv(LOGGING_CONFIG_FILE) != null) {+ try (InputStream is = Files.newInputStream(Paths.get(System.getenv(LOGGING_CONFIG_FILE)))) {+ LogManager.getLogManager().readConfiguration(is);+ } catch (Exception ex) {+ throw new ExceptionInInitializerError(ex);+ }+ // Or load a default configuration from the classpath+ } else {+ try (InputStream is = Container.class.getClassLoader().getResourceAsStream(defaultLoggingProperties)) {+ if (is != null) {+ LogManager.getLogManager().readConfiguration(is);+ }+ } catch (Exception ex) {+ throw new ExceptionInInitializerError(ex);+ }+ }+ }+ }+}diff --git a/controller/build.gradle b/controller/build.gradleindex 507ce4509..21918c672 100644--- a/controller/build.gradle+++ b/controller/build.gradle@@ -1,3 +1,20 @@+apply plugin: "java"+apply plugin: "application"+apply plugin: "groovy"++mainClassName = "org.openremote.controller.Main"++dependencies {++ compile project(":container")++ compile "org.drools:drools-compiler:6.5.0.Final"+ compile "org.drools:drools-decisiontables:6.5.0.Final"++ testCompile "junit:junit:$junitVersion"+ testCompile "org.spockframework:spock-core:$spockVersion"+}+import com.bmuschko.gradle.docker.tasks.image.*task buildImage(type: DockerBuildImage) {diff --git a/controller/src/main/java/org/openremote/controller/ControllerService.java b/controller/src/main/java/org/openremote/controller/ControllerService.javanew file mode 100644index 000000000..83dcd1389--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/ControllerService.java@@ -0,0 +1,45 @@+package org.openremote.controller;++import org.openremote.container.Container;+import org.openremote.container.ContainerService;+import org.openremote.controller.event.EventProcessorChain;+import org.openremote.controller.statuscache.ChangedStatusTable;+import org.openremote.controller.statuscache.StatusCache;++public class ControllerService implements ContainerService {++ final protected EventProcessorChain eventProcessorChain;++ protected StatusCache cache;++ public ControllerService(EventProcessorChain eventProcessorChain) {+ this.eventProcessorChain =eventProcessorChain;+ }++ @Override+ public void init(Container container) throws Exception {+ }++ @Override+ public void configure(Container container) throws Exception {+ ChangedStatusTable changeStatusTable = new ChangedStatusTable();+ cache = new StatusCache(changeStatusTable, eventProcessorChain);+ }++ @Override+ public void start(Container container) throws Exception {+ if (cache != null)+ cache.start();+ }++ @Override+ public void stop(Container container) throws Exception {+ if (cache != null) {+ cache.shutdown();+ }+ }++ public StatusCache getCache() {+ return cache;+ }+}diff --git a/controller/src/main/java/org/openremote/controller/Main.java b/controller/src/main/java/org/openremote/controller/Main.javanew file mode 100644index 000000000..7d19b6132--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/Main.java@@ -0,0 +1,9 @@+package org.openremote.controller;++public class Main {++ public static void main(String[] args) throws Exception {++ }++}diff --git a/controller/src/main/java/org/openremote/controller/command/Command.java b/controller/src/main/java/org/openremote/controller/command/Command.javanew file mode 100644index 000000000..3c2889d65--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/command/Command.java@@ -0,0 +1,4 @@+package org.openremote.controller.command;++public interface Command {+}diff --git a/controller/src/main/java/org/openremote/controller/command/CommandFactory.java b/controller/src/main/java/org/openremote/controller/command/CommandFactory.javanew file mode 100644index 000000000..40062ca20--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/command/CommandFactory.java@@ -0,0 +1,24 @@+package org.openremote.controller.command;++import org.openremote.controller.model.CommandDefinition;++public abstract class CommandFactory {++ public Command getCommand(CommandDefinition commandDefinition) throws Exception {+ if (commandDefinition == null) {+ throw new Exception("Null reference trying to create a protocol command");+ }++ String protocolType = commandDefinition.getProtocolType();++ if (protocolType == null || protocolType.equals("")) {+ throw new Exception(+ "Protocol attribute is missing: " + commandDefinition+ );+ }++ return buildCommand(commandDefinition);+ }++ protected abstract Command buildCommand(CommandDefinition commandDefinition);+}diff --git a/controller/src/main/java/org/openremote/controller/command/EventProducerCommand.java b/controller/src/main/java/org/openremote/controller/command/EventProducerCommand.javanew file mode 100644index 000000000..26ccd548d--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/command/EventProducerCommand.java@@ -0,0 +1,9 @@+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/ExecutableCommand.java b/controller/src/main/java/org/openremote/controller/command/ExecutableCommand.javanew file mode 100644index 000000000..8c5058425--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/command/ExecutableCommand.java@@ -0,0 +1,9 @@+package org.openremote.controller.command;++public interface ExecutableCommand extends Command {++ /**+ * Send some executable command to device.+ */+ void send();+}diff --git a/controller/src/main/java/org/openremote/controller/command/PullCommand.java b/controller/src/main/java/org/openremote/controller/command/PullCommand.javanew file mode 100644index 000000000..b1859b7bf--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/command/PullCommand.java@@ -0,0 +1,25 @@+package org.openremote.controller.command;++import org.openremote.controller.model.Sensor;++public abstract class PullCommand implements EventProducerCommand {++ public final static int POLLING_INTERVAL = 500;++ /**+ * Read a device status and translate it to a sensor's datatype.+ */+ public abstract String read(Sensor sensor);++ /**+ * Used by {@link Sensor.DeviceReader} to determine the interval used before the next call to read() method.+ * This method can be overridden by subclasses (protocol specific implementations) to specify individual polling intervals.+ * The value must be strictly positive, if a negative or zero value is provided, the default is used instead.+ *+ * @return a polling interval in milliseconds (default is 500ms)+ */+ public int getPollingInterval() {+ return POLLING_INTERVAL;+ }++}diff --git a/controller/src/main/java/org/openremote/controller/command/PushCommand.java b/controller/src/main/java/org/openremote/controller/command/PushCommand.javanew file mode 100644index 000000000..fb450f37e--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/command/PushCommand.java@@ -0,0 +1,78 @@+package org.openremote.controller.command;++import org.openremote.controller.model.Sensor;++/**+ * Push commands are intended for collecting events 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.+ *+ * A push command can be used with the same 'sensor' abstraction (seen for example in+ * the controller's <tt>controller.xml</tt) configuration file) as+ * {@link PullCommand}s.+ *+ * Push commands are expected to create their own threads (if needed) which implement the+ * push functionality and also directly push received events to the+ * (global) state cache of the controller using the sensor callback API provided.+ *+ * Push command implementations can use the sensor+ * {@link org.openremote.controller.model.Sensor#update} method to push state changes+ * into the controller, as shown in the example below:+ *+ * <pre><code>+ *+ * public class SamplePushCommand implements PushCommand, Runnable {+ *+ * // This implementation assumes a command instance per sensor, so only+ * // deals with a single sensor reference+ * Sensor sensor;+ *+ * @Override+ * public void setSensor(Sensor sensor) {+ * this.sensor = sensor;+ *+ * // Initialize the sensor with a default value. The sensor implementation may provide+ * // additional validation or translations to these values...+ *+ * sensor.update("0");+ *+ * // This implementation starts a listening thread per sensor. If you want multiple+ * // push commands / sensors to share same resources or threads, this can be managed in+ * // the command builder implementation...+ *+ * Thread t = new Thread(this);+ * t.start();+ * }+ *+ * @Overide+ * public void run() {+ * String sensorValue = implementYourListenerLogic()+ * sensor.update(sensorValue);+ * }+ * }+ *</code></pre>+ *+ *+ *+ * <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.+ *+ */+public interface PushCommand extends EventProducerCommand {++ /**+ * Each event listener is initialized with one or more sensor references the listener is bound to.+ * If the listener is used as an input for multiple sensors, this callback is invoked multiple+ * times, once for each associated sensor.+ *+ * @param sensor sensor this event listener is bound to+ */+ void setSensor(Sensor sensor);++ void stop(Sensor sensor);+}diff --git a/controller/src/main/java/org/openremote/controller/event/CommandFacade.java b/controller/src/main/java/org/openremote/controller/event/CommandFacade.javanew file mode 100644index 000000000..dfaf9a9c4--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/event/CommandFacade.java@@ -0,0 +1,51 @@+package org.openremote.controller.event;++import org.openremote.controller.model.CommandDefinition;++import java.util.Collection;+import java.util.HashMap;+import java.util.Map;++public class CommandFacade {++ final protected Map<String, CommandDefinition> namedCommands = new HashMap<>();++ public CommandFacade(Collection<CommandDefinition> commandDefinitions) {+ for (CommandDefinition cmd : commandDefinitions) {+ String cmdName = cmd.getProperty(CommandDefinition.COMMAND_NAME_PROPERTY);+ if (cmdName != null && !cmdName.equals("")) {+ namedCommands.put(cmdName, cmd);+ }+ }+ }++ public void command(String name) {+ command(name, null); // null == no param+ }++ public void command(String name, String param) {+ if (name == null || name.equals("")) {+ // TODO log+ return;+ }++ CommandDefinition cmd = namedCommands.get(name);++ if (cmd == null) {+ // TODO log+ return;+ }++ if (param == null) {+ cmd.execute();+ } else {+ cmd.execute(param);+ }+ }++ public void command(String name, int value) {+ command(name, Integer.toString(value));+ }++}+diff --git a/controller/src/main/java/org/openremote/controller/event/CustomStateEvent.java b/controller/src/main/java/org/openremote/controller/event/CustomStateEvent.javanew file mode 100644index 000000000..0d0725e56--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/event/CustomStateEvent.java@@ -0,0 +1,79 @@+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.+ *+ * 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+ throw new Error("NYI");+ }++ @Override+ public boolean isEqual(Object o) {+ if (o == null) {+ return false;+ }++ if (o == this) {+ return true;+ }++ if (o.getClass() != this.getClass()) {+ return false;+ }++ CustomStateEvent cs = (CustomStateEvent) o;++ return cs.getSourceID().equals(this.getSourceID())+ && cs.getSource().equals(this.getSource())+ && cs.getValue().equals(this.getValue());+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/event/Event.java b/controller/src/main/java/org/openremote/controller/event/Event.javanew file mode 100644index 000000000..9c8a60474--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/event/Event.java@@ -0,0 +1,88 @@+package org.openremote.controller.event;++public abstract class Event<T> {++ /**+ * The ID of the originating sensor.+ */+ private int sourceSensorID;++ /**+ * The name of the originating sensor.+ */+ private String sourceSensorName;++ /**+ * Constructs a new event with a given sensor ID and sensor name.+ *+ * @param sourceSensorID ID of the sensor that originated this event+ * @param sourceSensorName human-readable name of the sensor that originated this event+ */+ public Event(int sourceSensorID, String sourceSensorName) {+ this.sourceSensorID = sourceSensorID;+ this.sourceSensorName = sourceSensorName;+ }++ /**+ * Returns the ID of the sensor that originated this event.+ */+ public Integer getSourceID() {+ return sourceSensorID;+ }++ /**+ * Returns the human-readable name of the sensor that originated this event.+ */+ public String getSource() {+ return sourceSensorName;+ }++ public abstract Event clone(T newValue);++ /**+ * Returns the value of this event.+ *+ * @return event value+ */+ public abstract T getValue();++ public abstract void setValue(T value);++ public abstract boolean isEqual(Object o);++ /**+ *+ * This is an intermediate migration API -- at the end of the event processing chain+ * events are stored into the device state cache which panels consume. The API there is+ * still string-based.+ *+ * This method implementation should return an appropriate string representation of the+ * event value.+ *+ * @return string representation of event value+ */+ public abstract String serialize();++ @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/EventContext.java b/controller/src/main/java/org/openremote/controller/event/EventContext.javanew file mode 100644index 000000000..c78104d87--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/event/EventContext.java@@ -0,0 +1,68 @@+package org.openremote.controller.event;++import org.openremote.controller.statuscache.StatusCache;++import java.util.Collection;+import java.util.HashSet;+import java.util.Iterator;+import java.util.Set;+import java.util.logging.Logger;++public class EventContext {++ private static final Logger LOG = Logger.getLogger(EventContext.class.getName());++ private StatusCache cache;+ private Event event;+ private boolean terminated = false;++ public EventContext(StatusCache cache, Event evt) {+ this.cache = cache;+ this.event = evt;+ }++ public void terminate() {+ LOG.fine("Terminating event context");+ terminated = true;+ }++ public boolean hasTerminated() {+ return terminated;+ }++ public StatusCache getStatusCache() {+ return cache;+ }++ public Event getEvent() {+ return event;+ }++ public Collection getEvents() {+ Set<Event> events = new HashSet<Event>();++ Iterator<Event> it = cache.getStateSnapshot();++ while (it.hasNext()) {+ Event evt = it.next();++ if (evt.getSource().equals(getEvent().getSource()) &&+ evt.getSourceID().equals(getEvent().getSourceID())) {+ continue;+ }++ events.add(evt);+ }++ events.add(getEvent());++ return events;+ }+++ @Override+ public String toString() {+ return "Event Context for " + event;+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/event/EventFacade.java b/controller/src/main/java/org/openremote/controller/event/EventFacade.javanew file mode 100644index 000000000..cc1b1e860--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/event/EventFacade.java@@ -0,0 +1,19 @@+package org.openremote.controller.event;++public class EventFacade {++ protected EventContext eventContext;++ public void pushEventContext(EventContext ctx) {+ this.eventContext = ctx;+ }++ protected void dispatchEvent(final Event event) {+ eventContext.terminate();+ Thread t = new Thread(+ () -> eventContext.getStatusCache().update(event)+ );+ t.start();+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/event/EventProcessor.java b/controller/src/main/java/org/openremote/controller/event/EventProcessor.javanew file mode 100644index 000000000..2c95b0c2a--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/event/EventProcessor.java@@ -0,0 +1,18 @@+package org.openremote.controller.event;++public abstract class EventProcessor {++ public void init() throws Exception{+ }++ public void start(CommandFacade commandFacade) throws Exception{+ }++ public void stop() {+ }++ public abstract void push(EventContext 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.javanew file mode 100644index 000000000..ffa249c3d--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/event/EventProcessorChain.java@@ -0,0 +1,77 @@+package org.openremote.controller.event;++import java.util.Arrays;+import java.util.List;+import java.util.logging.Level;+import java.util.logging.Logger;++/**+ * Or, as we call it now, a Camel route.+ */+public class EventProcessorChain {++ private static final Logger LOG = Logger.getLogger(EventProcessorChain.class.getName());++ final protected CommandFacade commandFacade;++ /**+ * Contains the ordered list of configured event processors for this chain.+ */+ final protected List<EventProcessor> processors;++ public EventProcessorChain(CommandFacade commandFacade, EventProcessor... processors) {+ this.processors = Arrays.asList(processors);+ this.commandFacade = commandFacade;+ for (EventProcessor ep : processors) {+ try {+ ep.init();+ } catch (Throwable t) {+ LOG.log(Level.SEVERE, "Cannot initialize event processor: " + ep.getName(), t);+ }+ }+ }++ public void start() {+ for (EventProcessor ep : processors) {+ try {+ LOG.fine("Starting event processor: " + ep.getName());+ ep.start(commandFacade);+ LOG.info("Started event processor: " + ep.getName());+ } catch (Throwable t) {+ LOG.log(Level.SEVERE, "Cannot start event processor: " + ep.getName(), t);+ }+ }+ }++ public void stop() {+ for (EventProcessor ep : processors) {+ try {+ LOG.fine("Stopping event processor: " + ep.getName());+ ep.stop();+ LOG.info("Stopped event processor: " + ep.getName());+ } 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(EventContext ctx) {+ for (EventProcessor processor : processors) {+ LOG.fine("Processing: " + ctx.getEvent());+ processor.push(ctx);+ if (ctx.hasTerminated()) {+ LOG.log(Level.WARNING, "Ignoring event push, context was terminated, stopped event processor chain 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.javanew file mode 100644index 000000000..66f9aebef--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/event/LevelEvent.java@@ -0,0 +1,85 @@+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]+ *+ * 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.+ *+ * Level events are associated with sensors of 'level' type in controller.xml model.+ *+ * 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 boolean isEqual(Object o) {+ if (o == null) {+ return false;+ }++ if (o == this) {+ return true;+ }++ if (o.getClass() != this.getClass()) {+ return false;+ }++ LevelEvent l = (LevelEvent) o;++ return l.getSourceID().equals(this.getSourceID())+ && l.getSource().equals(this.getSource())+ && l.getValue().equals(this.getValue());+ }++}+diff --git a/controller/src/main/java/org/openremote/controller/event/RangeEvent.java b/controller/src/main/java/org/openremote/controller/event/RangeEvent.javanew file mode 100644index 000000000..ef2ca7497--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/event/RangeEvent.java@@ -0,0 +1,86 @@+package org.openremote.controller.event;++public class RangeEvent extends Event<Integer> {++ private Integer rangeValue;+ private Integer min;+ private Integer max;++ public RangeEvent(int sourceID, String sourceName, Integer value, Integer min, Integer max) {+ super(sourceID, sourceName);+ this.min = min;+ this.max = max;+ setValue(value);+ }++ public Integer getMinValue() {+ return min;+ }++ public Integer getMaxValue() {+ return max;+ }++ @Override+ public Integer getValue() {+ return rangeValue;+ }++ @Override+ public void setValue(Integer value) {+ // TODO: The LevelEvent logs when boundaries are breached, why don't we log here?+ if (value > max) {+ this.rangeValue = max;+ } else if (value < min) {+ this.rangeValue = min;+ } else {+ this.rangeValue = value;+ }+ }++ @Override+ public RangeEvent clone(Integer newValue) {+ if (newValue < getMinValue()) {+ newValue = getMinValue();+ } else if (newValue > getMaxValue()) {+ newValue = getMaxValue();+ }++ return new RangeEvent(this.getSourceID(), this.getSource(), newValue, getMinValue(), getMaxValue());+ }++ @Override+ public String serialize() {+ return Integer.toString(rangeValue);+ }++ @Override+ public boolean isEqual(Object o) {+ if (o == null) {+ return false;+ }++ if (o == this) {+ return true;+ }++ if (o.getClass() != this.getClass()) {+ return false;+ }++ RangeEvent r = (RangeEvent) o;++ return r.getSourceID().equals(this.getSourceID())+ && r.getSource().equals(this.getSource())+ && r.rangeValue.equals(this.rangeValue);+ }+++ @Override+ public String toString() {+ return+ "Range Event (ID = " + getSourceID() + ", Source = '" + getSource() + "', Value = '" ++ getValue() + "', Boundaries = [" + getMinValue() + "..." + getMaxValue() + "])";+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/event/SingleValueEventFacade.java b/controller/src/main/java/org/openremote/controller/event/SingleValueEventFacade.javanew file mode 100644index 000000000..4c5db572d--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/event/SingleValueEventFacade.java@@ -0,0 +1,25 @@+package org.openremote.controller.event;++import org.openremote.controller.model.Sensor;++public abstract class SingleValueEventFacade<T, U extends Event> extends EventFacade {++ public T name(String name) throws Exception {+ Event evt = eventContext.getStatusCache().queryStatus(name);++ 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/event/SwitchEvent.java b/controller/src/main/java/org/openremote/controller/event/SwitchEvent.javanew file mode 100644index 000000000..4213e0122--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/event/SwitchEvent.java@@ -0,0 +1,120 @@+/*+ * 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 boolean isEqual(Object o) {+ if (o == null) {+ return false;+ }++ if (o == this) {+ return true;+ }++ if (o.getClass() != this.getClass()) {+ return false;+ }++ SwitchEvent s = (SwitchEvent) o;++ return s.getSourceID().equals(this.getSourceID())+ && s.getSource().equals(this.getSource())+ && s.getValue().equals(this.getValue());+ }+++ @Override+ public String toString() {+ return+ "Switch Event (ID = " + getSourceID() + ", Source = '" + getSource() ++ "', Switch Value = '" + getValue() + "', Switch State = " + getState() + ")";+ }++}+diff --git a/controller/src/main/java/org/openremote/controller/model/CommandDefinition.java b/controller/src/main/java/org/openremote/controller/model/CommandDefinition.javanew file mode 100644index 000000000..7579418d0--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/model/CommandDefinition.java@@ -0,0 +1,199 @@+package org.openremote.controller.model;++import org.openremote.controller.command.Command;+import org.openremote.controller.command.CommandFactory;+import org.openremote.controller.command.ExecutableCommand;+import org.openremote.controller.command.PullCommand;++import java.util.HashMap;+import java.util.Locale;+import java.util.Map;+import java.util.logging.Level;+import java.util.logging.Logger;++/**+ * This is a command model that represents the command properties as an in-memory model for+ * rules, scripts, etc. This is different from the execution model that is currently defined+ * in the org.openremote.controller.command package.+ */+public class CommandDefinition {++ private static final Logger LOG = Logger.getLogger(CommandDefinition.class.getName());++ /**+ * Command property name of dynamic command value for slider, colorpicker.+ * This property is temporary for holding dynamic control command value from REST API.+ * Take slider for example:+ * REST API: http://localhost:8080/controller/rest/control/{slider_id}/10+ * <b>10</b> means control command value of slider+ *+ */+ public static final String DYNAMIC_VALUE_PROPERTY = "dynamicValue";++ /**+ * Default value returned by {@link #getName()} if no name has been set in command's properties.+ */+ public final static String DEFAULT_NAME_PROPERTY_VALUE = "<no name>";++ /**+ * Command property name that contains a logical command name that can be used by scripts,+ * rules, REST API calls, etc.+ */+ public final static String COMMAND_NAME_PROPERTY = "name";++ /**+ * Command factory delegates creation of command execution model to specific protocol specific+ * builders (Such as X10, KNX, one-wire, etc.)+ */+ final private CommandFactory commandFactory;++ /**+ * Command's protocol identifier, such as 'knx', 'x10', 'onewire', etc. This identifier is+ * used to determine which protocol builder plugin is used to construct executable commands.+ */+ final private String protocolType;++ /**+ * A unique command identifier. This corresponds to the 'id' attribute in controller XML+ * definition's {@code <command>} element.+ */+ final private int id;++ /**+ * List of generic command properties. The correspond to {@code <property>} elements nested+ * within {@code <command>} element in controller's XML definition.+ *+ * An arbitrary list of properties is allowed. Specific property names (such as+ * {@link #COMMAND_NAME_PROPERTY}) may have a special meaning.+ *+ * NOTE: property *names* are *not* case sensitive. All property names are converted to lower+ * case.+ */+ final private Map<String, String> properties;++ /**+ * Constructs a command data model.+ *+ * @param commandFactory Command factory is used to construct a protocol specific command execution model+ * (for example, KNX specific commands or X10 specific commands).+ * @param id This represents the unique identifier of the command element in controller's+ * XML definition (corresponding to 'id' attribute of {@code <command>} element)+ * @param protocolType Protocol type identifier for this command. The protocol type identifier is used+ * with the command factory to identify which plugin (Java bean implementation) is+ * used to construct command's protocol specific execution model.+ * @param properties Command's properties. Arbitrary list of properties that can be used to configure+ * command instances. Certain property values such as {@link #COMMAND_NAME_PROPERTY}+ * may have special meaning. The property name,value pairs match the+ * {@code <property>} elements nested within {@code <command>} elements within+ * controller's XML document model.+ */+ public CommandDefinition(CommandFactory commandFactory, int id, String protocolType, Map<String, String> properties) {+ this.commandFactory = commandFactory;+ this.id = id;+ this.protocolType = protocolType;+ this.properties = properties;+ }++ public CommandDefinition(CommandDefinition original) {+ this(+ original.commandFactory,+ original.id,+ original.protocolType,+ new HashMap<>(original.properties)+ );+ }++ /**+ * Returns the unique identifier of the command that corresponds to 'id' attribute of+ * {@code <command>} element in controller's XML definition.+ *+ * @return unique identifier of the command+ */+ public int getID() {+ return id;+ }++ /**+ * Returns a command's name property if present.+ *+ * @return commands name, or a default {@link #DEFAULT_NAME_PROPERTY_VALUE} string if+ * name property is not present+ */+ public String getName() {+ String name = getProperty(COMMAND_NAME_PROPERTY);+ if (name == null || name.equals("")) {+ return DEFAULT_NAME_PROPERTY_VALUE;+ }+ return name;+ }++ /**+ * Returns the protocol type of the command that corresponds to 'protocol' attribute of+ * {@code <command>} element in controller's XML definition.+ *+ * @return the protocol type+ */+ public String getProtocolType() {+ return protocolType;+ }++ /**+ * Returns a command property value.+ *+ * @param name Name of the command property to return. Note that command property names are+ * not case-sensitive. All names are converted to lower case characters.+ * @return Command property value, or empty string if not found.+ */+ public String getProperty(String name) {+ String value = properties.get(name.trim().toLowerCase(Locale.ROOT));+ return (value == null) ? "" : value;+ }++ /**+ * Executes a command. This normally means a device protocol is used to communicate with+ * some physical device.+ */+ public void execute() {+ execute(null); // null == no param+ }++ /**+ * Executes a parameterized command. This normally means a device protocol is used to+ * communicate with some physical device. Command parameterization is typically used+ * with commands that allow setting distinct values, such as setting a volume to a specific+ * distinct level, setting blinds to a specific distinct location, etc.+ *+ * @param param command parameter value+ */+ public void execute(String param) {+ try {+ // Work on a copy of this, so we can modify it for this execution (bad design)+ CommandDefinition commandDefinition = new CommandDefinition(this);+ if (param != null) {+ commandDefinition.properties.put(CommandDefinition.DYNAMIC_VALUE_PROPERTY, param);+ }+ Command command = commandFactory.getCommand(commandDefinition);++ if (command instanceof ExecutableCommand) {+ ExecutableCommand writeCommand = (ExecutableCommand) command;+ writeCommand.send();+ } else if (command instanceof PullCommand) {+ LOG.severe("Execution of read commands not implemented yet.");+ } else {+ LOG.log(Level.SEVERE, "Cannot execute: " + this);+ }+ } catch (Throwable t) {+ LOG.log(Level.SEVERE, "Unable to execute command: " + this, t);+ }+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "protocolType='" + protocolType + '\'' ++ ", id=" + id ++ ", properties=" + properties ++ '}';+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/model/LevelSensor.java b/controller/src/main/java/org/openremote/controller/model/LevelSensor.javanew file mode 100644index 000000000..65731f401--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/model/LevelSensor.java@@ -0,0 +1,37 @@+package org.openremote.controller.model;++import org.openremote.controller.command.EventProducerCommand;+import org.openremote.controller.event.Event;+import org.openremote.controller.event.LevelEvent;+import org.openremote.controller.statuscache.StatusCache;++import java.util.logging.Level;+import java.util.logging.Logger;++public class LevelSensor extends RangeSensor {++ private static final Logger LOG = Logger.getLogger(LevelSensor.class.getName());++ public LevelSensor(String name, int sensorID, StatusCache cache, EventProducerCommand eventProducerCommand, int commandID) {+ super(name, sensorID, cache, eventProducerCommand, commandID, 0, 100);+ }++ @Override+ public Event processEvent(String value) {+ try {+ return new LevelEvent(getSensorID(), getName(), new Integer(value.trim()));+ } catch (NumberFormatException e) {+ if (!isUnknownSensorValue(value)) {+ LOG.log(+ Level.WARNING,+ "Sensor ''{0}'' (ID = {1}) is LEVEL type but produced a value that is not " ++ " an integer : ''{2}''",+ new Object[]{getName(), getSensorID(), value}+ );+ }+ return new UnknownEvent(this);+ }+ }++}+diff --git a/controller/src/main/java/org/openremote/controller/model/RangeSensor.java b/controller/src/main/java/org/openremote/controller/model/RangeSensor.javanew file mode 100644index 000000000..56cde627a--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/model/RangeSensor.java@@ -0,0 +1,62 @@+package org.openremote.controller.model;++import org.openremote.controller.command.EventProducerCommand;+import org.openremote.controller.event.Event;+import org.openremote.controller.event.RangeEvent;+import org.openremote.controller.statuscache.StatusCache;++import java.util.HashMap;+import java.util.logging.Level;+import java.util.logging.Logger;++public class RangeSensor extends Sensor {++ private static final Logger LOG = Logger.getLogger(RangeSensor.class.getName());++ private int minValue;+ private int maxValue;++ public RangeSensor(String name, int sensorID, StatusCache cache, EventProducerCommand eventProducerCommand, int commandID, int minValue, int maxValue) {+ super(name, sensorID, cache, eventProducerCommand, commandID, new HashMap<>());+ if (minValue > maxValue)+ throw new IllegalArgumentException("Sensor value min '" + minValue + "' is larger than max '" + maxValue + "'");+ this.minValue = minValue;+ this.maxValue = maxValue;+ }++ public int getMaxValue() {+ return maxValue;+ }++ public int getMinValue() {+ return minValue;+ }++ @Override+ protected Event processEvent(String value) {+ try {+ return new RangeEvent(getSensorID(), getName(), new Integer(value.trim()), getMinValue(), getMaxValue());+ } catch (NumberFormatException exception) {+ if (!isUnknownSensorValue(value)) {+ LOG.log(+ Level.WARNING,+ "Sensor ''{0}'' (ID = {1}) is RANGE type but produced a value that is not an integer : ''{2}''",+ new Object[]{getName(), getSensorID(), value}+ );+ }+ return new UnknownEvent(this);+ }++ }++ @Override+ public String toString() {+ return "RangeSensor{" ++ ", sensorID=" + getSensorID() ++ ", commandID=" + getCommandID() ++ ", minValue=" + minValue ++ ", maxValue=" + maxValue ++ '}';+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/model/Sensor.java b/controller/src/main/java/org/openremote/controller/model/Sensor.javanew file mode 100644index 000000000..28fb0cc1d--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/model/Sensor.java@@ -0,0 +1,497 @@+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.event.Event;+import org.openremote.controller.statuscache.StatusCache;++import java.security.AccessController;+import java.security.PrivilegedAction;+import java.util.HashMap;+import java.util.Map;+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.+ *+ * 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.+ *+ * 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.+ *+ * Sensors are registered with+ * {@link org.openremote.controller.statuscache.StatusCache device state cache}. Sensors create+ * {@link org.openremote.controller.event.Event} which represent the data from event+ * producers and are passed by cache to+ * {@link org.openremote.controller.event.EventProcessor}s.+ *+ * Therefore the object hierarchy for sensors is as follows:+ *+ * <pre>{@code Cache (one) <--> (many) Sensor (one) <--> (one) Event Producer}</pre>+ *+ * Event producers are created by third party integrators where as cache and sensors are part of+ * the controller framework.+ */+public abstract class Sensor {++ private static final Logger LOG = Logger.getLogger(Sensor.class.getName());++ public static final String UNKNOWN_STATUS = "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);+ }++ /**+ * Human readable sensor name. Used with event processors, logging, etc.+ */+ private String sensorName;++ /**+ * Sensor's unique ID. Must be unique per controller deployment.+ */+ private int sensorID;++ /**+ * Identifier of the the related command that is used to receive sensor values.+ */+ private int commandID;++ /**+ * Reference to the state cache that receives and processes the events generated from this sensor.+ */+ private StatusCache statusCache;++ /**+ * An event producer is a protocol handler that can be customized to return values to a sensor.+ * Therefore the sensor implementation remains type (as in Java class type) and protocol+ * independent and delegates these protocol specific tasks to event producer implementations.+ *+ * Two sub-categories of event producers exist today: pull and push commands. These are dealt+ * differently in that pull commands are actively polled by+ * the sensor while push commands produce events to the controller at their own schedule.+ */+ private EventProducerCommand eventProducerCommand;++ /**+ * This is a polling thread implementation for sensors that use+ * {@link PullCommand} instead of+ * {@link PushCommand}.+ */+ private DeviceReader deviceReader;++ /**+ * Sensor properties. These properties can be used by the protocol implementors to direct+ * their implementation on read commands and event listeners according to sensor configuration.+ */+ private Map<String, String> sensorProperties;++ /**+ * Constructs a new sensor with a given name, ID, sensor datatype (deprecated legacy),+ * an event producing protocol handler, reference to the managing device state cache,+ * and a set of sensor 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 cache reference to a device state cache this sensor registers itself with and pushes+ * value updates to+ * @param eventProducerCommand protocol handler implementation+ * @param commandID A unique command ID. Must be unique per controller deployment.+ * @param sensorProperties Additional sensor properties. These properties can be used by the protocol+ * implementors to direct their implementation according to sensor configuration.+ */+ protected Sensor(String name,+ int sensorID,+ StatusCache cache,+ EventProducerCommand eventProducerCommand,+ int commandID,+ Map<String, String> sensorProperties) {+ if (eventProducerCommand == null) {+ throw new IllegalArgumentException("Sensor requires event producer command: " + sensorID);+ }++ if (sensorProperties == null) {+ sensorProperties = new HashMap<>(0);+ }++ this.sensorName = name;+ this.sensorID = sensorID;+ this.statusCache = cache;+ this.eventProducerCommand = eventProducerCommand;+ this.commandID = commandID;+ this.sensorProperties = sensorProperties;+ }++ /**+ * Returns the human readable name of this sensor.+ *+ * @return sensor's name as defined in tooling and controller's XML definition+ */+ public String getName() {+ return sensorName;+ }++ /**+ * Returns this sensor's ID. The sensor ID is unique within a controller deployment.+ *+ * @return sensor ID+ */+ public int getSensorID() {+ return sensorID;+ }++ /**+ * Returns the identifier of the related command that is used to update sensor values.+ *+ * @return the command ID+ */+ public int getCommandID() {+ return commandID;+ }++ /**+ * Returns sensor's properties. Properties are simply string based name-value mappings.+ * Concrete sensor implementations may specify which particular properties they expose.+ *+ * The returned map does not reference this sensor instance and can be modified freely.+ *+ * @return sensor properties or an empty collection+ */+ public Map<String, String> getProperties() {+ HashMap<String, String> props = new HashMap<>(5);+ props.putAll(sensorProperties);++ return props;+ }++ /**+ * Call path for push commands. Allow direct update of the sensor's value in the controller's+ * global state cache.+ *+ * Before updating the state cache, the value is first validated by concrete sensor+ * implementation's {@link Sensor#processEvent(String)} method.+ *+ * @param state the new value for this sensor+ */+ public void update(String state) {+ // TODO : signature update to event type -- http://jira.openremote.org/browse/ORCJAVA-97+ // TODO : event dispatcher thread -- http://jira.openremote.org/browse/ORCJAVA-99++ // Allow for sensor type specific processing of the value.+ // This can be used for mappings, validating value ranges, etc. before the value is+ // pushed into device state cache and event processor chain.++ Event evt = processEvent(state);+ LOG.fine("Processed '" + state + "', received: " + evt.getValue());+ statusCache.update(evt);+ }++ /**+ * Indicates if this sensor is bound to a command that actively pushes new data.+ */+ public boolean isPushCommand() {+ return eventProducerCommand instanceof PushCommand;+ }++ /**+ * Starts this sensor. When this sensor is bound to push command, will invoke its+ * {@link PushCommand#setSensor(Sensor)} method.+ * For {@link PullCommand} implementations, this will start a polling thread to invoke+ * their {@link PullCommand#read(Sensor)} method.+ */+ public void start() {+ if (isPushCommand()) {+ PushCommand pushCommand = (PushCommand) eventProducerCommand;+ try {+ pushCommand.setSensor(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 {+ deviceReader = new DeviceReader();+ deviceReader.start();+ }+ }++ /**+ * Stops this sensor. In case this sensor has been bound to a push command, the stop+ * invokes its {@link PushCommand#stop(Sensor)} method. In case of a+ * {@link PullCommand}, the polling thread is stopped.+ *+ * @see org.openremote.controller.model.Sensor#start()+ */+ public void stop() {+ if (isPushCommand()) {+ PushCommand pushCommand = (PushCommand) eventProducerCommand;+ try {+ pushCommand.stop(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 stopped correctly.", t);+ }+ } else {+ if (deviceReader != null) {+ deviceReader.stop();+ }+ }+ }++ public boolean isRunning() {+ return deviceReader != null && deviceReader.pollingThreadRunning;+ }++ /**+ * Callback to subclasses to apply their event validations and other processing+ * if necessary. This method is called both when a value is+ * pulled or a command pushes a new sensor value to state cache.+ *+ * @param value value returned by the event producer+ * @return validated and processed value of the event producer+ * @see Sensor#update+ */+ protected abstract Event processEvent(String value);++ /**+ * Handles the {@link PullCommand#read(Sensor)} polling.+ */+ private class DeviceReader implements Runnable {++ /**+ * Indicates the device polling thread's run state. Notice that for immediate stop, setting+ * this to false is not sufficient, but the thread also must be interrupted. See+ * {@link DeviceReader#stop}.+ */+ private volatile boolean pollingThreadRunning = true;++ /**+ * The actual thread reference being used by the owning sensor instance when+ * {@link PullCommand} is used as event producer.+ */+ private Thread pollingThread;++ /**+ * The actual interval used+ */+ private int interval;++ public DeviceReader() {+ if (eventProducerCommand instanceof PullCommand) {+ int pollingInterval = ((PullCommand) eventProducerCommand).getPollingInterval();+ if (pollingInterval > 0) {+ this.interval = ((PullCommand) eventProducerCommand).getPollingInterval();+ } else {+ this.interval = PullCommand.POLLING_INTERVAL;+ }+ } else {+ this.interval = PullCommand.POLLING_INTERVAL;+ }+ LOG.log(Level.INFO,+ "Created polling thread for sensor (ID = {0}, name = {1}), polling interval {3}",+ new Object[]{getSensorID(), getName(), this.interval}+ );+ }++ /**+ * Starts the device polling thread.+ */+ public void start() {+ pollingThreadRunning = true;+ pollingThread = new Thread(this);+ pollingThread.start();+ }++ /**+ * Stops the device polling thread. Notice that stopping the thread will cause it to exit.+ * The same thread cannot be resumed but a new thread will be created via+ * {@link DeviceReader#start()}.+ */+ public void stop() {+ pollingThreadRunning = false;+ try {+ AccessController.doPrivilegedWithCombiner((PrivilegedAction<Void>) () -> {+ pollingThread.interrupt();+ return null;+ });+ } catch (SecurityException e) {+ LOG.log(+ Level.WARNING,+ "Could not interrupt device polling thread ''{0}'' due to security constraints: {1}\n" ++ "the thread will exit in {2} milliseconds...",+ new Object[]{pollingThread.getName(), e.getMessage(), PullCommand.POLLING_INTERVAL}+ );+ }+ }++ /**+ * Once every given interval defined in {@link PullCommand#POLLING_INTERVAL}, invokes a read()+ * request on the sensor and the underlying event producer. Depending on event producer+ * implementation this may create a concrete request on the device to read current state, or+ * it may return a cached value from memory.+ */+ @Override+ public void run() {+ LOG.log(+ Level.INFO,+ "Started polling thread for sensor (ID = {0}, name = {1}).",+ new Object[]{getSensorID(), getName()}+ );++ while (pollingThreadRunning) {+ Sensor.this.update(read());++ try {+ Thread.sleep(this.interval);+ } catch (InterruptedException e) {+ pollingThreadRunning = false;+ LOG.log(+ Level.INFO,+ "Shutting down polling thread of sensor (ID = {0}, name = {1}).",+ new Object[]{getSensorID(), getName()}+ );+ Thread.currentThread().interrupt();+ }+ }+ }+++ /**+ * Returns the current state of this sensor.+ *+ * If the sensor is bound to a pull command implementation, the command is invoked --+ * this may yield an active request using the connecting transport to device unless the+ * command implementation caches certain values and returns them from memory.+ *+ * In case of a push command, this method does not invoke anything on the command itself+ * but returns the last stored state from the controller's device state cache associated with+ * this sensor's ID. A push command implementation is responsible of actively updating and+ * inserting the device state values into the controller's cache.+ *+ * In case of errors, {@link #UNKNOWN_STATUS} is returned.+ *+ * 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)}+ * 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.+ */+ private String read() {++ // If this sensor abstracts a push command, the read() will not invoke the protocol+ // handler associated with this sensor directly -- instead we try to fetch the latest+ // value produced by a push command from the controller's global device state cache.++ if (isPushCommand()) {+ return statusCache.queryStatus(sensorID);+ } else if (eventProducerCommand instanceof PullCommand) {+ // If we are dealing with pull commands, execute it to explicitly fetch the+ // device state...+ PullCommand command = (PullCommand) eventProducerCommand;+ try {+ return command.read(Sensor.this);+ } catch (Throwable t) {+ LOG.log(Level.SEVERE, "Implementation error in pull command: " + eventProducerCommand, t);+ return UNKNOWN_STATUS;+ }+ } else {+ throw new IllegalArgumentException(+ "Sensor has been initialized with an event producer that is neither a pull nor a push command. " ++ "This type can not be handled: " + eventProducerCommand.getClass().getName()+ );+ }+ }+ }++ /**+ * 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.+ *+ * The value returned by this event is defined in {@link #UNKNOWN_STATUS}.+ */+ public static class UnknownEvent extends Event<String> {++ public UnknownEvent(Sensor sensor) {+ super(sensor.getSensorID(), sensor.getName());+ }++ @Override+ public String getValue() {+ return serialize();+ }++ @Override+ public void setValue(String str) {+ // NOOP+ }++ @Override+ public UnknownEvent clone(String ignored) {+ return this;+ }++ @Override+ public boolean isEqual(Object o) {+ if (o == null) {+ return false;+ }+ if (o.getClass() != this.getClass()) {+ return false;+ }+ UnknownEvent ue = (UnknownEvent) o;+ return ue.getSourceID().equals(this.getSourceID())+ && ue.getSource().equals(this.getSource());+ }++ @Override+ public String serialize() {+ return UNKNOWN_STATUS;+ }+ }++ /**+ * Test sensor object equality based on unique identifier (as returned by {@link #getSensorID}.+ *+ * Subclasses are considered equal, despite what their data values are, as long as the sensor+ * ID is equal.+ *+ * @param o object to compare to+ * @return true if equals, false otherwise+ */+ @Override+ public boolean equals(Object o) {+ if (o == null)+ return false;++ if (!(o instanceof Sensor))+ return false;++ Sensor sensor = (Sensor) o;++ return sensor.getSensorID() == this.getSensorID();+ }++ @Override+ public int hashCode() {+ return sensorID;+ }+}diff --git a/controller/src/main/java/org/openremote/controller/model/StateSensor.java b/controller/src/main/java/org/openremote/controller/model/StateSensor.javanew file mode 100644index 000000000..5b5c3e958--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/model/StateSensor.java@@ -0,0 +1,311 @@+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.event.CustomStateEvent;+import org.openremote.controller.event.Event;+import org.openremote.controller.statuscache.StatusCache;++import java.util.HashMap;+import java.util.Map;+import java.util.Set;+import java.util.logging.Level;+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 StateSensor extends Sensor {++ private static final Logger LOG = Logger.getLogger(StateSensor.class.getName());++ /**+ * The default setting for enforcing strict state mapping rules -- only explicitly declared+ * state values can be returned from this sensor.+ */+ public final static boolean DEFAULT_STRICT_STATE_MAPPING = true;++ /**+ * Adds distinct states as sensor properties.+ *+ * @param include indicates whether the sensor's distinct states should be included as+ * properties or if an empty property set should be returned instead+ * @param states the distinct states of this sensor+ * @return sensor's properties, including the distinct state names if included+ */+ private static Map<String, String> statesAsProperties(boolean include, DistinctStates states) {+ if (states == null || !include) {+ return new HashMap<>(0);+ }+ HashMap<String, String> props = new HashMap<>();+ int index = 1;+ for (String state : states.getAllStates()) {+ props.put("state-" + index++, state);+ }+ return props;+ }++ /**+ * Stores the state values and possible mappings for this sensor.+ */+ private DistinctStates states;+++ /**+ * 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.+ */+ private boolean hasStrictStateMapping = DEFAULT_STRICT_STATE_MAPPING;++ /**+ * Constructs a new sensor with a given sensor ID, event producer and distinct state values+ * this sensor will return.+ * <p>+ * The default implementation of a state sensor sends all its state values to event producer+ * implementations -- therefore protocol implementers can inspect what the expected return+ * values of a state sensor are and adjust their implementations accordingly. See+ * {@link PullCommand} and+ * {@link PushCommand} for details.+ *+ * @param name human-readable name of this sensor+ * @param sensorID controller unique identifier+ * @param cache reference to the device state cache this sensor will register with+ * @param producer the protocol handler that backs this sensor either with a read command+ * or event listener implementation+ * @param commandID controller unique identifier of related command+ * @param states distinct state values and their mappings this sensor will return+ */+ public StateSensor(String name, int sensorID, StatusCache cache, EventProducerCommand producer, int commandID, DistinctStates states) {+ this(name, sensorID, cache, producer, commandID, states, true);+ }++ /**+ * 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 name human-readable name of this sensor+ * @param sensorID controller unique identifier+ * @param cache reference to the device state cache this sensor will register with+ * @param producer the protocol handler that backs this sensor either with a read command+ * or event listener implementation+ * @param commandID controller unique identifier of related command+ * @param states distinct state values and their mappings this sensor will return+ * @param includeStatesAsProperties indicates whether the sensor implementation should pass the+ * explicit state strings as sensor properties for event producer implementers+ * to inspect+ */+ protected StateSensor(String name, int sensorID, StatusCache cache, EventProducerCommand producer,+ int commandID, DistinctStates states, boolean includeStatesAsProperties) {+ super(name, sensorID, cache, producer, commandID, statesAsProperties(includeStatesAsProperties, states));++ if (states == null) {+ this.states = new DistinctStates();+ } else {+ this.states = states;+ }+ }++ /**+ * 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 #setStrictStateMapping} 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 #setStrictStateMapping} 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 (hasStrictStateMapping) {+ Event evt = new UnknownEvent(this);+ LOG.log(Level.WARNING,+ "Event producer bound to sensor (ID = {0}) returned a value that is not " ++ "consistent with sensor''s datatype : {1} setting sensor value to ''{2}''",+ new Object[]{super.getSensorID(), value, evt.getValue()}+ );++ return new UnknownEvent(this);+ } else {+ return createEvent(value);+ }+ }++ if (!states.hasMapping(value)) {+ return createEvent(value);+ } else {+ return createEvent(states.getMapping(value), value);+ }+ }+++ /**+ * When set to true, this sensor can only return values that have been explicitly declared as+ * its distinct states. When false, any arbitrary value can be returned from the sensor (those+ * with distinct state mappings will get translated).+ *+ * @param strictStateMapping true or false+ */+ public void setStrictStateMapping(boolean strictStateMapping) {+ this.hasStrictStateMapping = strictStateMapping;+ }++ /**+ * 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) {+ int id = getSensorID();+ String name = getName();++ return new CustomStateEvent(id, name, 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) {+ int id = getSensorID();+ String name = getName();++ return new CustomStateEvent(id, name, 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 "StateSensor{" ++ ", sensorID=" + getSensorID() ++ ", commandID=" + getCommandID() ++ ", hasStrictStateMapping=" + hasStrictStateMapping ++ ", 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.javanew file mode 100644index 000000000..7d03b6048--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/model/SwitchSensor.java@@ -0,0 +1,122 @@+package org.openremote.controller.model;++import org.bouncycastle.util.Strings;+import org.openremote.controller.command.EventProducerCommand;+import org.openremote.controller.event.Event;+import org.openremote.controller.event.SwitchEvent;+import org.openremote.controller.statuscache.StatusCache;++import java.util.logging.Level;+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 StateSensor {++ private static final Logger LOG = Logger.getLogger(SwitchSensor.class.getName());++ /**+ * Set up the distinct on/off states for the superclass constructor+ *+ * @return distinct states for the state sensor+ */+ private static DistinctStates createSwitchStates() {+ DistinctStates states = new DistinctStates();+ states.addState("on");+ states.addState("off");+ return states;+ }++ /**+ * Constructs a new switch sensor with given sensor ID and event producer. The sensor+ * implementation will return 'on' or 'off' string values.+ *+ * @param name human-readable name of this sensor+ * @param sensorID controller unique identifier+ * @param cache reference to the device state cache this sensor is associated with+ * @param producer the protocol handler that backs this sensor either with a read command+ * or event listener implementation+ * @param commandID controller unique identifier of related command+ */+ public SwitchSensor(String name, int sensorID, StatusCache cache, EventProducerCommand producer, int commandID) {+ this(name, sensorID, cache, producer, commandID, createSwitchStates());+ }++ /**+ * 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.+ *+ * The sensor implementation will return 'on or 'off' string values.+ *+ * @param name human-readable name of this sensor+ * @param sensorID controller unique identifier+ * @param cache reference to the device state cache this sensor is associated with+ * @param producer the protocol handler that backs this sensor either with a read command+ * or event listener implementation+ * @param commandID controller unique identifier of related command+ * @param states state string mappings for the default 'on' and 'off' values+ */+ public SwitchSensor(String name, int sensorID, StatusCache cache, EventProducerCommand producer, int commandID, DistinctStates states) {+ super(name, sensorID, cache, producer, commandID, states, false);+ }++ /**+ * 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.+ *+ * 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(+ getSensorID(), getName(), value, SwitchEvent.State.valueOf(Strings.toUpperCase(originalValue.trim()))+ );+ } catch (IllegalArgumentException e) {+ if (!isUnknownSensorValue(originalValue)) {+ LOG.log(+ Level.WARNING,+ "Switch event value must be either 'on' or 'off', got ''{0}'' in {1}",+ new Object[]{originalValue, this}+ );+ }++ return new UnknownEvent(this);+ }+ }++ @Override+ public String toString() {+ return "SwitchSensor{" ++ ", sensorID=" + getSensorID() ++ ", commandID=" + getCommandID()+ + "}";+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/rules/RuleEngine.java b/controller/src/main/java/org/openremote/controller/rules/RuleEngine.javanew file mode 100644index 000000000..f7acbd383--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/rules/RuleEngine.java@@ -0,0 +1,278 @@+/*+ * OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2016, 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.rules;++import org.drools.core.builder.conf.impl.DecisionTableConfigurationImpl;+import org.kie.api.KieBase;+import org.kie.api.KieServices;+import org.kie.api.builder.KieBuilder;+import org.kie.api.builder.KieFileSystem;+import org.kie.api.builder.KieModule;+import org.kie.api.builder.Message;+import org.kie.api.builder.model.KieBaseModel;+import org.kie.api.builder.model.KieModuleModel;+import org.kie.api.builder.model.KieSessionModel;+import org.kie.api.conf.EqualityBehaviorOption;+import org.kie.api.io.Resource;+import org.kie.api.io.ResourceConfiguration;+import org.kie.api.io.ResourceType;+import org.kie.api.runtime.KieContainer;+import org.kie.api.runtime.KieSession;+import org.kie.api.runtime.KieSessionConfiguration;+import org.kie.api.runtime.conf.TimedRuleExectionOption;+import org.kie.api.runtime.rule.FactHandle;+import org.kie.internal.builder.DecisionTableConfiguration;+import org.kie.internal.builder.DecisionTableInputType;+import org.kie.internal.builder.KnowledgeBuilder;+import org.kie.internal.builder.KnowledgeBuilderFactory;+import org.kie.internal.io.ResourceTypeImpl;+import org.openremote.controller.event.CommandFacade;+import org.openremote.controller.event.Event;+import org.openremote.controller.event.EventContext;+import org.openremote.controller.event.EventProcessor;+import org.openremote.controller.statuscache.LevelFacade;+import org.openremote.controller.statuscache.RangeFacade;+import org.openremote.controller.statuscache.SwitchFacade;++import java.util.Collection;+import java.util.HashMap;+import java.util.Map;+import java.util.Properties;+import java.util.logging.Level;+import java.util.logging.Logger;+import java.util.stream.Stream;++public abstract class RuleEngine extends EventProcessor {++ private static final Logger LOG = Logger.getLogger(RuleEngine.class.getName());++ private KieBase kb;+ private KieSession knowledgeSession;+ private Map<Integer, FactHandle> eventSources = new HashMap<>();+ private long factCount;++ private SwitchFacade switchFacade;+ private LevelFacade levelFacade;+ private RangeFacade rangeFacade;++ @Override+ public String getName() {+ return "Drools Rule Engine";+ }++ @Override+ public void push(EventContext 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 evt = ctx.getEvent();++ switchFacade.pushEventContext(ctx);+ levelFacade.pushEventContext(ctx);+ rangeFacade.pushEventContext(ctx);++ try {+ long factNewCount;+ if (!knowledgeSession.getObjects().contains(evt)) {+ boolean debug = true;+ if (eventSources.keySet().contains(evt.getSourceID())) {+ try {+ knowledgeSession.delete(eventSources.get(evt.getSourceID()));+ } finally {+ // Doing this in the finally to make sure we don't keep a reference to a fact when we should not (ORCJAVA-407)+ eventSources.remove(evt.getSourceID());+ }+ debug = false;+ }++ FactHandle handle = knowledgeSession.insert(evt);+ eventSources.put(evt.getSourceID(), handle);++ if (debug) {+ LOG.fine("Inserted: " + evt);+ }+ factNewCount = knowledgeSession.getFactCount();+ LOG.fine("Fact count: " + factNewCount);+ if (factNewCount != factCount) {+ LOG.fine("Fact count changed from " + factCount + " to " + factNewCount + " on '" + evt.getSource() + "'");+ }+ factCount = factNewCount;+ }++ knowledgeSession.fireAllRules();++ factNewCount = knowledgeSession.getFactCount();+ if (factNewCount >= 1000) // look for runaway insertion of facts+ if (factNewCount != factCount) {+ LOG.fine("Fact count changed from " + factCount + " to " + factNewCount + " on '" + evt.getSource() + "'");+ }+ factCount = factNewCount;+ } 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 init() throws Exception {+ }++ @Override+ public void start(CommandFacade commandFacade) throws Exception {+ KieServices kieServices = KieServices.Factory.get();+ KieModuleModel kieModuleModel = kieServices.newKieModuleModel();++ KieBaseModel kieBaseModel = kieModuleModel.newKieBaseModel("OpenRemoteKBase")+ .setDefault(true)+ .setEqualsBehavior(EqualityBehaviorOption.EQUALITY);+ KieSessionModel kieSessionModel = kieBaseModel.newKieSessionModel("OpenRemoteKSession")+ .setDefault(true)+ .setType(KieSessionModel.KieSessionType.STATEFUL);++ KieFileSystem kfs = kieServices.newKieFileSystem();+ kfs.writeKModuleXML(kieModuleModel.toXML());++ addResources(kieServices, kfs);++ KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());++ kb = kieContainer.getKieBase();++ KieSessionConfiguration kieSessionConfiguration = kieServices.newKieSessionConfiguration();+ // Use this option to ensure timer rules are fired even in passive mode (triggered by fireAllRules.+ // This ensures compatibility with the behaviour of previous controller using drools 5.1+ kieSessionConfiguration.setOption(TimedRuleExectionOption.YES);+ knowledgeSession = kb.newKieSession(kieSessionConfiguration, null);++ switchFacade = new SwitchFacade();+ rangeFacade = new RangeFacade();+ levelFacade = new LevelFacade();++ try {+ knowledgeSession.setGlobal("execute", commandFacade);+ } catch (Throwable t) {+ // TODO So, we never see any problems?+ }++ try {+ knowledgeSession.setGlobal("switches", switchFacade);+ } catch (Throwable t) {+ }++ try {+ knowledgeSession.setGlobal("ranges", rangeFacade);+ } catch (Throwable t) {+ }++ try {+ knowledgeSession.setGlobal("levels", levelFacade);+ } catch (Throwable t) {+ }++ try {+ RuleExecutionLogger ruleExecutionLogger = new RuleExecutionLogger();+ knowledgeSession.addEventListener(ruleExecutionLogger);+ } catch (Throwable t) {+ LOG.fine("Exception in addEventListener");+ }++ LOG.fine("Rule engine started");++ knowledgeSession.fireAllRules();+ }++ @Override+ public void stop() {+ LOG.fine("Stopping RuleEngine");+ if (knowledgeSession != null) {+ knowledgeSession.dispose();+ LOG.fine("Knowledge session disposed");+ }+ eventSources.clear();++ // We're disposing of the knowledge base, don't keep references to any facts (ORCJAVA-407)+ eventSources.clear();++ kb = null;+ }++ 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);+ }+ }++ 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);+ }+ } 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);++ @Override+ public String toString() {+ return "RuleEngine{" ++ "factCount=" + factCount ++ "}";+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/rules/RuleExecutionLogger.java b/controller/src/main/java/org/openremote/controller/rules/RuleExecutionLogger.javanew file mode 100644index 000000000..a83b6b791--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/rules/RuleExecutionLogger.java@@ -0,0 +1,132 @@+package org.openremote.controller.rules;++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 java.util.List;+import java.util.Map;+import java.util.logging.Logger;++/**+ * This class logs Drools rule execution. It is intended to assist the user in debugging Drools behavior.+ */+public class RuleExecutionLogger extends DefaultAgendaEventListener {++ private static final Logger LOG = Logger.getLogger(RuleExecutionLogger.class.getName());++ public static Logger getLOG() {+ return LOG;+ }++ @Override+ public void beforeMatchFired(BeforeMatchFiredEvent event) {+ final Rule rule = event.getMatch().getRule();+ String ruleName = rule.getName();++ if (ruleName.startsWith("--")) {+ return;+ }++ if (ruleName.startsWith("-")) {+ LOG.fine("Rule: " + ruleName + ": SKIPPED LOGGER");+ return;+ }++ String rulePackage = rule.getPackageName();+ ruleName = "\"" + ruleName + "\" // (package " + rulePackage + ")";++ Match matchEvent = event.getMatch();+ List<String> declarationIDs = matchEvent.getDeclarationIds();+ List<Object> antecedents = matchEvent.getObjects();++ String declarationLog = "";+ for (String declarationID : declarationIDs) {+ Object declarationValue = matchEvent.getDeclarationValue(declarationID);+ String declarationValueString = this.declarationValueToString(declarationValue);+ if (declarationValue instanceof Sensor || declarationValue instanceof Event) {+ 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);+ }+ }++ String objectLog = "";+ for (Object antecedent : antecedents) {+ String theClass = antecedent.getClass().getSimpleName();+ String theValue = this.antecedentValueToString(antecedent);+ objectLog = String.format("%s\t\tClass: \"%s\"\n\t\tFields: \n\t\t\t%s\n", objectLog, theClass, theValue);+ }++ LOG.fine(String.format("rule %s\n" ++ "\tDeclarations \n%s" ++ "\tLHS objects(antecedents)\n%s", ruleName, declarationLog, objectLog));+ }++ /**+ * This method converts a declarationValue into a string.+ * The need for this method would be obviated if all our facts descended from+ * a Fact class with a method to return the most salient value of a fact.+ *+ * @param antecedent - An object referenced by a drools LHS+ */+ private String antecedentValueToString(Object antecedent) {+ String theValue = null;+ if (antecedent != null) {+ theValue = antecedent.toString();+ }++ if (antecedent instanceof Sensor) //may be unnecessary if we never have raw sensor objects in WM+ {+ Sensor theSensor = (Sensor) antecedent;+ String sensorName = theSensor.getName();+ theValue = String.format("Sensor: %s\n", sensorName);++ theValue = String.format("%s\t\tSensor Properties\n", theValue);+ Map<String, String> sensorValues = theSensor.getProperties();++ for (Map.Entry<String, String> entry : sensorValues.entrySet()) {+ String entryName = entry.getKey();+ String entryValue = entry.getValue();+ 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);+ }++ return theValue;+ }++ /**+ * This method converts a declarationValue into a string.+ * The need for this method would be obviated if all our facts descended from+ * a Fact class with a method to return the unique identifier as a string.+ *+ * @param declarationValue - The object associated with a drools LHS declaration+ */+ private String declarationValueToString(Object declarationValue) {+ String convertedDeclarationValue = null;+ if (declarationValue != null) {+ convertedDeclarationValue = declarationValue.toString();+ }++ if (declarationValue instanceof Sensor) //may be unnecessary if we never have raw sensor objects in WM+ {+ convertedDeclarationValue = ((Sensor) declarationValue).getName();+ }+ if (declarationValue instanceof Event) {+ String sensorName = ((Event) declarationValue).getSource();+ String sensorValue = ((Event) declarationValue).getValue().toString();+ convertedDeclarationValue = String.format("Sensor Name: \"%s\"\n\t\t\tSensor Value: \"%s\"", sensorName, sensorValue);+ }++ return convertedDeclarationValue;+ }+}diff --git a/controller/src/main/java/org/openremote/controller/statuscache/ChangedStatusRecord.java b/controller/src/main/java/org/openremote/controller/statuscache/ChangedStatusRecord.javanew file mode 100644index 000000000..3ce47702a--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/statuscache/ChangedStatusRecord.java@@ -0,0 +1,73 @@+package org.openremote.controller.statuscache;++import java.util.HashSet;+import java.util.Set;+import java.util.TreeSet;++/**+ * A changed status record.+ * This Record is used to record the skipped changed statuses and waited changed statuses .+ */+public class ChangedStatusRecord {++ /**+ * A logical identity of panel+sensorIDs+ */+ private String key;++ /**+ * The ids a polling request contains+ */+ private Set<Integer> pollingSensorIDs = new TreeSet<Integer>();++ /**+ * The ids whose status had changed in the statusChangedSensorIDs+ */+ private Set<Integer> statusChangedSensorIDs = new HashSet<Integer>(3);+++ public ChangedStatusRecord(String key, Set<Integer> pollingSensorIDs) {+ this.key = key;+ this.pollingSensorIDs = pollingSensorIDs;+ }+++ public String getRecordKey() {+ return key;+ }++ public Set<Integer> getPollingSensorIDs() {+ return pollingSensorIDs;+ }+++ public Set<Integer> getStatusChangedSensorIDs() {+ return statusChangedSensorIDs;+ }++ public void setStatusChangedSensorIDs(Set<Integer> statusChangedSensorIDs) {+ this.statusChangedSensorIDs = statusChangedSensorIDs;+ }+++ @Override+ public boolean equals(Object obj) {+ if (obj == null || !(obj instanceof ChangedStatusRecord)) {+ return false;+ }+ ChangedStatusRecord timeoutRecord = (ChangedStatusRecord) obj;+ return timeoutRecord.getRecordKey().equals(getRecordKey());+ }++ @Override+ public int hashCode() {+ return key.hashCode();+ }++ @Override+ public String toString() {+ return "ChangedStatusRecord:" + key ++ " sensorID:" + this.pollingSensorIDs.toString() ++ " statusChangedSensorID:" + this.statusChangedSensorIDs;+ }+}diff --git a/controller/src/main/java/org/openremote/controller/statuscache/ChangedStatusTable.java b/controller/src/main/java/org/openremote/controller/statuscache/ChangedStatusTable.javanew file mode 100644index 000000000..871ccaeff--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/statuscache/ChangedStatusTable.java@@ -0,0 +1,74 @@+package org.openremote.controller.statuscache;++import java.util.HashMap;+import java.util.HashSet;+import java.util.Map;++/**+ * Use wait, notify, synchronize mechanism to do polling.+ *+ * This table is used to record the skipped changed statuses and waited changed statuses .+ *+ * <b>Use Case1:</b> During the process of iPhone refreshing the polling connection or+ * dealing with the response of changed state, a later (very soon, before iPhone reestablishes the next polling,+ * although it's kind of probability stuff) change won't be detected by iPhone , in other word, this polling request has left+ * the changed status. the result is when iPhone comes back to continue polling, it+ * knows nothing about what has happened just now, and iPhone will keep the old view and waiting for the next change+ * which is not synchronous any more.+ *+ * <b>Use Case2:</b>If no statuses changed, polling request will <b>WAIT</b><br /> the Corresponded ChangedStatusRecord until<br />+ * the waited polling sensor ids' statuses changed. So, the polling request will be notified and get the change statuses.<br />+ */+public class ChangedStatusTable {++ private Map<String, ChangedStatusRecord> recordList;++ public ChangedStatusTable() {+ recordList = new HashMap<>();+ }++ /**+ * Insert a changed status record.+ */+ public synchronized void insert(ChangedStatusRecord record) {+ recordList.put(record.getRecordKey(), record);+ }++ /**+ * Query changed status record by deviceID and pollingSensorIDs(pollingSensorIDs is order-insensitive).+ */+ public synchronized ChangedStatusRecord query(String key) {+ return recordList.get(key);+ }++ public void updateStatusChangedIDs(Integer statusChangedSensorID) {+ for (ChangedStatusRecord record : recordList.values()) {+ // TODO That's some bullshit synchronization+ synchronized (record) {+ if (record.getPollingSensorIDs().contains(statusChangedSensorID)) {+ record.getStatusChangedSensorIDs().add(statusChangedSensorID);+ record.notifyAll();+ }+ }+ }+ }++ /**+ * Reset changed status of panel in {@link ChangedStatusTable}.+ */+ @Deprecated+ public synchronized void resetChangedStatusIDs(String key) {+ ChangedStatusRecord skippedStatusRecord = this.query(key);++ if (skippedStatusRecord != null) {+ skippedStatusRecord.setStatusChangedSensorIDs(new HashSet<Integer>());+ }+ }++ /**+ * Clear all records+ */+ public void clearAllRecords() {+ this.recordList.clear();+ }+}diff --git a/controller/src/main/java/org/openremote/controller/statuscache/LevelFacade.java b/controller/src/main/java/org/openremote/controller/statuscache/LevelFacade.javanew file mode 100644index 000000000..a19dc465f--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/statuscache/LevelFacade.java@@ -0,0 +1,39 @@+package org.openremote.controller.statuscache;++import org.openremote.controller.event.SingleValueEventFacade;+import org.openremote.controller.event.LevelEvent;++public class LevelFacade extends SingleValueEventFacade<LevelFacade.LevelAdapter, LevelEvent> {++ @Override+ protected LevelEvent createDefaultEvent(int sourceID, String sourceName) {+ return new LevelEvent(sourceID, sourceName, 0);+ }++ @Override+ protected LevelAdapter createAdapter(LevelEvent event) {+ return new LevelAdapter(event);+ }++ public class LevelAdapter {++ private LevelEvent levelEvent;++ private LevelAdapter(LevelEvent levelEvent) {+ this.levelEvent = levelEvent;+ }++ public void value(int value) {+ if (value < 0) {+ value = 0;+ } else if (value > 100) {+ value = 100;+ }++ LevelEvent newLevelEventEvent = levelEvent.clone(value);++ dispatchEvent(newLevelEventEvent);+ }+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/statuscache/RangeFacade.java b/controller/src/main/java/org/openremote/controller/statuscache/RangeFacade.javanew file mode 100644index 000000000..459dd446d--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/statuscache/RangeFacade.java@@ -0,0 +1,44 @@+package org.openremote.controller.statuscache;++import org.openremote.controller.event.SingleValueEventFacade;+import org.openremote.controller.event.RangeEvent;++import java.util.logging.Logger;++public class RangeFacade extends SingleValueEventFacade<RangeFacade.RangeAdapter, RangeEvent> {++ private static final Logger LOG = Logger.getLogger(RangeFacade.class.getName());++ @Override+ protected RangeEvent createDefaultEvent(int sourceID, String sourceName) {+ return new RangeEvent(sourceID, sourceName, 0, Integer.MIN_VALUE, Integer.MAX_VALUE);+ }++ @Override+ protected RangeAdapter createAdapter(RangeEvent event) {+ return new RangeAdapter(event);+ }++ public class RangeAdapter {++ private RangeEvent rangeEvent;++ private RangeAdapter(RangeEvent event) {+ this.rangeEvent = event;+ }++ public void value(int value) {+ if (value < rangeEvent.getMinValue()) {+ value = rangeEvent.getMinValue();+ } else if (value > rangeEvent.getMaxValue()) {+ value = rangeEvent.getMaxValue();+ }++ RangeEvent newRangeEventEvent = rangeEvent.clone(value);++ LOG.fine("Dispatching event (original value was: '" + value + "'): " + newRangeEventEvent);+ dispatchEvent(newRangeEventEvent);+ }+ }+}+diff --git a/controller/src/main/java/org/openremote/controller/statuscache/StatusCache.java b/controller/src/main/java/org/openremote/controller/statuscache/StatusCache.javanew file mode 100644index 000000000..9f905b757--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/statuscache/StatusCache.java@@ -0,0 +1,282 @@+package org.openremote.controller.statuscache;++import org.openremote.controller.event.Event;+import org.openremote.controller.event.EventContext;+import org.openremote.controller.event.EventProcessorChain;+import org.openremote.controller.model.Sensor;++import java.util.HashMap;+import java.util.Iterator;+import java.util.Map;+import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;+import java.util.logging.Level;+import java.util.logging.Logger;++public class StatusCache {++ private static final Logger LOG = Logger.getLogger(StatusCache.class.getName());++ /**+ * Maintains a map of sensor ids to their values in cache.+ */+ final protected SensorMap sensorMap;++ /**+ * TODO : Map of sensor IDs to actual sensor instances.+ */+ final protected Map<Integer, Sensor> sensors = new ConcurrentHashMap<>();++ /**+ * A chain of event processors that incoming events (values) are forced through before+ * their values are stored in the cache.+ *+ * Event processors may modify the existing values, discard events entirely or spawn+ * multiple other events that are included in the state cache.+ */+ final protected EventProcessorChain eventProcessorChain;++ /**+ * Used to indicate if the state cache is in the middle of a shut down process -- this+ * flag can be used by methods to fail-fast in such cases.+ */+ private volatile Boolean isShutdownInProcess = false;++ public StatusCache(ChangedStatusTable cst, EventProcessorChain epc) {+ this.eventProcessorChain = epc;+ this.sensorMap = new SensorMap(cst);+ }++ public void start() {+ eventProcessorChain.start();+ }++ /**+ * Register a sensor with this cache instance. The registered sensor will participate in+ * cache's lifecycle.+ *+ * @param sensor sensor to register+ */+ public synchronized void registerSensor(Sensor sensor) {+ // TODO :+ // push thread synchronization down to sensorMap.init() once+ // Sensor references are handled there+ // [JPL]++ if (isShutdownInProcess) {+ return;+ }++ Sensor previous = sensors.put(sensor.getSensorID(), sensor);++ // Use a specific log category just to log the creation of sensor objects+ // in this method (happens at startup or soft restart)...++ if (previous != null) {+ throw new IllegalArgumentException(+ "Duplicate registration of sensor ID '" + sensor.getSensorID() + "', already registered as sensor named '" + previous.getName()+ );+ }++ sensorMap.init(sensor);+ LOG.info("Registered sensor: " + sensor);+ }++ /**+ * Returns a sensor instance associated with the given ID.+ *+ * @param id sensor ID+ * @return sensor instance+ */+ public Sensor getSensor(int id) {+ return sensors.get(id);+ }++ /**+ * Performs a state cache cleanup at shut down. This method is synchronized, preventing+ * concurrent thread access to shutdown steps.+ *+ * Part of the shutdown of state cache:+ * <ul>+ * <li>registered sensors are stopped</li>+ * <li>the in-memory states are cleared</li>+ * <li>registered sensors are unregistered</li>+ * </ul>+ *+ * This allows more orderly cleanup of the resources associated with this state cache --+ * namely the sensor threads are allowed to cleanup and stop properly.+ *+ * Once the shutdown is completed, this cache instance can be discarded. There's no corresponding+ * start operation to allow reuse of this object.+ */+ public synchronized void shutdown() {+ try {+ isShutdownInProcess = true;+ eventProcessorChain.stop();+ stopSensors();+ sensorMap.clear();+ sensors.clear();+ } finally {+ isShutdownInProcess = false;+ }+ }++ /**+ * Updates an incoming event value into cache.+ * This method is currently synchronized to restrict concurrency -- events are processed+ * and updated one-by-one. The implications of concurrent event processing through the processors+ * and concurrent updates must be evaluated. See ORCJAVA-205.+ *+ * @param event the event to process -- the actual value stored in this cache will depend+ * on the modifications made by event processors associated with this cache+ */+ public synchronized void update(Event event) {+ LOG.fine("==> Updating status for event: " + event);+ if (isShutdownInProcess) {+ LOG.fine("<== Status cache is shutting down. Ignoring update from: " + event.getSource());+ return;+ }++ // push incoming event through processing chain -- keep the last returned instance including+ // modifications if any...++ EventContext ctx = new EventContext(this, event);++ eventProcessorChain.push(ctx);++ // Update the final value...++ if (!ctx.hasTerminated()) {+ sensorMap.update(ctx.getEvent());+ LOG.fine("<== Updating status complete for event: " + event);+ } else {+ LOG.fine("<== Updating status complete, event context terminated, no update was made to status cache for event: " + ctx.getEvent());+ }+ }++ public Map<Integer, String> queryStatus(Set<Integer> sensorIDs) {+ if (sensorIDs == null || sensorIDs.size() == 0) {+ return null; // TODO : return an empty collection instead+ }+ LOG.fine("Query status for sensor IDs: " + sensorIDs);+ Map<Integer, String> statuses = new HashMap<Integer, String>();+ for (Integer sensorId : sensorIDs) {+ statuses.put(sensorId, queryStatus(sensorId));+ }+ LOG.fine("Returning sensor status map (ID, Value): " + statuses);+ return statuses;+ }++ /**+ * Returns the current in-memory state of the given sensor ID.+ *+ * @param sensorID requested sensor ID+ * @return current cache-stored value for the given sensor ID+ */+ public String queryStatus(Integer sensorID) {+ if (!sensorMap.hasExistingState(sensorID)) {+ LOG.info("Requested sensor id '" + sensorID + "' was not found. Defaulting to: " + Sensor.UNKNOWN_STATUS);+ return Sensor.UNKNOWN_STATUS;+ }+ return sensorMap.getCurrentState(sensorID).serialize();+ }++ public Event queryStatus(String name) throws Exception {+ return sensorMap.get(name);+ }++ public Iterator<Event> getStateSnapshot() {+ return sensorMap.getSnapshot();+ }++ public Integer sensorIDFromName(String sensorName) {+ return sensorMap.getSensorID(sensorName);+ }++ private void stopSensors() {+ for (Sensor sensor : sensors.values()) {+ LOG.info("Stopping sensor: " + sensor);++ try {+ sensor.stop();+ } catch (Throwable t) {+ LOG.log(Level.SEVERE, "Failed to stop sensor: " + sensor, t);+ }+ }+ }++ private class SensorMap {++ private Map<String, Integer> nameIdIndex = new ConcurrentHashMap<>();+ private Map<Integer, Event> currentState = new ConcurrentHashMap<>();+ private ChangedStatusTable deviceStatusChanges;++ private SensorMap(ChangedStatusTable cst) {+ this.deviceStatusChanges = cst;+ }++ private void init(Sensor sensor) {+ nameIdIndex.put(sensor.getName(), sensor.getSensorID());+ currentState.put(sensor.getSensorID(), new Sensor.UnknownEvent(sensor));+ }++ private Iterator<Event> getSnapshot() {+ return currentState.values().iterator();+ }++ private void clear() {+ clearDeviceStatusChanges();++ nameIdIndex.clear();+ currentState.clear();+ }++ private void clearDeviceStatusChanges() {+ for (Sensor sensor : sensors.values()) {+ // Just wake up all the records, acturelly, the status didn't change.+ deviceStatusChanges.updateStatusChangedIDs(sensor.getSensorID());+ }+ deviceStatusChanges.clearAllRecords();+ }+++ private boolean hasExistingState(int id) {+ return currentState.get(id) != null;+ }++ private Event getCurrentState(int id) {+ return currentState.get(id);+ }++ private Event get(String name) throws Exception {+ if (!nameIdIndex.keySet().contains(name)) {+ throw new Exception("No sensors with name: " + name);+ }+ int id = nameIdIndex.get(name);+ return currentState.get(id);+ }++ private Integer getSensorID(String sensorName) {+ return nameIdIndex.get(sensorName);+ }++ private void update(Event event) {+ int id = event.getSourceID();++ if (currentState.get(id) == null) {+ LOG.fine("Starting value cache for sensor: " + event.getSource());+ currentState.put(id, event);+ } else {+ Event previousState = currentState.get(id);+ if (previousState.isEqual(event)) {+ return;+ }+ LOG.fine("Updating value cache for sensor: " + event.getSource());+ currentState.put(id, event);+ }++ deviceStatusChanges.updateStatusChangedIDs(event.getSourceID());+ LOG.fine("Marking changed sensor: " + event.getSource());+ }+ }+}diff --git a/controller/src/main/java/org/openremote/controller/statuscache/SwitchFacade.java b/controller/src/main/java/org/openremote/controller/statuscache/SwitchFacade.javanew file mode 100644index 000000000..55a8e4c7a--- /dev/null+++ b/controller/src/main/java/org/openremote/controller/statuscache/SwitchFacade.java@@ -0,0 +1,62 @@+package org.openremote.controller.statuscache;++import org.openremote.controller.event.Event;+import org.openremote.controller.event.EventFacade;+import org.openremote.controller.model.Sensor;+import org.openremote.controller.event.SwitchEvent;++public class SwitchFacade extends EventFacade {++ public SwitchAdapter name(String name) throws Exception {+ Event evt = eventContext.getStatusCache().queryStatus(name);++ if (evt instanceof Sensor.UnknownEvent) {+ evt = new SwitchEvent(+ evt.getSourceID(),+ evt.getSource(),+ SwitchEvent.State.OFF.serialize(),+ SwitchEvent.State.OFF+ );+ }++ if (evt instanceof SwitchEvent) {+ return new SwitchAdapter((SwitchEvent) evt);+ } else {+ throw new Exception("Sensor is not switch type: " + name);+ }+ }++ public class SwitchAdapter {++ private SwitchEvent switchEvent;++ private SwitchAdapter(SwitchEvent switchEvent) {+ this.switchEvent = switchEvent;+ }++ public void off() {+ off(null);+ }++ public void off(String eventValue) {+ if (eventValue == null) {+ eventValue = SwitchEvent.State.OFF.serialize();+ }+ SwitchEvent newSwitchEvent = switchEvent.clone(eventValue, SwitchEvent.State.OFF);+ dispatchEvent(newSwitchEvent);+ }++ public void on() {+ on(null);+ }++ public void on(String eventValue) {+ if (eventValue == null) {+ eventValue = SwitchEvent.State.ON.serialize();+ }+ SwitchEvent newSwitchEvent = switchEvent.clone(eventValue, SwitchEvent.State.ON);+ dispatchEvent(newSwitchEvent);+ }+ }+}+diff --git a/controller/src/main/resources/logging.properties b/controller/src/main/resources/logging.propertiesnew file mode 100644index 000000000..00aa58ff9--- /dev/null+++ b/controller/src/main/resources/logging.properties@@ -0,0 +1,28 @@+# This configuration file is used in the Manager's Docker image, it's the default+# configuration we ship to users.++handlers=java.util.logging.ConsoleHandler++java.util.logging.ConsoleHandler.formatter=org.openremote.container.util.LogFormatter+java.util.logging.ConsoleHandler.level=FINEST++.level=INFO++org.openremote.level=FINEST+org.openremote.container.message.level=INFO++# Low-level debugging+org.hibernate.level=WARNING+com.zaxxer.hikari.level=WARNING+javax.management.level=WARNING+org.xnio.level=WARNING+org.apache.camel.management.level=WARNING+org.apache.camel.impl.converter.DefaultTypeConverter.level=WARNING++# Set this to FINEST to log outgoing HTTP traffic+org.apache.http.level=WARNING+org.apache.http.impl.conn.DefaultClientConnection.level=WARNING++# Set this to FINEST to log SQL execution+org.hibernate.SQL.level=FINEST+org.hibernate.type.descriptor.sql.BasicBinder.level=FINESTdiff --git a/controller/src/test/groovy/org/openremote/test/rules/Bak.java b/controller/src/test/groovy/org/openremote/test/rules/Bak.javanew file mode 100644index 000000000..318c60c94--- /dev/null+++ b/controller/src/test/groovy/org/openremote/test/rules/Bak.java@@ -0,0 +1,1577 @@+package org.openremote.test.rules;++public class Bak {+++//+// /**+// * Test a mixed deployment of multiple rules, some from drools rule language,+// * others from CSV decision table.+// *+// * @throws Exception if test fails+// */+// @Test+// public void testMixedDRLCSVDeployment() throws Exception {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/mixed/").toString();+//+// config.setResourcePath(newResourcePath);+//+// RuleEngine rules = new RuleEngine();+// EventGrab grab = new EventGrab();+//+// List<EventProcessor> processors = new ArrayList<EventProcessor>();+// processors.add(rules);+// processors.add(grab);+//+// CommandCounter commandCounter = new CommandCounter();+//+// StatusCache cache = createCache(processors, "commandCounter", commandCounter, "count");+//+//+// // should not trigger commands...+//+// Switch sw = new Switch(1, "test", "on", Switch.State.ON);+//+// cache.update(sw);+// Event evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("test"));+// Assert.assertTrue(evt.getSourceID() == 1);+// Assert.assertTrue(evt.getValue().equals("on"));+// Assert.assertTrue(evt.serialize().equals("on"));+// Assert.assertTrue(evt instanceof Switch);+// Assert.assertTrue(evt.equals(sw));+// Assert.assertTrue(evt == sw);+//+// Switch swevt = (Switch) evt;+//+// Assert.assertTrue(swevt.getState().equals(Switch.State.ON));+//+// Assert.assertTrue(grab.count == 1);+// Assert.assertTrue(commandCounter.count == 0);+//+//+// // Should get its value modified by EventMod.drl above range max...+//+// Level level = new Level(123, "test level mod", 30);+//+// cache.registerSensor(new LevelSensor("test level mod", 123, cache, new TestCommand(), 1));+//+// cache.update(level);+//+// Thread.sleep(2000);+//+// evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("test level mod"));+//+// Assert.assertTrue(+// "Was expecting 100, got " + evt.getValue(),+// evt.getValue().equals(100)+// );+//+// Assert.assertTrue(evt.serialize().equals("100"));+// Assert.assertTrue(evt instanceof Level);+// Assert.assertTrue(!evt.equals(level));+// Assert.assertTrue(evt != level);+//+// Level l1 = (Level) evt;+// Assert.assertTrue(l1.getValue() == 100);+//+// Assert.assertTrue(grab.count == 2);+//+//+// // should execute command with param 55...+//+// level = new Level(555, "test level mod 555", 101);+//+// cache.update(level);+// evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("test level mod 555"));+// Assert.assertTrue(evt.getSourceID() == 555);+// Assert.assertTrue(evt.getValue().equals(100));+// Assert.assertTrue(evt.serialize().equals("100"));+// Assert.assertTrue(evt instanceof Level);+// Assert.assertTrue(evt.equals(level));+// Assert.assertTrue(evt == level);+//+//+// Assert.assertTrue(commandCounter.count == 1);+// Assert.assertTrue(commandCounter.lastValue.equals("55"));+// Assert.assertTrue(grab.count == 3);+//+//+// // should execute command with param 6666...+//+// level = new Level(666, "test level mod 666", 1);+//+// cache.update(level);+// evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("test level mod 666"));+// Assert.assertTrue(evt.getSourceID() == 666);+// Assert.assertTrue(evt.getValue().equals(1));+// Assert.assertTrue(evt.serialize().equals("1"));+//+// Assert.assertTrue(commandCounter.count == 2);+// Assert.assertTrue(commandCounter.lastValue.equals("6666"));+// Assert.assertTrue(grab.count == 4);+//+//+// // should execute command with param -77+//+// level = new Level(777, "test level mod 777", 10);+//+// cache.update(level);+// evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("test level mod 777"));+// Assert.assertTrue(evt.getSourceID() == 777);+// Assert.assertTrue(evt.getValue().equals(10));+// Assert.assertTrue(evt.serialize().equals("10"));+//+// Assert.assertTrue(commandCounter.count == 3);+// Assert.assertTrue(commandCounter.lastValue.equals("-77"));+// Assert.assertTrue(grab.count == 5);+// }+//+//+// /**+// * Test rule engine initialization in case of a broken CSV file (should not+// * throw an exception that propagates through the event processor).+// *+// * @throws Exception if test fails+// */+// @Test+// public void testDecisionTableNoRuleSet() throws Exception {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/dtable-noruleset/").toString();+//+// config.setResourcePath(newResourcePath);+//+// RuleEngine rules = new RuleEngine();+// rules.init();+//+// rules.start(new LifeCycleEvent(null));+// }+//+//+// /**+// * Test rule engine initialization in case of a incorrectly defined decision table+// * (should not propagate exceptions through event processor implementation).+// *+// * @throws Exception if test fails+// */+// @Test+// public void testDecisionTableIncorrectDefinition() throws Exception {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/dtable-incorrect-definition/").toString();+//+// config.setResourcePath(newResourcePath);+//+// RuleEngine rules = new RuleEngine();+// rules.init();+//+// rules.start(new LifeCycleEvent(null));+// }+//+//+// /**+// * Test basic decision table deployment and operation to modify the processed events.+// *+// * @throws Exception if test fails+// */+// @Test+// public void testDecisionTable() throws Exception {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/dtable/").toString();+//+// config.setResourcePath(newResourcePath);+//+// RuleEngine rules = new RuleEngine();+// rules.init();+// EventGrab grab = new EventGrab();+//+// List<EventProcessor> processors = new ArrayList<EventProcessor>();+// processors.add(rules);+// processors.add(grab);+//+// CommandCounter commandCounter = new CommandCounter();+// StatusCache cache = createCache(processors, "commandCounter", commandCounter, "count");+//+//+// Switch sw = new Switch(555, "test555", "on", Switch.State.ON);+//+// cache.update(sw);+//+// Assert.assertTrue(+// "Expected 'triggered', got '" + commandCounter.lastValue + "'",+// commandCounter.lastValue.equals("triggered")+// );+//+// sw = new Switch(666, "test666", "on", Switch.State.ON);+//+// cache.update(sw);+//+// Assert.assertTrue(commandCounter.lastValue.equals("started"));+//+// sw = new Switch(777, "test777", "on", Switch.State.ON);+//+// cache.update(sw);+//+// Assert.assertTrue(commandCounter.lastValue.equals("good"));+// }+//+//+// /**+// * TODO+// *+// * @throws Exception if test fails+// */+// @Test+// public void vacationTest() throws Exception {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/holiday-example/").toString();+//+// config.setResourcePath(newResourcePath);+//+// RuleEngine rules = new RuleEngine();+// EventGrab grab = new EventGrab();+//+// List<EventProcessor> processors = new ArrayList<EventProcessor>();+// processors.add(rules);+// processors.add(grab);+//+// CommandCounter tempCommands = new CommandCounter();+//+// StatusCache cache = createCache(processors, "commandCounter", tempCommands, "temp");+//+//+// Assert.assertTrue(grab.count == 0);+//+//+// {+// CustomState state = new CustomState(20, "time of day", "day");+//+// cache.update(state);+//+// Event evt = grab.event;+//+// Assert.assertTrue(grab.count == 1);+//+// Assert.assertTrue(evt.getSourceID() == 20);+// Assert.assertTrue(evt.getSource().equals("time of day"));+// Assert.assertTrue(evt.getValue().equals("day"));+// Assert.assertTrue(evt instanceof CustomState);+// Assert.assertTrue(evt.equals(state));+// Assert.assertTrue(evt == state);+//+//+// Assert.assertTrue(tempCommands.count == 1);+//+// Assert.assertTrue(+// "Expected last command value '21', got '" + tempCommands.lastValue + "'",+// tempCommands.lastValue.equals("21")+// );+// }+//+//+// {+// CustomState state = new CustomState(20, "time of day", "night");+//+// cache.update(state);+//+// Event evt = grab.event;+//+// Assert.assertTrue(grab.count == 2);+//+// Assert.assertTrue(evt.getSourceID() == 20);+// Assert.assertTrue(evt.getSource().equals("time of day"));+// Assert.assertTrue(evt.getValue().equals("night"));+// Assert.assertTrue(evt instanceof CustomState);+// Assert.assertTrue(evt.equals(state));+// Assert.assertTrue(evt == state);+//+//+// Assert.assertTrue(tempCommands.count == 2);+//+// Assert.assertTrue(+// "Expected last command value '18', got '" + tempCommands.lastValue + "'",+// tempCommands.lastValue.equals("18")+// );+// }+//+//+// {+// Switch sw = new Switch(1, "vacation start", "on", Switch.State.ON);+//+// cache.update(sw);+//+// Event evt = grab.event;+//+// Assert.assertTrue(grab.count == 3);+//+// Assert.assertTrue(evt.getSourceID() == 1);+// Assert.assertTrue(evt.getSource().equals("vacation start"));+// Assert.assertTrue(evt instanceof Switch);+// Assert.assertTrue(evt.equals(sw));+// Assert.assertTrue(evt == sw);+//+// Assert.assertTrue(+// "Expected command count 3, got " + tempCommands.count,+// tempCommands.count == 3+// );+//+// Assert.assertTrue(+// "Expected last command value '15', got '" + tempCommands.lastValue + "'",+// tempCommands.lastValue.equals("15")+// );+//+// }+//+//+// {+// CustomState state = new CustomState(20, "time of day", "day");+//+// cache.update(state);+//+// Event evt = grab.event;+//+// Assert.assertTrue(grab.count == 4);+//+// Assert.assertTrue(evt.getSourceID() == 20);+// Assert.assertTrue(evt.getSource().equals("time of day"));+// Assert.assertTrue(evt.getValue().equals("day"));+// Assert.assertTrue(evt instanceof CustomState);+// Assert.assertTrue(evt.equals(state));+// Assert.assertTrue(evt == state);+//+//+// Assert.assertTrue(+// "Expected command count 4, got " + tempCommands.count,+// tempCommands.count == 4+// );+//+// Assert.assertTrue(+// "Expected last command value '15', got '" + tempCommands.lastValue + "'",+// tempCommands.lastValue.equals("15")+// );+// }+//+//+// {+// Switch sw = new Switch(1, "vacation end", Switch.State.OFF.serialize(), Switch.State.ON);+//+// cache.update(sw);+//+// Event evt = grab.event;+//+// Assert.assertTrue(grab.count == 5);+//+// Assert.assertTrue(evt.getSourceID() == 1);+// Assert.assertTrue(evt.getSource().equals("vacation end"));+// Assert.assertTrue(evt instanceof Switch);+// Assert.assertTrue(evt.equals(sw));+// Assert.assertTrue(evt == sw);+//+// Assert.assertTrue(+// "Expected command count 5, got " + tempCommands.count,+// tempCommands.count == 5+// );+//+// Assert.assertTrue(+// "Expected last command value '21', got '" + tempCommands.lastValue + "'",+// tempCommands.lastValue.equals("21")+// );+//+// }+//+// }+//+//+// /**+// * TODO+// *+// * @throws Exception if test fails+// */+// @Test+// public void testSwitchModifications() throws Exception {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/switch/").toString();+//+// config.setResourcePath(newResourcePath);+//+// RuleEngine rules = new RuleEngine();+// EventGrab grab = new EventGrab();+//+// List<EventProcessor> processors = new ArrayList<EventProcessor>();+// processors.add(rules);+// processors.add(grab);+//+// StatusCache cache = createCache(processors, "commandCounter", new CommandCounter(), "counter");+//+// // Just run through a single event to make sure no rules get triggered...+//+// Assert.assertTrue(grab.count == 0);+//+// Switch sw = new Switch(555, "switch555", "on", Switch.State.ON);+//+// cache.update(sw);+// Event evt = grab.event;+//+// Assert.assertTrue(grab.count == 1);+//+// Assert.assertTrue(evt.getSourceID() == 555);+// Assert.assertTrue(evt.getSource().equals("switch555"));+// Assert.assertTrue(evt instanceof Switch);+// Assert.assertTrue(evt.equals(sw));+// Assert.assertTrue(evt == sw);+//+// Switch sw1 = (Switch) evt;+//+// Assert.assertTrue(sw1.getValue().equals("on"));+// Assert.assertTrue(sw1.getState() == Switch.State.ON);+//+//+// Switch sw2 = new Switch(444, "switch444", "off", Switch.State.OFF);+// cache.registerSensor(new SwitchSensor("switch444", 444, cache, new TestCommand(), 1));+//+// cache.update(sw2);+//+// Thread.sleep(2000);+//+// evt = grab.event;+//+// Assert.assertTrue("Expected count 2, got " + grab.count, grab.count == 2);+//+//+// Assert.assertTrue(evt.getSourceID() == 444);+// Assert.assertTrue(evt.getSource().equals("switch444"));+// Assert.assertTrue(evt instanceof Switch);+// Assert.assertTrue(!evt.equals(sw2));+//+// Switch sw3 = (Switch) evt;+//+// Assert.assertTrue(+// "Expected 'Complete', got '" + sw3.getValue() + "'",+// sw3.getValue().equals("Complete")+// );+//+// Assert.assertTrue(sw3.getState() == Switch.State.ON);+// }+//+//+// /**+// * Basic Level event tests to check rule execution based on event equality (which includes+// * event source name and id and event's value. Repeated events from the same source and+// * with same value should not re-trigger rule execution (unless the event value has from the+// * source has changed in between).+// *+// * @throws Exception if test fails+// */+// @Test+// public void testLevelCommandExecution() throws Exception {+// StatusCache cache = null;+//+// try {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/level-command-execution/").toString();+//+// config.setResourcePath(newResourcePath);+//+//+// RuleEngine sre = new RuleEngine();+// EventGrab grab = new EventGrab();+//+// List<EventProcessor> processors = new ArrayList<EventProcessor>();+// processors.add(sre);+// processors.add(grab);+//+// CommandCounter commandCounter = new CommandCounter();+// cache = createCache(processors, "commandCounter", commandCounter, "counter");+//+//+// // Starting condition...+//+// Assert.assertTrue(commandCounter.count == 0);+//+//+// // should not trigger rule (command execution)...+//+// Level level1 = new Level(1, "level-test", 50);+//+// cache.update(level1);+//+// Assert.assertTrue(commandCounter.count == 0);+//+//+// Event evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("level-test"));+// Assert.assertTrue(evt.getSourceID() == 1);+// Assert.assertTrue(+// "Expected 50, got " + evt.getValue(),+// evt.getValue().equals(50)+// );+// Assert.assertTrue(evt.serialize().equals("50"));+// Assert.assertTrue(evt instanceof Level);+// Assert.assertTrue(evt.equals(level1));+// Assert.assertTrue(evt == level1);+//+// Level l1 = (Level) evt;+//+// Assert.assertTrue(l1.getValue() == 50);+//+//+// // should execute command due to above trigger level (>75)...+//+// Level level2 = new Level(1, "level-test", 80);+//+// cache.update(level2);+//+// Assert.assertTrue(commandCounter.count == 1);+//+// evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("level-test"));+// Assert.assertTrue(evt.getSourceID() == 1);+// Assert.assertTrue(+// "Expected 80, got " + evt.getValue(),+// evt.getValue().equals(80)+// );+// Assert.assertTrue(evt.serialize().equals("80"));+// Assert.assertTrue(evt instanceof Level);+// Assert.assertTrue(evt.equals(level2));+// Assert.assertTrue(evt == level2);+//+// Level l2 = (Level) evt;+//+// Assert.assertTrue(l2.getValue() == 80);+//+//+// // should execute command again...+//+// Level level3 = new Level(1, "level-test", 90);+//+// cache.update(level3);+//+// Assert.assertTrue(commandCounter.count == 2);+//+// evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("level-test"));+// Assert.assertTrue(evt.getSourceID() == 1);+// Assert.assertTrue(+// "Expected 90, got " + evt.getValue(),+// evt.getValue().equals(90)+// );+// Assert.assertTrue(evt.serialize().equals("90"));+// Assert.assertTrue(evt instanceof Level);+// Assert.assertTrue(evt.equals(level3));+// Assert.assertTrue(evt == level3);+//+// Level l3 = (Level) evt;+//+// Assert.assertTrue(l3.getValue() == 90);+//+//+// // should execute once more...+//+// Level level4 = new Level(1, "level-test", 100);+//+// cache.update(level4);+//+// Assert.assertTrue(commandCounter.count == 3);+//+// evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("level-test"));+// Assert.assertTrue(evt.getSourceID() == 1);+// Assert.assertTrue(+// "Expected 100, got " + evt.getValue(),+// evt.getValue().equals(100)+// );+// Assert.assertTrue(evt.serialize().equals("100"));+// Assert.assertTrue(evt instanceof Level);+// Assert.assertTrue(evt.equals(level4));+// Assert.assertTrue(evt == level4);+//+// Level l4 = (Level) evt;+//+// Assert.assertTrue(l4.getValue() == 100);+//+//+// // should not trigger...+//+// Level level5 = new Level(1, "level-test", 0);+//+// cache.update(level5);+//+// Assert.assertTrue(commandCounter.count == 3);+//+// evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("level-test"));+// Assert.assertTrue(evt.getSourceID() == 1);+// Assert.assertTrue(+// "Expected 0, got " + evt.getValue(),+// evt.getValue().equals(0)+// );+// Assert.assertTrue(evt.serialize().equals("0"));+// Assert.assertTrue(evt instanceof Level);+// Assert.assertTrue(evt.equals(level5));+// Assert.assertTrue(evt == level5);+//+// Level l5 = (Level) evt;+//+// Assert.assertTrue(l5.getValue() == 0);+//+//+// // should trigger again, repeating earlier value (but was zeroed in between)...+//+// Level level6 = new Level(1, "level-test", 100);+//+// cache.update(level6);+//+// Assert.assertTrue(commandCounter.count == 4);+//+// evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("level-test"));+// Assert.assertTrue(evt.getSourceID() == 1);+// Assert.assertTrue(+// "Expected 100, got " + evt.getValue(),+// evt.getValue().equals(100)+// );+// Assert.assertTrue(evt.serialize().equals("100"));+// Assert.assertTrue(evt instanceof Level);+// Assert.assertTrue(evt.equals(level6));+// Assert.assertTrue(evt == level6);+//+// Level l6 = (Level) evt;+//+// Assert.assertTrue(l6.getValue() == 100);+//+//+// // should NOT re-trigger due to equality rules...+//+// Level level7 = new Level(1, "level-test", 100);+//+// cache.update(level7);+//+// Assert.assertTrue(commandCounter.count == 4);+//+// evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("level-test"));+// Assert.assertTrue(evt.getSourceID() == 1);+// Assert.assertTrue(+// "Expected 100, got " + evt.getValue(),+// evt.getValue().equals(100)+// );+// Assert.assertTrue(evt.serialize().equals("100"));+// Assert.assertTrue(evt instanceof Level);+// Assert.assertTrue(evt.equals(level7));+// Assert.assertTrue(evt == level7);+//+// Level l7 = (Level) evt;+//+// Assert.assertTrue(l7.getValue() == 100);+// } finally {+// if (cache != null) {+// cache.shutdown();+// }+// }+// }+//+//+// /**+// * Tests command execution based on a schedule (1s interval schedule)+// *+// * @throws Exception if test fails+// */+// @Test+// public void testScheduledCommandExecution() throws Exception {+// StatusCache cache = null;+//+// try {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/scheduled-command-execution/").toString();+//+// config.setResourcePath(newResourcePath);+//+//+// RuleEngine sre = new RuleEngine();+// EventGrab grab = new EventGrab();+//+// List<EventProcessor> processors = new ArrayList<EventProcessor>();+// processors.add(sre);+// processors.add(grab);+//+// CommandCounter commandCounter = new CommandCounter();+//+// Assert.assertTrue(+// "Expected 0, got " + commandCounter.count,+// commandCounter.count == 0+// );+//+// cache = createCache(processors, "commandCounter", commandCounter, "counter");+//+//+// // wait 6 seconds, we should have *minimum* of five hits by then...+//+// Thread.sleep(6 * 1000);+//+// Assert.assertTrue(+// "Expect >= 5, got " + commandCounter.count,+// commandCounter.count >= 5+// );+// } finally {+// if (cache != null) {+// cache.shutdown();+// }+// }+// }+//+//+// /**+// * Tests rules with range events and a three-way rule definition that+// * executes with different command parameters depending on whether the range value+// * is at min boundary, max boundary or between boundaries.+// *+// * @throws Exception if test fails+// */+// @Test+// public void testSpecializedEventAPI() throws Exception {+// StatusCache cache = null;+//+// try {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/range-limits/").toString();+//+// config.setResourcePath(newResourcePath);+//+// RuleEngine rules = new RuleEngine();+//+// List<EventProcessor> processors = new ArrayList<EventProcessor>();+// processors.add(rules);+//+// CommandCounter commandCounter = new CommandCounter();+//+// cache = createCache(processors, "commandCounter", commandCounter, "counter");+//+// for (int rangeValue = 0; rangeValue < 10; rangeValue++) {+// Range range = new Range(11, "temperature", rangeValue, -10, 10);+//+// cache.update(range);+//+// Assert.assertTrue(+// "Expected '" + rangeValue + "', got " + commandCounter.lastValue,+// commandCounter.lastValue.equals(Integer.toString(rangeValue))+// );+//+// Assert.assertTrue(commandCounter.count == rangeValue + 1);+// }+//+//+// {+// Range range = new Range(11, "temperature", 10, -10, 10);+//+// cache.update(range);+//+// Assert.assertTrue(+// "Expected 'hit the max', got " + commandCounter.lastValue,+// commandCounter.lastValue.equals("hit the max")+// );+//+// Assert.assertTrue(+// "Expected 11, got " + commandCounter.count,+// commandCounter.count == 11+// );+// }+//+// for (int rangeValue = 9; rangeValue > -10; rangeValue--) {+// Range range = new Range(11, "temperature", rangeValue, -10, 10);+//+// cache.update(range);+//+// Assert.assertTrue(+// "Expected '" + rangeValue + "', got " + commandCounter.lastValue,+// commandCounter.lastValue.equals(Integer.toString(rangeValue))+// );+// }+//+// Range range = new Range(11, "temperature", -10, -10, 10);+//+// cache.update(range);+//+// Assert.assertTrue(+// "Expected 'hit the min', got " + commandCounter.lastValue,+// commandCounter.lastValue.equals("hit the min")+// );+//+// Assert.assertTrue(+// "Expected 31, got " + commandCounter.count,+// commandCounter.count == 31+// );+// } finally {+// if (cache != null) {+// cache.shutdown();+// }+// }+// }+//+//+// /**+// * Test parameterized command execution based on sensor event condition.+// *+// * @throws Exception if test fails+// */+// @Test+// public void testParameterizedCommandExecution() throws Exception {+// StatusCache cache = null;+//+// try {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/param-command-execution/").toString();+//+// config.setResourcePath(newResourcePath);+//+// RuleEngine ruleEngine = new RuleEngine();+//+// List<EventProcessor> processors = new ArrayList<EventProcessor>();+// processors.add(ruleEngine);+//+// CommandCounter commandCounter = new CommandCounter();+//+// cache = createCache(processors, "commandCounter", commandCounter, "counter");+//+// Assert.assertTrue(commandCounter.count == 0);+//+// Switch sw1 = new Switch(100, "test sensor", "on", Switch.State.ON);+//+// cache.update(sw1);+//+// Assert.assertTrue(commandCounter.count == 1);+// Assert.assertTrue(commandCounter.lastValue.equals("5"));+// } finally {+// if (cache != null) {+// cache.shutdown();+// }+// }+// }+//+//+// /**+// * Test command execution (no params) based on sensor event condition.+// *+// * @throws Exception if test fails+// */+// @Test+// public void testCommandExecution() throws Exception {+// StatusCache cache = null;+//+// try {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/command-execution/").toString();+//+// config.setResourcePath(newResourcePath);+//+// RuleEngine rules = new RuleEngine();+//+// List<EventProcessor> processors = new ArrayList<EventProcessor>();+// processors.add(rules);+//+// CommandCounter commandCounter = new CommandCounter();+//+// cache = createCache(processors, "commandCounter", commandCounter, "counter");+//+// Assert.assertTrue(commandCounter.count == 0);+//+// Switch sw1 = new Switch(1, "test sensor", "on", Switch.State.ON);+//+// cache.update(sw1);+//+// Assert.assertTrue(commandCounter.count == 1);+// } finally {+// if (cache != null) {+// cache.shutdown();+// }+// }+// }+//+//+// /**+// * Test rule execution that require three separate switch events (sensors) to be+// * in 'on' state or 'off' state.+// *+// * @throws Exception if test fails+// */+// @Test+// public void testThreeWaySwitchOn() throws Exception {+// StatusCache cache = null;+//+// try {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/sensor-three-switches/").toString();+//+// config.setResourcePath(newResourcePath);+//+// RuleEngine rules = new RuleEngine();+// EventGrab grab = new EventGrab();+//+// List<EventProcessor> processors = new ArrayList<EventProcessor>();+// processors.add(rules);+// processors.add(grab);+//+// CommandCounter commandCounter = new CommandCounter();+//+// cache = createCache(processors, "commandCounter", commandCounter, "counter");+//+// Assert.assertTrue(commandCounter.count == 0);+//+//+// // Switch 1 off...+//+// Switch sw1 = new Switch(1, "sensor 1", "off", Switch.State.OFF);+//+// cache.update(sw1);+//+// Assert.assertTrue(commandCounter.count == 0);+//+// Event evt = grab.event;+//+// Assert.assertTrue(+// "Expected 'sensor 1', got '" + evt.getSource() + "'",+// evt.getSource().equals("sensor 1")+// );+//+// String currentState = cache.queryStatus(1);+//+// Assert.assertTrue(currentState.equals("off"));+//+//+// // Switch 2 off...+//+// Switch sw2 = new Switch(2, "sensor 2", "off", Switch.State.OFF);+//+// cache.update(sw2);+//+// Assert.assertTrue(commandCounter.count == 0);+//+// evt = grab.event;+//+// Assert.assertTrue(+// "Expected 'sensor 2', got '" + evt.getSource() + "'",+// evt.getSource().equals("sensor 2")+// );+//+// currentState = cache.queryStatus(2);+//+// Assert.assertTrue(currentState.equals("off"));+//+//+// // All off...+//+// Switch sw3 = new Switch(3, "sensor 3", "off", Switch.State.OFF);+//+// cache.update(sw3);+//+// Assert.assertTrue(+// "Expected 1, got " + commandCounter.count,+// commandCounter.count == 1+// );+//+// Assert.assertTrue(commandCounter.lastValue.equals("all off"));+//+// evt = grab.event;+//+// Assert.assertTrue(+// "Expected 'sensor 3', got '" + evt.getSource() + "'",+// evt.getSource().equals("sensor 3")+// );+//+// currentState = cache.queryStatus(3);+//+// Assert.assertTrue(currentState.equals("off"));+//+//+// // Update sensor 1 'on'....+//+// sw1 = new Switch(1, "sensor 1", "on", Switch.State.ON);+//+// cache.update(sw1);+//+//+// evt = grab.event;+//+// Assert.assertTrue(+// "Expected 'sensor 1', got '" + evt.getSource() + "'",+// evt.getSource().equals("sensor 1")+// );+//+// currentState = cache.queryStatus(1);+//+// Assert.assertTrue(currentState.equals("on"));+//+// Assert.assertTrue(+// "Expected 1, got " + commandCounter.count,+// commandCounter.count == 1+// );+//+//+// currentState = cache.queryStatus(2);+//+// Assert.assertTrue(currentState.equals("off"));+//+//+// currentState = cache.queryStatus(3);+//+// Assert.assertTrue(currentState.equals("off"));+//+//+// // Update sensor 2 'on'....+//+// sw2 = new Switch(2, "sensor 2", "on", Switch.State.ON);+//+// cache.update(sw2);+//+//+// evt = grab.event;+//+// Assert.assertTrue(+// "Expected 'sensor 2', got '" + evt.getSource() + "'",+// evt.getSource().equals("sensor 2")+// );+//+// Assert.assertTrue(+// "Expected 1, got " + commandCounter.count,+// commandCounter.count == 1+// );+//+// currentState = cache.queryStatus(1);+//+// Assert.assertTrue(currentState.equals("on"));+//+//+// currentState = cache.queryStatus(2);+//+// Assert.assertTrue(currentState.equals("on"));+//+//+// currentState = cache.queryStatus(3);+//+// Assert.assertTrue(currentState.equals("off"));+//+//+// // Update sensor 3 'on'... this is where 'all on' command should trigger.+//+// sw3 = new Switch(3, "sensor 3", "on", Switch.State.ON);+//+// cache.update(sw3);+//+// evt = grab.event;+//+// Assert.assertTrue(+// "Expected 'on', got '" + evt.getValue() + "'",+// evt.getValue().equals("on")+// );+//+//+// Assert.assertTrue(+// "Expected 2, got " + commandCounter.count,+// commandCounter.count == 2+// );+//+// Assert.assertTrue(commandCounter.lastValue.equals("all on"));+//+//+// currentState = cache.queryStatus(1);+//+// Assert.assertTrue(currentState.equals("on"));+//+//+// currentState = cache.queryStatus(2);+//+// Assert.assertTrue(currentState.equals("on"));+//+//+// currentState = cache.queryStatus(3);+//+// Assert.assertTrue(currentState.equals("on"));+//+//+// // Turn all off again... random order this time.+//+//+// // Switch 1 off...+//+// sw2 = new Switch(2, "sensor 2", "off", Switch.State.OFF);+//+// cache.update(sw2);+//+// Assert.assertTrue(commandCounter.count == 2);+//+// evt = grab.event;+//+// Assert.assertTrue(+// "Expected 'sensor 2', got '" + evt.getSource() + "'",+// evt.getSource().equals("sensor 2")+// );+//+// currentState = cache.queryStatus(2);+//+// Assert.assertTrue(currentState.equals("off"));+//+//+// // Switch 3 off...+//+// sw3 = new Switch(3, "sensor 3", "off", Switch.State.OFF);+//+// cache.update(sw3);+//+// Assert.assertTrue(commandCounter.count == 2);+//+// evt = grab.event;+//+// Assert.assertTrue(+// "Expected 'sensor 3', got '" + evt.getSource() + "'",+// evt.getSource().equals("sensor 3")+// );+//+// currentState = cache.queryStatus(3);+//+// Assert.assertTrue(currentState.equals("off"));+//+//+// // All off...+//+// sw1 = new Switch(1, "sensor 1", "off", Switch.State.OFF);+//+// cache.update(sw1);+//+// Assert.assertTrue(+// "Expected 3, got " + commandCounter.count,+// commandCounter.count == 3+// );+//+// Assert.assertTrue(commandCounter.lastValue.equals("all off"));+//+// evt = grab.event;+//+// Assert.assertTrue(+// "Expected 'sensor 1', got '" + evt.getSource() + "'",+// evt.getSource().equals("sensor 1")+// );+//+// currentState = cache.queryStatus(1);+//+// Assert.assertTrue(currentState.equals("off"));+//+//+// // Finally all on again... in reverse order.+//+//+// sw3 = new Switch(3, "sensor 3", "on", Switch.State.ON);+//+// cache.update(sw3);+//+//+// evt = grab.event;+//+// Assert.assertTrue(+// "Expected 'sensor 3', got '" + evt.getSource() + "'",+// evt.getSource().equals("sensor 3")+// );+//+// currentState = cache.queryStatus(3);+//+// Assert.assertTrue(currentState.equals("on"));+//+// Assert.assertTrue(+// "Expected 3, got " + commandCounter.count,+// commandCounter.count == 3+// );+//+//+// currentState = cache.queryStatus(2);+//+// Assert.assertTrue(currentState.equals("off"));+//+//+// currentState = cache.queryStatus(1);+//+// Assert.assertTrue(currentState.equals("off"));+//+//+// // Update sensor 2 'on'....+//+// sw2 = new Switch(2, "sensor 2", "on", Switch.State.ON);+//+// cache.update(sw2);+//+//+// evt = grab.event;+//+// Assert.assertTrue(+// "Expected 'sensor 2', got '" + evt.getSource() + "'",+// evt.getSource().equals("sensor 2")+// );+//+// Assert.assertTrue(+// "Expected 3, got " + commandCounter.count,+// commandCounter.count == 3+// );+//+// currentState = cache.queryStatus(3);+//+// Assert.assertTrue(currentState.equals("on"));+//+//+// currentState = cache.queryStatus(2);+//+// Assert.assertTrue(currentState.equals("on"));+//+//+// currentState = cache.queryStatus(1);+//+// Assert.assertTrue(currentState.equals("off"));+//+//+// // Update sensor 1 'on'... this is where 'all on' command should trigger.+//+// sw1 = new Switch(1, "sensor 1", "on", Switch.State.ON);+//+// cache.update(sw1);+//+// evt = grab.event;+//+// Assert.assertTrue(+// "Expected 'on', got '" + evt.getValue() + "'",+// evt.getValue().equals("on")+// );+//+//+// Assert.assertTrue(+// "Expected 4, got " + commandCounter.count,+// commandCounter.count == 4+// );+//+// Assert.assertTrue(commandCounter.lastValue.equals("all on"));+//+//+// currentState = cache.queryStatus(1);+//+// Assert.assertTrue(currentState.equals("on"));+//+//+// currentState = cache.queryStatus(2);+//+// Assert.assertTrue(currentState.equals("on"));+//+//+// currentState = cache.queryStatus(3);+//+// Assert.assertTrue(currentState.equals("on"));+// } finally {+// cache.shutdown();+// }+//+// }+//+//+// /**+// * Test rule condition based on two existing sensor events.+// *+// * @throws Exception if test fails+// */+// @Test+// public void testRuleConditionOnExistingSensorValues() throws Exception {+//+// StatusCache cache = null;+//+// try {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/sensors/").toString();+//+// config.setResourcePath(newResourcePath);+//+// RuleEngine rules = new RuleEngine();+// EventGrab grab = new EventGrab();+//+// List<EventProcessor> processors = new ArrayList<EventProcessor>();+// processors.add(rules);+// processors.add(grab);+//+// CommandCounter commandCounter = new CommandCounter();+//+// cache = createCache(processors, "commandCounter", commandCounter, "counter");+//+//+// Assert.assertTrue(commandCounter.count == 0);+//+//+// // should not trigger on existence of first event...+//+// Switch sw1 = new Switch(999, "my event", "off", Switch.State.OFF);+//+// cache.update(sw1);+//+// Assert.assertTrue(commandCounter.count == 0);+//+// Event evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("my event"));+// Assert.assertTrue(evt.getSourceID() == 999);+// Assert.assertTrue(+// "Expected 'off', got '" + evt.getValue() + "'",+// evt.getValue().equals("off")+// );+// Assert.assertTrue(evt.serialize().equals("off"));+// Assert.assertTrue(evt instanceof Switch);+// Assert.assertTrue(evt.equals(sw1));+// Assert.assertTrue(evt == sw1);+//+// Switch swevt = (Switch) evt;+//+// Assert.assertTrue(swevt.getState().equals(Switch.State.OFF));+//+//+// // should trigger on existence of both events....+//+// Switch sw2 = new Switch(1000, "test sensor 1", "off", Switch.State.OFF);+//+// cache.update(sw2);+//+// Assert.assertTrue(commandCounter.count == 1);+// Assert.assertTrue(commandCounter.lastValue.equals("triggered"));+//+// evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("test sensor 1"));+// Assert.assertTrue(evt.getSourceID() == 1000);+// Assert.assertTrue(+// "Expected 'off', got '" + evt.getValue() + "'",+// evt.getValue().equals("off")+// );+// Assert.assertTrue(evt.serialize().equals("off"));+// Assert.assertTrue(evt instanceof Switch);+// Assert.assertTrue(evt.equals(sw2));+// Assert.assertTrue(evt == sw2);+//+// swevt = (Switch) evt;+//+// Assert.assertTrue(swevt.getState().equals(Switch.State.OFF));+//+//+// // should not re-trigger due to equivalence rules...+//+// cache.update(sw1);+//+// evt = grab.event;+//+// Assert.assertTrue(commandCounter.count == 1);+//+// Assert.assertTrue(evt.getSource().equals("my event"));+// Assert.assertTrue(evt.getSourceID() == 999);+// Assert.assertTrue(+// "Expected 'off', got '" + evt.getValue() + "'",+// evt.getValue().equals("off")+// );+// Assert.assertTrue(evt.serialize().equals("off"));+// Assert.assertTrue(evt instanceof Switch);+// Assert.assertTrue(evt.equals(sw1));+// Assert.assertTrue(evt == sw1);+//+// swevt = (Switch) evt;+//+// Assert.assertTrue(swevt.getState().equals(Switch.State.OFF));+//+//+// // should not re-trigger due to equivalence rules....+//+// cache.update(sw2);+//+// Assert.assertTrue(commandCounter.count == 1);+//+// evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("test sensor 1"));+// Assert.assertTrue(evt.getSourceID() == 1000);+// Assert.assertTrue(+// "Expected 'off', got '" + evt.getValue() + "'",+// evt.getValue().equals("off")+// );+// Assert.assertTrue(evt.serialize().equals("off"));+// Assert.assertTrue(evt instanceof Switch);+// Assert.assertTrue(evt.equals(sw2));+// Assert.assertTrue(evt == sw2);+//+// swevt = (Switch) evt;+//+// Assert.assertTrue(swevt.getState().equals(Switch.State.OFF));+//+//+// // should trigger due to changed event value...+//+// sw2 = new Switch(1000, "test sensor 1", "on", Switch.State.ON);+//+// cache.update(sw2);+//+// Assert.assertTrue(commandCounter.count == 2);+//+// evt = grab.event;+//+// Assert.assertTrue(evt.getSource().equals("test sensor 1"));+// Assert.assertTrue(evt.getSourceID() == 1000);+// Assert.assertTrue(+// "Expected 'on', got '" + evt.getValue() + "'",+// evt.getValue().equals("on")+// );+// Assert.assertTrue(evt.serialize().equals("on"));+// Assert.assertTrue(evt instanceof Switch);+// Assert.assertTrue(evt.equals(sw2));+// Assert.assertTrue(evt == sw2);+//+// swevt = (Switch) evt;+//+// Assert.assertTrue(swevt.getState().equals(Switch.State.ON));+//+//+// // should trigger again due to second event's changed value...+//+// sw1 = new Switch(999, "my event", "on", Switch.State.ON);+//+// cache.update(sw1);+//+// evt = grab.event;+//+// Assert.assertTrue(commandCounter.count == 3);+//+// Assert.assertTrue(evt.getSource().equals("my event"));+// Assert.assertTrue(evt.getSourceID() == 999);+// Assert.assertTrue(+// "Expected 'on', got '" + evt.getValue() + "'",+// evt.getValue().equals("on")+// );+// Assert.assertTrue(evt.serialize().equals("on"));+// Assert.assertTrue(evt instanceof Switch);+// Assert.assertTrue(evt.equals(sw1));+// Assert.assertTrue(evt == sw1);+//+// swevt = (Switch) evt;+//+// Assert.assertTrue(swevt.getState().equals(Switch.State.ON));+// } finally {+// if (cache != null) {+// cache.shutdown();+// }+// }+// }+//+//+// /**+// * Test implementation behavior when controller configuration for finding/reading+// * rules is incorrect.+// */+// @Test+// public void testWhenNoRuleDir() {+// String newResourcePath = AllTests.getAbsoluteFixturePath()+// .resolve("statuscache/rules/no-rule-dir/").toString();+//+// config.setResourcePath(newResourcePath);+//+// RuleEngine rules = new RuleEngine();+//+// try {+// rules.init();+// rules.start(new LifeCycleEvent(null));+//+// Assert.fail("Should not get here...");+// } catch (InitializationException e) {+// // Expected -- controller configuration is incorrect if no rule dir is present+// }+//+// }+//+//+// // Helpers --------------------------------------------------------------------------------------+//+//+// private StatusCache createCache(List<EventProcessor> processors,+// String protocolType, CommandBuilder commandBuilder,+// String commandName) throws Exception {+// ChangedStatusTable cst = new ChangedStatusTable();+// EventProcessorChain epc = new EventProcessorChain();+//+// epc.setEventProcessors(processors);+// epc.init();+//+// StatusCache cache = new StatusCache(cst, epc);+//+// Map<String, CommandBuilder> builders = new HashMap<String, CommandBuilder>();+// builders.put(protocolType, commandBuilder);+//+// CommandFactory cf = new CommandFactory(builders);+//+// Element cmdElement = new Element("command", ModelBuilder.SchemaVersion.OPENREMOTE_NAMESPACE);+// cmdElement.setAttribute("id", "10");+// cmdElement.setAttribute("protocol", protocolType);+//+// Element nameProp = new Element("property", ModelBuilder.SchemaVersion.OPENREMOTE_NAMESPACE);+// nameProp.setAttribute("name", "name");+// nameProp.setAttribute("value", commandName);+//+// Set<Element> content = new HashSet<Element>();+// content.add(nameProp);+//+// cmdElement.addContent(content);+//+// Version20CommandBuilder cmdBuilder = new Version20CommandBuilder(cf);+// Command cmd = cmdBuilder.build(cmdElement);+//+// Set<Command> commands = new HashSet<Command>();+// commands.add(cmd);+//+// cache.initializeEventContext(commands);+//+// cache.start();+//+// return cache;+// }+//+//+// // Nested Classes -------------------------------------------------------------------------------+//++// private static class CommandCounter implements CommandBuilder {+// private int count = 0;+// private String lastValue = "<nothing>";+//+//+// @Override+// public org.openremote.controller.command.Command build(Element el) {+// count++;+//+// Attribute attribute = el.getAttribute(+// org.openremote.controller.command.Command.DYNAMIC_VALUE_ATTR_NAME+// );+//+// if (attribute != null) {+// lastValue = attribute.getValue();+// }+//+// return new ExecutableCommand() {+// @Override+// public void send() {+//+// }+// };+// }+// }+//++}+diff --git a/controller/src/test/groovy/org/openremote/test/rules/EventModTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/EventModTest.groovynew file mode 100644index 000000000..1416c8f18--- /dev/null+++ b/controller/src/test/groovy/org/openremote/test/rules/EventModTest.groovy@@ -0,0 +1,93 @@+package org.openremote.test.rules++import org.kie.api.KieServices+import org.kie.api.io.Resource+import org.openremote.controller.ControllerService+import org.openremote.controller.event.CommandFacade+import org.openremote.controller.event.EventProcessorChain+import org.openremote.controller.event.SwitchEvent+import org.openremote.controller.model.SwitchSensor+import org.openremote.controller.rules.RuleEngine+import org.openremote.test.ContainerTrait+import org.openremote.test.util.EventGrabProcessor+import org.openremote.test.util.TestEventProducerCommand+import spock.lang.Specification++import java.util.stream.Stream++import static org.kie.api.io.ResourceType.DRL++/**+ * Basic rule engine test, trigger a rule through an event.+ * The rule dispatches a new event, replacing the original event.+ */+class EventModTest extends Specification implements ContainerTrait {++ def "Sensor event replaced by rule-triggered event"() {++ given: "event processors and rules"+ def ruleEngineProcessor = new RuleEngine() {+ @Override+ protected Stream<Resource> getResources(KieServices kieServices) {+ Stream.of(+ kieServices.getResources().newClassPathResource(+ "org/openremote/test/rules/EventMod.drl"+ ).setResourceType(DRL)+ )+ }+ }+ def grabProcessor = new EventGrabProcessor();++ def commandDefinitions = []+ def commandFacade = new CommandFacade(commandDefinitions)+ def eventProcessorChain = new EventProcessorChain(+ commandFacade,+ ruleEngineProcessor,+ grabProcessor+ )++ and: "the started controller server"+ def controllerService = new ControllerService(eventProcessorChain)+ def services = Stream.of(controllerService)+ def serverPort = findEphemeralPort()+ def container = startContainer(defaultConfig(serverPort), services)++ and: "registered sensor"+ def sensorName = "test"+ def sensorId = 123+ def commandId = 1+ def switchSensor = new SwitchSensor(+ sensorName,+ sensorId,+ controllerService.getCache(),+ new TestEventProducerCommand(),+ commandId+ );+ controllerService.getCache().registerSensor(switchSensor);++ when: "the sensor says it has been switched on"+ def switchEvent = new SwitchEvent(sensorId, sensorName, "on", SwitchEvent.State.ON);+ controllerService.getCache().update(switchEvent);++ and: "we wait a bit for the rules to fire"+ Thread.sleep(100);++ then: "the rules should immediately switch the sensor off again"+ def lastEvent = grabProcessor.lastEvent;+ lastEvent.getSourceID() == sensorId+ lastEvent.getSource() == sensorName+ 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 cache state of the sensor should be 'off'"+ controllerService.getCache().queryStatus(sensorId) == "off"++ cleanup: "the server should be stopped"+ stopContainer(container)+ }+}diff --git a/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovynew file mode 100644index 000000000..d16afd52e--- /dev/null+++ b/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovy@@ -0,0 +1,212 @@+package org.openremote.test.rules++import org.kie.api.KieServices+import org.kie.api.io.Resource+import org.openremote.controller.ControllerService+import org.openremote.controller.event.CommandFacade+import org.openremote.controller.event.EventProcessorChain+import org.openremote.controller.event.RangeEvent+import org.openremote.controller.event.SwitchEvent+import org.openremote.controller.model.RangeSensor+import org.openremote.controller.rules.RuleEngine+import org.openremote.test.ContainerTrait+import org.openremote.test.util.EventGrabProcessor+import org.openremote.test.util.TestEventProducerCommand+import spock.lang.Specification++import java.util.stream.Stream++/**+ * Test deployment behavior when some of the rule definitions have+ * errors or can't be deployed. Make sure the correct ones still+ * operate.+ */+class MixedWithErrorsTest extends Specification implements ContainerTrait {++ def "Sensor event replaced by rule-triggered event"() {++ given: "some sensor event processors and rules"+ def ruleEngineProcessor = new RuleEngine() {+ @Override+ protected Stream<Resource> getResources(KieServices kieServices) {+ Stream.of(+ kieServices.getResources().newClassPathResource(+ "org/openremote/test/rules/mixed-with-errors/EventMod.drl"+ ),+ kieServices.getResources().newClassPathResource(+ "org/openremote/test/rules/mixed-with-errors/IncorrectRule.drl"+ ),+ kieServices.getResources().newClassPathResource(+ "org/openremote/test/rules/mixed-with-errors/BrokenDTable.csv"+ ),+ kieServices.getResources().newClassPathResource(+ "org/openremote/test/rules/mixed-with-errors/DTableTest.csv"+ )+ )+ }+ }+ def grabProcessor = new EventGrabProcessor()++ def commandDefinitions = []+ def commandFacade = new CommandFacade(commandDefinitions)+ def eventProcessorChain = new EventProcessorChain(+ commandFacade,+ ruleEngineProcessor,+ grabProcessor+ )++ and: "the started controller server"+ def controllerService = new ControllerService(eventProcessorChain)+ def services = Stream.of(controllerService)+ def serverPort = findEphemeralPort()+ def container = startContainer(defaultConfig(serverPort), services)++ when: "a switch event is dispatched"+ def switchEvent = new SwitchEvent(1, "test", "on", SwitchEvent.State.ON);+ controllerService.getCache().update(switchEvent)++ and: "we wait a bit for the rules to fire"+ Thread.sleep(100)+ def lastEvent = grabProcessor.lastEvent++ then: "the event should not be modified"+ lastEvent.getSourceID() == 1+ lastEvent.getSource() == "test"+ lastEvent.getValue() == "on"+ lastEvent.serialize() == "on"++ and: "the total event couht should match"+ grabProcessor.totalEventCount == 1++ when: "a range sensor is registered"+ controllerService.getCache().registerSensor(+ new RangeSensor(+ "test level mod",+ 123,+ controllerService.getCache(),+ new TestEventProducerCommand(),+ 1,+ 0,+ 1000+ )+ )++ and: "a range event is dispatched"+ def rangeEvent = new RangeEvent(123, "test level mod", 30, 0, 1000);+ controllerService.getCache().update(rangeEvent)++ and: "we wait a bit for the rules to fire"+ Thread.sleep(100)+ lastEvent = grabProcessor.lastEvent++ then: "the event should be modified/replaced"+ lastEvent.getSourceID() == 123+ lastEvent.getSource() == "test level mod"+ lastEvent.getValue() == 321+ lastEvent.serialize() == "321"+ lastEvent instanceof RangeEvent+ lastEvent != rangeEvent // Must be replaced by rule!++ and: "the total event couht should match"+ grabProcessor.totalEventCount == 2++ when: "another range sensor is registered"+ controllerService.getCache().registerSensor(+ new RangeSensor(+ "test level mod 555",+ 555,+ controllerService.getCache(),+ new TestEventProducerCommand(),+ 1,+ 0,+ 10000+ )+ )++ and: "a range event is dispatched"+ rangeEvent = new RangeEvent(555, "test level mod 555", 101, 0, 10000)+ controllerService.getCache().update(rangeEvent)++ and: "we wait a bit for the rules to fire"+ Thread.sleep(100)+ lastEvent = grabProcessor.lastEvent++ then: "the event should be modified/replaced"+ lastEvent.getSourceID() == 555+ lastEvent.getSource() == "test level mod 555"+ lastEvent.getValue() == 55+ lastEvent.serialize() == "55"+ lastEvent instanceof RangeEvent+ lastEvent != rangeEvent // Must be replaced by rule!++ and: "the total event couht should match"+ grabProcessor.totalEventCount == 3++ when: "another range sensor is registered"+ controllerService.getCache().registerSensor(+ new RangeSensor(+ "test level mod 666",+ 666,+ controllerService.getCache(),+ new TestEventProducerCommand(),+ 1,+ 0,+ 10000+ )+ )++ and: "a range event is dispatched"+ rangeEvent = new RangeEvent(666, "test level mod 666", 1, 1, 10000)+ controllerService.getCache().update(rangeEvent)++ and: "we wait a bit for the rules to fire"+ Thread.sleep(100)+ lastEvent = grabProcessor.lastEvent++ then: "the event should be modified/replaced"+ lastEvent.getSourceID() == 666+ lastEvent.getSource() == "test level mod 666"+ lastEvent.getValue() == 6666+ lastEvent.serialize() == "6666"+ lastEvent instanceof RangeEvent+ lastEvent != rangeEvent // Must be replaced by rule!++ and: "the total event couht should match"+ grabProcessor.totalEventCount == 4++ when: "another range sensor is registered"+ controllerService.getCache().registerSensor(+ new RangeSensor(+ "test level mod 777",+ 777,+ controllerService.getCache(),+ new TestEventProducerCommand(),+ 1,+ -100,+ 100+ )+ )++ and: "a range event is dispatched"+ rangeEvent = new RangeEvent(777, "test level mod 777", 10, -100, 100)+ controllerService.getCache().update(rangeEvent)++ and: "we wait a bit for the rules to fire"+ Thread.sleep(100)+ lastEvent = grabProcessor.lastEvent++ then: "the event should be modified/replaced"+ lastEvent.getSourceID() == 777+ lastEvent.getSource() == "test level mod 777"+ lastEvent.getValue() == -77+ lastEvent.serialize() == "-77"+ lastEvent instanceof RangeEvent+ lastEvent != rangeEvent // Must be replaced by rule!++ and: "the total event couht should match"+ grabProcessor.totalEventCount == 5++ cleanup: "the server should be stopped"+ stopContainer(container)+ }+}diff --git a/controller/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovynew file mode 100644index 000000000..6ad2379da--- /dev/null+++ b/controller/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovy@@ -0,0 +1,116 @@+package org.openremote.test.rules++import org.kie.api.KieBase+import org.kie.api.KieServices+import org.kie.api.builder.KieFileSystem+import org.kie.api.builder.model.KieSessionModel+import org.kie.api.runtime.KieContainer+import org.kie.api.runtime.KieSession+import org.kie.internal.io.ResourceFactory+import org.openremote.controller.event.CustomStateEvent+import org.openremote.controller.rules.RuleExecutionLogger+import org.openremote.test.ContainerTrait+import spock.lang.Shared+import spock.lang.Specification++import java.util.logging.*++import static org.kie.api.builder.Message.Level.ERROR++class RuleExecutionLoggerTest extends Specification implements ContainerTrait {++ public static TEST_SENSOR_NAME = "SENSOR_NAME";++ @Shared+ KieSession ksession++ def setup() {+ def kieServices = KieServices.Factory.get()+ def kieModuleModel = kieServices.newKieModuleModel()+ def kieBaseModel = kieModuleModel.newKieBaseModel("OpenRemoteKBase")+ .setDefault(true)+ .setEqualsBehavior(org.kie.api.conf.EqualityBehaviorOption.EQUALITY)+ def kieSessionModel = kieBaseModel.newKieSessionModel("OpenRemoteKSession")+ .setDefault(true)+ .setType(KieSessionModel.KieSessionType.STATEFUL)+ KieFileSystem kfs = kieServices.newKieFileSystem()+ kfs.writeKModuleXML(kieModuleModel.toXML())++ kfs.write(ResourceFactory.newClassPathResource("org/openremote/test/rules/TestRuleFiring.drl")+ );+ def kieBuilder = kieServices.newKieBuilder(kfs).buildAll();++ if (kieBuilder.getResults().hasMessages(ERROR)) {+ throw new RuntimeException("KIE builder has errors")+ }++ KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId())+ KieBase kb = kieContainer.getKieBase();+ ksession = kb.newKieSession();+ }++ def cleanup() {+ if (ksession != null) {+ ksession.dispose()+ ksession = null;+ }+ }++ /**+ * This test confirms the plumbing for the event listener is working.+ * This test is testing the following behavior:+ * The event listener detects rule activations.+ * The listener fires "BeforeMatchFired" in response to rule activations.+ * The listener is properly detecting and logging information about the rule (name, declarations, LHS, etc.).+ */+ def "Event listener plumbing"() {+ given: "a custom state event"+ CustomStateEvent newState = new CustomStateEvent(1, TEST_SENSOR_NAME, "ON");+ ksession.insert(newState)++ and: "a logger of rule execution"+ RuleExecutionLogger ruleExecutionLogger = new RuleExecutionLogger()+ ksession.addEventListener(ruleExecutionLogger)+ //add a handler so logging output can be stored in active memory+ Logger ruleLogger = ruleExecutionLogger.getLOG()+ def testLogHandler = new TestLogHandler()+ ruleLogger.addHandler(testLogHandler);+ ruleLogger.setLevel(Level.ALL);++ when: "rules are fired"+ ksession.fireAllRules();++ String lastLog = String.format("rule \"%s\" // (package org.openremote.test.rules)\n" ++ "\tDeclarations \n\t\tDeclaration: \"\$e\"\n\t\tValue:\n\t\t\tSensor Name: \"%s\"\n\t\t\tSensor Value: \"ON\"\n" ++ "\tLHS objects(antecedents)\n\t\tClass: \"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);++ then: "the execution should be logged"+ testLogHandler.lastLevel == Level.FINE+ testLogHandler.lastMessage == lastLog+ }++ static class TestLogHandler extends Handler {++ Level lastLevel+ String lastMessage;++ TestLogHandler() {+ this.setLevel(Level.ALL);+ this.setFormatter(new SimpleFormatter());+ }++ @Override+ void publish(LogRecord record) {+ lastLevel = record.getLevel();+ lastMessage = record.getMessage();+ }++ @Override+ void flush() {+ }++ @Override+ void close() {+ }+ }+}\ No newline at end of filediff --git a/controller/src/test/groovy/org/openremote/test/util/EventGrabProcessor.java b/controller/src/test/groovy/org/openremote/test/util/EventGrabProcessor.javanew file mode 100644index 000000000..2cdcf1ac2--- /dev/null+++ b/controller/src/test/groovy/org/openremote/test/util/EventGrabProcessor.java@@ -0,0 +1,38 @@+package org.openremote.test.util;++import org.openremote.controller.event.Event;+import org.openremote.controller.event.EventContext;+import org.openremote.controller.event.EventProcessor;++public class EventGrabProcessor extends EventProcessor {++ public Event lastEvent;+ public int totalEventCount = 0;++ @Override+ public void push(EventContext 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/groovy/org/openremote/test/util/TestEventProducerCommand.java b/controller/src/test/groovy/org/openremote/test/util/TestEventProducerCommand.javanew file mode 100644index 000000000..cadd4e3a5--- /dev/null+++ b/controller/src/test/groovy/org/openremote/test/util/TestEventProducerCommand.java@@ -0,0 +1,7 @@+package org.openremote.test.util;++import org.openremote.controller.command.EventProducerCommand;++public class TestEventProducerCommand implements EventProducerCommand {++}diff --git a/controller/src/test/resources/org/openremote/test/rules/EventMod.drl b/controller/src/test/resources/org/openremote/test/rules/EventMod.drlnew file mode 100644index 000000000..44eb61dd0--- /dev/null+++ b/controller/src/test/resources/org/openremote/test/rules/EventMod.drl@@ -0,0 +1,12 @@+package org.openremote.test.rules;++import org.openremote.controller.event.*;++global org.openremote.controller.statuscache.SwitchFacade switches;++rule "Modify Switch State"+when+ $switch : SwitchEvent(sourceID == 123)+then+ switches.name($switch.getSource()).off();+enddiff --git a/controller/src/test/resources/org/openremote/test/rules/TestRuleFiring.drl b/controller/src/test/resources/org/openremote/test/rules/TestRuleFiring.drlnew file mode 100644index 000000000..03a322f30--- /dev/null+++ b/controller/src/test/resources/org/openremote/test/rules/TestRuleFiring.drl@@ -0,0 +1,13 @@+package org.openremote.test.rules;++import org.openremote.controller.command.*;+import org.openremote.controller.event.*;+import org.openremote.controller.rules.*++rule "TestRuleFiring"+when+ $e: Event(source == RuleExecutionLoggerTest.TEST_SENSOR_NAME)+then+// Do Nothing+end+diff --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.csvnew file mode 100644index 000000000..2cd505cb7--- /dev/null+++ b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/BrokenDTable.csv@@ -0,0 +1,14 @@+++, ,Ruleset, Cannot find the ruleset on this one+, ,Import, org.openremote.controller.event.Event+++ ,RuleTable,Event Mod+, ,CONDITION,ACTION+, ,evt: Event,+,(descriptions),sourceID,evt.setSourceID($param);+,Case, Event 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.csvnew file mode 100644index 000000000..5d33b0a70--- /dev/null+++ b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/DTableTest.csv@@ -0,0 +1,15 @@+++Ruleset, My CSV Rules Examples+Import, org.openremote.controller.event.Event+Variables, org.openremote.controller.statuscache.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+Fire Alarm,"test level mod 555",55+Ice Age,"test level mod 666",6666+Comfort,"test level mod 777",-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.drlnew file mode 100644index 000000000..aca68724a--- /dev/null+++ b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/EventMod.drl@@ -0,0 +1,12 @@+package org.openremote.test.rules++import org.openremote.controller.event.*;++global org.openremote.controller.statuscache.RangeFacade ranges;++rule "Modify Level State Above Max"+when+ Event( sourceID == 123, $name : source )+then+ ranges.name($name).value( 321 );+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.drlnew file mode 100644index 000000000..f1933cbb0--- /dev/null+++ b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/IncorrectRule.drl@@ -0,0 +1,10 @@+package org.openremote.test.rules++import org.openremote.controller.event.*;++rule "Incorrect Event Modification Attempt"+when+ $event : Event( sourceID == 123 )+then+ $event.setSourceID( 321 );+enddiff --git a/manager/test/build.gradle b/manager/test/build.gradleindex 517c7e6a0..cf2ef0d0f 100644--- a/manager/test/build.gradle+++ b/manager/test/build.gradle@@ -10,10 +10,6 @@ dependencies {compile project(":manager:connector:controller2")compile "junit:junit:$junitVersion"- compile "org.spockframework:spock-core:$spockVersion"- compile "org.objenesis:objenesis:$objenesisVersion"- compile "org.glassfish.tyrus:tyrus-client:$tyrusVersion"- compile "org.glassfish.tyrus:tyrus-container-grizzly-client:$tyrusVersion"}test {