Skip to content

armgit / core

Public Imported from GitHub
0

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

Implemented controller deployment

Christian Bauer52422fbc5e83
diff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.java
index a6d082620..f49237203 100644
--- a/container/src/main/java/org/openremote/container/Container.java
+++ b/container/src/main/java/org/openremote/container/Container.java
@@ -35,6 +35,7 @@ import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.stream.Stream;
@@ -194,9 +195,13 @@ public class Container {
/**
* Starts the container and a non-daemon thread that waits forever.
*/
- public void startBackground() throws Exception {
+ public void startBackground() throws Throwable {
// We block here so we die fast if startup fails
- start().get();
+ try {
+ start().get();
+ } catch (ExecutionException ex) {
+ throw ex.getCause();
+ }
Thread containerThread = new Thread("container") {
@Override
public void run() {
diff --git a/container/src/main/java/org/openremote/container/util/TextUtil.java b/container/src/main/java/org/openremote/container/util/TextUtil.java
new file mode 100644
index 000000000..ae555c73c
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/util/TextUtil.java
@@ -0,0 +1,60 @@
+/*
+ * 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;
+
+public class TextUtil {
+
+ /**
+ * Converts a String which represents a pollingInterval into an int which can be used as delay
+ * for Thread.sleep(); <p>
+ * <p>
+ * Following conversion will happen: <p>
+ * <p>
+ * null || "" = -1 <br>
+ * 500 = 500 <br>
+ * 1s = 1000 * 1 = 1000 <br>
+ * 1m = 1000 * 60 = 60000 <br>
+ * 1h = 1000 * 60 * 60 = 3600000 <br>
+ *
+ * @param pollingInterval interval string, such as '1m' as millisecond value
+ * @return interval in milliseconds
+ */
+ public static int convertPollingIntervalString(String pollingInterval) {
+ if ((pollingInterval != null) && (pollingInterval.trim().length() != 0)) {
+ pollingInterval = pollingInterval.trim();
+ char lastChar = pollingInterval.charAt(pollingInterval.length() - 1);
+ String timePart = pollingInterval.substring(0, pollingInterval.length() - 1);
+
+ switch (lastChar) {
+ case 's':
+ return Integer.parseInt(timePart) * 1000;
+ case 'm':
+ return Integer.parseInt(timePart) * 1000 * 60;
+ case 'h':
+ return Integer.parseInt(timePart) * 1000 * 60 * 60;
+ default:
+ return Integer.parseInt(pollingInterval);
+ }
+ }
+
+ return -1;
+ }
+
+}
diff --git a/container/src/main/java/org/openremote/container/xml/CatalogResourceResolver.java b/container/src/main/java/org/openremote/container/xml/CatalogResourceResolver.java
new file mode 100644
index 000000000..1a5c69006
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/xml/CatalogResourceResolver.java
@@ -0,0 +1,138 @@
+/*
+ * 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.xml;
+
+import org.w3c.dom.ls.LSInput;
+import org.w3c.dom.ls.LSResourceResolver;
+
+import java.io.InputStream;
+import java.io.Reader;
+import java.net.URI;
+import java.net.URL;
+import java.util.Map;
+import java.util.logging.Logger;
+
+/**
+ * Another namespace-URI-to-whatever (namespace, context, resolver, map) magic thingy.
+ * <p>
+ * Of course it's just a map, like so many others in the JAXP hell. But this time someone
+ * really went all out on the API fugliness. The person who designed this probably got promoted
+ * and is now designing the signaling system for the airport you are about to land on.
+ * Feeling better?
+ * </p>
+ */
+public class CatalogResourceResolver implements LSResourceResolver {
+
+ private static final Logger LOG = Logger.getLogger(CatalogResourceResolver.class.getName());
+
+ private final Map<URI, URL> catalog;
+
+ public CatalogResourceResolver(Map<URI, URL> catalog) {
+ this.catalog = catalog;
+ }
+
+ public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
+ LOG.fine("Trying to resolve system identifier URI in catalog: " + systemId);
+ URL systemURL;
+ if ((systemURL = catalog.get(URI.create(systemId))) != null) {
+ LOG.finest("Loading catalog resource: " + systemURL);
+ try {
+ Input i = new Input(systemURL.openStream());
+ i.setBaseURI(baseURI);
+ i.setSystemId(systemId);
+ i.setPublicId(publicId);
+ return i;
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+ LOG.info(
+ "System identifier not found in catalog, continuing with default resolution " +
+ "(this most likely means remote HTTP request!): " + systemId
+ );
+ return null;
+ }
+
+ // WTF...
+ private static final class Input implements LSInput {
+
+ InputStream in;
+
+ public Input(InputStream in) {
+ this.in = in;
+ }
+
+ public Reader getCharacterStream() {
+ return null;
+ }
+
+ public void setCharacterStream(Reader characterStream) {
+ }
+
+ public InputStream getByteStream() {
+ return in;
+ }
+
+ public void setByteStream(InputStream byteStream) {
+ }
+
+ public String getStringData() {
+ return null;
+ }
+
+ public void setStringData(String stringData) {
+ }
+
+ public String getSystemId() {
+ return null;
+ }
+
+ public void setSystemId(String systemId) {
+ }
+
+ public String getPublicId() {
+ return null;
+ }
+
+ public void setPublicId(String publicId) {
+ }
+
+ public String getBaseURI() {
+ return null;
+ }
+
+ public void setBaseURI(String baseURI) {
+ }
+
+ public String getEncoding() {
+ return null;
+ }
+
+ public void setEncoding(String encoding) {
+ }
+
+ public boolean getCertifiedText() {
+ return false;
+ }
+
+ public void setCertifiedText(boolean certifiedText) {
+ }
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/xml/DOM.java b/container/src/main/java/org/openremote/container/xml/DOM.java
new file mode 100644
index 000000000..ba8b9d73f
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/xml/DOM.java
@@ -0,0 +1,62 @@
+/*
+ * 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.xml;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import javax.xml.xpath.XPath;
+import java.net.URI;
+import java.net.URL;
+
+/**
+ * Wraps a W3C document and provides an entry point for browsing the DOM (in subclasses).
+ */
+public abstract class DOM {
+
+ public static final URI XML_SCHEMA_NAMESPACE = URI.create("http://www.w3.org/2001/xml.xsd");
+ public static final URL XML_SCHEMA_RESOURCE = DOM.class.getResource("/org/openremote/schemas/xml.xsd");
+
+ public static final String CDATA_BEGIN = "<![CDATA[";
+ public static final String CDATA_END = "]]>";
+
+ private Document dom;
+
+ public DOM(Document dom) {
+ this.dom = dom;
+ }
+
+ public Document getW3CDocument() {
+ return dom;
+ }
+
+ public Element createRoot(String name) {
+ Element el = getW3CDocument().createElementNS(getRootElementNamespace(), name);
+ getW3CDocument().appendChild(el);
+ return el;
+ }
+
+ public abstract String getRootElementNamespace();
+
+ public abstract DOMElement getRoot(XPath xpath);
+
+ public abstract DOM copy();
+
+}
diff --git a/container/src/main/java/org/openremote/container/xml/DOMElement.java b/container/src/main/java/org/openremote/container/xml/DOMElement.java
new file mode 100644
index 000000000..178926fc5
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/xml/DOMElement.java
@@ -0,0 +1,312 @@
+/*
+ * 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.xml;
+
+import org.w3c.dom.*;
+
+import javax.xml.namespace.QName;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Wraps a W3C element.
+ * <p>
+ * Using XPath for simple queries like "get all children with attribute value X" is actually slower than
+ * iterating with the W3C API. We still use XPath because there is a small chance that the authors of the
+ * XML implementation in the JDK will not get forced by Larry to fix their ugly code and APIs. Yes, it'
+ * s unlikely but one can dream...
+ * </p>
+ *
+ * @author Christian Bauer
+ */
+public abstract class DOMElement<CHILD extends DOMElement, PARENT extends DOMElement> {
+
+ public final Builder<PARENT> PARENT_BUILDER;
+ public final ArrayBuilder<CHILD> CHILD_BUILDER;
+
+ private final XPath xpath;
+ private Element element;
+
+ public DOMElement(XPath xpath, Element element) {
+ this.xpath = xpath;
+ this.element = element;
+ this.PARENT_BUILDER = createParentBuilder(this);
+ this.CHILD_BUILDER = createChildBuilder(this);
+ }
+
+ public Element getW3CElement() {
+ return element;
+ }
+
+ public String getElementName() {
+ return getW3CElement().getNodeName();
+ }
+
+ public String getContent() {
+ return getW3CElement().getTextContent();
+ }
+
+ public DOMElement<CHILD, PARENT> setContent(String content) {
+ getW3CElement().setTextContent(content);
+ return this;
+ }
+
+ public String getAttribute(String attribute) {
+ String v = getW3CElement().getAttribute(attribute);
+ return v.length() > 0 ? v : null;
+ }
+
+ public DOMElement setAttribute(String attribute, String value) {
+ getW3CElement().setAttribute(attribute, value);
+ return this;
+ }
+
+ public PARENT getParent() {
+ return PARENT_BUILDER.build((Element) getW3CElement().getParentNode());
+ }
+
+ public CHILD[] getChildren() {
+ NodeList nodes = getW3CElement().getChildNodes();
+ List<CHILD> children = new ArrayList();
+ for (int i = 0; i < nodes.getLength(); i++) {
+ Node node = nodes.item(i);
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ children.add(CHILD_BUILDER.build((Element) node));
+ }
+ }
+ return children.toArray(CHILD_BUILDER.newChildrenArray(children.size()));
+ }
+
+ public CHILD[] getChildren(String name) {
+ Collection<CHILD> list = getXPathChildElements(CHILD_BUILDER, prefix(name));
+ return list.toArray(CHILD_BUILDER.newChildrenArray(list.size()));
+ }
+
+ public CHILD getRequiredChild(String name) throws ParserException {
+ CHILD[] children = getChildren(name);
+ if (children.length != 1) {
+ throw new ParserException("Required single child element of '" + getElementName() + "' not found: " + name);
+ }
+ return children[0];
+ }
+
+ public CHILD[] findChildren(String name) {
+ Collection<CHILD> list = getXPathChildElements(CHILD_BUILDER, "descendant::" + prefix(name));
+ return list.toArray(CHILD_BUILDER.newChildrenArray(list.size()));
+ }
+
+ public CHILD findChildWithIdentifier(final String id) {
+ Collection<CHILD> list = getXPathChildElements(CHILD_BUILDER, "descendant::" + prefix("*") + "[@id=\"" + id + "\"]");
+ if (list.size() == 1) return list.iterator().next();
+ return null;
+ }
+
+ public CHILD getFirstChild(String name) {
+ return getXPathChildElement(CHILD_BUILDER, prefix(name) + "[1]");
+ }
+
+ public CHILD createChild(String name) {
+ return createChild(name, null);
+ }
+
+ public CHILD createChild(String name, String namespaceURI) {
+ CHILD child = CHILD_BUILDER.build(
+ namespaceURI == null
+ ? getW3CElement().getOwnerDocument().createElement(name)
+ : getW3CElement().getOwnerDocument().createElementNS(namespaceURI, name)
+ );
+ getW3CElement().appendChild(child.getW3CElement());
+ return child;
+ }
+
+ public CHILD appendChild(CHILD el, boolean copy) {
+ el = adoptOrImport(getW3CElement().getOwnerDocument(), el, copy);
+ getW3CElement().appendChild(el.getW3CElement());
+ return el;
+ }
+
+ public CHILD replaceChild(CHILD original, CHILD replacement, boolean copy) {
+ replacement = adoptOrImport(getW3CElement().getOwnerDocument(), replacement, copy);
+ getW3CElement().replaceChild(replacement.getW3CElement(), original.getW3CElement());
+ return replacement;
+ }
+
+ public void replaceEqualChild(DOMElement source, String identifier) {
+ DOMElement original = findChildWithIdentifier(identifier);
+ DOMElement replacement = source.findChildWithIdentifier(identifier);
+ original.getParent().replaceChild(original, replacement, true);
+ }
+
+ public void removeChild(CHILD el) {
+ getW3CElement().removeChild(el.getW3CElement());
+ }
+
+ public void removeChildren() {
+ NodeList children = getW3CElement().getChildNodes();
+ for (int i = 0; i < children.getLength(); i++) {
+ Node child = children.item(i);
+ getW3CElement().removeChild(child);
+ }
+ }
+
+ protected CHILD adoptOrImport(Document document, CHILD child, boolean copy) {
+ if (document != null) {
+ if (copy) {
+ child = CHILD_BUILDER.build(
+ (Element) document.importNode(child.getW3CElement(), true)
+ );
+ } else {
+ child = CHILD_BUILDER.build(
+ (Element) document.adoptNode(child.getW3CElement())
+ );
+ }
+ }
+ return child;
+ }
+
+
+ protected abstract Builder<PARENT> createParentBuilder(DOMElement el);
+
+ protected abstract ArrayBuilder<CHILD> createChildBuilder(DOMElement el);
+
+ public String toSimpleXMLString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("<").append(getElementName());
+ NamedNodeMap map = getW3CElement().getAttributes();
+ for (int i = 0; i < map.getLength(); i++) {
+ Node attr = map.item(i);
+ sb.append(" ").append(attr.getNodeName()).append("=\"")
+ .append(attr.getTextContent()).append("\"");
+ }
+ if (getContent().length() > 0) {
+ sb.append(">").append(getContent()).append("</").append(getElementName()).append(">");
+ } else {
+ sb.append("/>");
+ }
+ return sb.toString();
+ }
+
+ @Override
+ public String toString() {
+ return "(" + getClass().getSimpleName() + ") " +
+ (getW3CElement() == null ? "UNBOUND" : getElementName());
+ }
+
+ public XPath getXpath() {
+ return xpath;
+ }
+
+ protected String prefix(String localName) {
+ return localName;
+ }
+
+ public Collection<PARENT> getXPathParentElements(Builder<CHILD> builder, String expr) {
+ return getXPathElements(builder, expr);
+ }
+
+ public Collection<CHILD> getXPathChildElements(Builder<CHILD> builder, String expr) {
+ return getXPathElements(builder, expr);
+ }
+
+ public PARENT getXPathParentElement(Builder<PARENT> builder, String expr) {
+ Node node = (Node) getXPathResult(getW3CElement(), expr, XPathConstants.NODE);
+ return node != null && node.getNodeType() == Node.ELEMENT_NODE ? builder.build((Element) node) : null;
+ }
+
+ public CHILD getXPathChildElement(Builder<CHILD> builder, String expr) {
+ Node node = (Node) getXPathResult(getW3CElement(), expr, XPathConstants.NODE);
+ return node != null && node.getNodeType() == Node.ELEMENT_NODE ? builder.build((Element) node) : null;
+ }
+
+ public Collection getXPathElements(Builder builder, String expr) {
+ Collection col = new ArrayList();
+ NodeList result = (NodeList) getXPathResult(getW3CElement(), expr, XPathConstants.NODESET);
+ for (int i = 0; i < result.getLength(); i++) {
+ DOMElement e = builder.build((Element) result.item(i));
+ col.add(e);
+ }
+ return col;
+ }
+
+ public String getXPathString(XPath xpath, String expr) {
+ return getXPathResult(getW3CElement(), expr, null).toString();
+ }
+
+ public Object getXPathResult(String expr, QName result) {
+ return getXPathResult(getW3CElement(), expr, result);
+ }
+
+ public Object getXPathResult(Node context, String expr, QName result) {
+ try {
+ //System.out.println("#### XPATH: " + expr + " CONTEXT: " + context.getAttributes().getNamedItem("id") + " EXPECTING: " + result);
+ if (result == null) {
+ return xpath.evaluate(expr, context);
+ }
+ return xpath.evaluate(expr, context, result);
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ public abstract class Builder<T extends DOMElement> {
+ public DOMElement element;
+
+ protected Builder(DOMElement element) {
+ this.element = element;
+ }
+
+ public abstract T build(Element element);
+
+ public T firstChildOrNull(String elementName) {
+ DOMElement el = element.getFirstChild(elementName);
+ return el != null ? build(el.getW3CElement()) : null;
+ }
+
+ }
+
+ public abstract class ArrayBuilder<T extends DOMElement> extends Builder<T> {
+
+ protected ArrayBuilder(DOMElement element) {
+ super(element);
+ }
+
+ public abstract T[] newChildrenArray(int length);
+
+ public T[] getChildElements() {
+ return buildArray(element.getChildren());
+ }
+
+ public T[] getChildElements(String elementName) {
+ return buildArray(element.getChildren(elementName));
+ }
+
+ protected T[] buildArray(DOMElement[] list) {
+ T[] children = newChildrenArray(list.length);
+ for (int i = 0; i < children.length; i++) {
+ children[i] = build(list[i].getW3CElement());
+ }
+ return children;
+ }
+ }
+
+}
diff --git a/container/src/main/java/org/openremote/container/xml/DOMParser.java b/container/src/main/java/org/openremote/container/xml/DOMParser.java
new file mode 100644
index 000000000..416fafe80
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/xml/DOMParser.java
@@ -0,0 +1,590 @@
+/*
+ * 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.xml;
+
+import org.w3c.dom.*;
+import org.xml.sax.*;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.namespace.QName;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.sax.SAXSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+import javax.xml.validation.Validator;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathFactory;
+import java.io.*;
+import java.net.URI;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Condensed API for parsing of XML into DOM with (optional) XML schema validation.
+ * <p>
+ * Provides many XML utility features, like pretty printing, escaping, or node visitor.
+ * </p>
+ * <p>
+ * NOTE: This class is not thread-safe because JAXP factories are not thread-safe!
+ * </p>
+ */
+public abstract class DOMParser<D extends DOM> implements ErrorHandler, EntityResolver {
+
+ private static final Logger LOG = Logger.getLogger(DOMParser.class.getName());
+
+ protected Source[] schemaSources;
+ protected Schema schema;
+
+ public DOMParser(Source... schemaSources) {
+ this.schemaSources = schemaSources;
+ }
+
+ public Schema getSchema() {
+
+ if (schema == null) {
+ // Lazy initialization
+ // TODO: http://stackoverflow.com/questions/3129934/schemafactory-doesnt-support-w3c-xml-schema-in-platform-level-8
+ try {
+ SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+
+ schemaFactory.setResourceResolver(new CatalogResourceResolver(
+ new HashMap<URI, URL>() {{
+ put(DOM.XML_SCHEMA_NAMESPACE, DOM.XML_SCHEMA_RESOURCE);
+ }}
+ ));
+
+ if (schemaSources != null) {
+ schema = schemaFactory.newSchema(schemaSources);
+ } else {
+ schema = schemaFactory.newSchema();
+ }
+
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+ return schema;
+ }
+
+ // =================================================================================================
+
+ protected abstract D createDOM(Document document);
+
+ public DocumentBuilderFactory createFactory(boolean validating) throws ParserException {
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+
+ try {
+
+ // Yes, namespaces would be nice... because they make XML sooooo eXtensible!
+ factory.setNamespaceAware(true);
+
+ if (validating) {
+
+ // Well this in theory works without validation but requires namespaces. We don't want
+ // namespaces when we are not validating because we get funny xmlns="" in output.
+ factory.setXIncludeAware(true);
+
+ // Whatever that does... we want it
+ factory.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false);
+ factory.setFeature("http://apache.org/xml/features/xinclude/fixup-language", false);
+
+ // Good idea to set a schema when you want to validate! Tell me, how does it work
+ // without a schema?!
+ factory.setSchema(getSchema());
+
+ // Oh, it's dynamic! Soooo dynamic! This is hilarious:
+ //
+ // "The parser will validate the document only if a grammar is specified."
+ //
+ // What, you are surprised that it won't validate without a grammar?!?! Well,
+ // I'm going to turn that smart feature on, of course! Seriously, it won't
+ // validate without this switch. And I'm so proud having 'apache.org' in my
+ // source, a true sign of quality.
+ //
+ factory.setFeature("http://apache.org/xml/features/validation/dynamic", true);
+ }
+
+ } catch (ParserConfigurationException ex) {
+ // Lovely, of course it couldn't have been a RuntimeException!
+ throw new ParserException(ex);
+ }
+ return factory;
+ }
+
+ public Transformer createTransformer(String method, int indent, boolean standalone) throws ParserException {
+ try {
+ TransformerFactory transFactory = TransformerFactory.newInstance();
+
+ if (indent > 0) {
+ try {
+ transFactory.setAttribute("indent-number", indent);
+ } catch (IllegalArgumentException ex) {
+ // Fuck you, Apache morons.
+ }
+ }
+
+ Transformer transformer = transFactory.newTransformer();
+ transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, standalone ? "no" : "yes");
+
+ // JDK 7 bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7150637
+ if (standalone) {
+ try {
+ transformer.setOutputProperty("http://www.oracle.com/xml/is-standalone", "yes");
+ } catch (IllegalArgumentException e) {
+ // Expected on older versions
+ }
+ }
+
+ transformer.setOutputProperty(OutputKeys.INDENT, indent > 0 ? "yes" : "no");
+ if (indent > 0)
+ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent));
+ transformer.setOutputProperty(OutputKeys.METHOD, method);
+
+ return transformer;
+ } catch (Exception ex) {
+ throw new ParserException(ex);
+ }
+ }
+
+ public D createDocument() {
+ try {
+ return createDOM(createFactory(false).newDocumentBuilder().newDocument());
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ // =================================================================================================
+
+ public D parse(URL url) throws ParserException {
+ return parse(url, true);
+ }
+
+ public D parse(String string) throws ParserException {
+ if (string == null)
+ throw new IllegalArgumentException("No file available");
+ return parse(string, true);
+ }
+
+ public D parse(File file) throws ParserException {
+ if (file == null)
+ throw new IllegalArgumentException("No file available");
+ return parse(file, true);
+ }
+
+ public D parse(InputStream stream) throws ParserException {
+ if (stream == null)
+ throw new IllegalArgumentException("No input stream available");
+ return parse(stream, true);
+ }
+
+ public D parse(URL url, boolean validate) throws ParserException {
+ if (url == null)
+ throw new IllegalArgumentException("Can't parse null URL");
+ try {
+ return parse(url.openStream(), validate);
+ } catch (Exception ex) {
+ throw new ParserException("Parsing URL failed: " + url, ex);
+ }
+ }
+
+ public D parse(String string, boolean validate) throws ParserException {
+ if (string == null)
+ throw new IllegalArgumentException("Can't parse null string");
+ return parse(new InputSource(new StringReader(string)), validate);
+ }
+
+ public D parse(File file, boolean validate) throws ParserException {
+ if (file == null)
+ throw new IllegalArgumentException("Can't parse null file");
+ try {
+ return parse(file.toURI().toURL(), validate);
+ } catch (Exception ex) {
+ throw new ParserException("Parsing file failed: " + file, ex);
+ }
+ }
+
+ public D parse(InputStream stream, boolean validate) throws ParserException {
+ if (stream == null)
+ throw new IllegalArgumentException("No file available");
+ return parse(new InputSource(stream), validate);
+ }
+
+ public D parse(InputSource source, boolean validate) throws ParserException {
+ try {
+
+ DocumentBuilder parser = createFactory(validate).newDocumentBuilder();
+
+ parser.setEntityResolver(this);
+
+ parser.setErrorHandler(this);
+
+ Document dom = parser.parse(source);
+
+ dom.normalizeDocument();
+
+ return createDOM(dom);
+
+ } catch (Exception ex) {
+ throw unwrapException(ex);
+ }
+ }
+
+ // =================================================================================================
+
+ public void validate(URL url) throws ParserException {
+ if (url == null) throw new IllegalArgumentException("Can't validate null URL");
+ LOG.fine("Validating XML of URL: " + url);
+ validate(new StreamSource(url.toString()));
+ }
+
+ public void validate(String string) throws ParserException {
+ if (string == null) throw new IllegalArgumentException("Can't validate null string");
+ LOG.fine("Validating XML string characters: " + string.length());
+ validate(new SAXSource(new InputSource(new StringReader(string))));
+ }
+
+ public void validate(Document document) throws ParserException {
+ validate(new DOMSource(document));
+ }
+
+ public void validate(DOM dom) throws ParserException {
+ validate(new DOMSource(dom.getW3CDocument()));
+ }
+
+ public void validate(Source source) throws ParserException {
+ try {
+ Validator validator = getSchema().newValidator();
+ validator.setErrorHandler(this);
+ validator.validate(source);
+ } catch (Exception ex) {
+ throw unwrapException(ex);
+ }
+ }
+
+ // =================================================================================================
+
+ public XPathFactory createXPathFactory() {
+ return XPathFactory.newInstance();
+ }
+
+ public XPath createXPath(NamespaceContext nsContext) {
+ XPath xpath = createXPathFactory().newXPath();
+ xpath.setNamespaceContext(nsContext);
+ return xpath;
+ }
+
+ public XPath createXPath(XPathFactory factory, NamespaceContext nsContext) {
+ XPath xpath = factory.newXPath();
+ xpath.setNamespaceContext(nsContext);
+ return xpath;
+ }
+
+ public Object getXPathResult(DOM dom, XPath xpath, String expr, QName result) {
+ return getXPathResult(dom.getW3CDocument(), xpath, expr, result);
+ }
+
+ public Object getXPathResult(DOMElement element, XPath xpath, String expr, QName result) {
+ return getXPathResult(element.getW3CElement(), xpath, expr, result);
+ }
+
+ public Object getXPathResult(Node context, XPath xpath, String expr, QName result) {
+ try {
+ LOG.fine("Evaluating xpath query: " + expr);
+ return xpath.evaluate(expr, context, result);
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ // =================================================================================================
+
+ public String print(DOM dom) throws ParserException {
+ return print(dom, 4, true);
+ }
+
+ public String print(DOM dom, int indent) throws ParserException {
+ return print(dom, indent, true);
+ }
+
+ public String print(DOM dom, boolean standalone) throws ParserException {
+ return print(dom, 4, standalone);
+ }
+
+ public String print(DOM dom, int indent, boolean standalone) throws ParserException {
+ return print(dom.getW3CDocument(), indent, standalone);
+ }
+
+ public String print(Document document, int indent, boolean standalone) throws ParserException {
+ removeIgnorableWSNodes(document.getDocumentElement());
+ return print(new DOMSource(document.getDocumentElement()), indent, standalone);
+ }
+
+ public String print(String string, int indent, boolean standalone) throws ParserException {
+ return print(new StreamSource(new StringReader(string)), indent, standalone);
+ }
+
+ public String print(Source source, int indent, boolean standalone) throws ParserException {
+ try {
+ Transformer transformer = createTransformer("xml", indent, standalone);
+ transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
+
+ StringWriter out = new StringWriter();
+ transformer.transform(source, new StreamResult(out));
+ out.flush();
+
+ return out.toString();
+
+ } catch (Exception e) {
+ throw new ParserException(e);
+ }
+ }
+
+ public String printHTML(Document dom) throws ParserException {
+ return printHTML(dom, 4, true, true);
+ }
+
+ // This prints XHTML into HTML that IE understands, and that validates with W3C rules
+
+ public String printHTML(Document dom, int indent, boolean standalone, boolean doctype) throws ParserException {
+
+ // Make a copy so we can remove stuff from the DOM that violates W3C when rendered as HTML (go figure!)
+ dom = (Document) dom.cloneNode(true);
+
+ // CDATA will be escaped by the transformer for HTML output but we
+ // need to copy it into text nodes (yes, I know XML is fantastic...)
+ accept(dom.getDocumentElement(), new NodeVisitor(Node.CDATA_SECTION_NODE) {
+ @Override
+ public void visit(Node node) {
+ CDATASection cdata = (CDATASection) node;
+ cdata.getParentNode().setTextContent(cdata.getData());
+ }
+ });
+
+ removeIgnorableWSNodes(dom.getDocumentElement());
+
+ try {
+ Transformer transformer = createTransformer("html", indent, standalone);
+
+ if (doctype) {
+ transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD HTML 4.01 Transitional//EN");
+ transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://www.w3.org/TR/html4/loose.dtd");
+ }
+
+ StringWriter out = new StringWriter();
+ transformer.transform(new DOMSource(dom), new StreamResult(out));
+ out.flush();
+ String output = out.toString();
+
+ // Rip out the idiotic META http-equiv tag - we have HTTP headers for that!
+ String meta = "\\s*<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">";
+ output = output.replaceFirst(meta, "");
+
+ // Rip out the even dumber xmlns attribute that magically got added (seems to be a difference between JDK 1.4 and 5)
+ String xmlns = "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
+ output = output.replaceFirst(xmlns, "<html>");
+
+ return output;
+
+ } catch (Exception ex) {
+ throw new ParserException(ex);
+ }
+ }
+
+ public void removeIgnorableWSNodes(Element element) {
+ Node nextNode = element.getFirstChild();
+ Node child;
+ while (nextNode != null) {
+ child = nextNode;
+ nextNode = child.getNextSibling();
+ if (isIgnorableWSNode(child)) {
+ element.removeChild(child);
+ } else if (child.getNodeType() == Node.ELEMENT_NODE) {
+ removeIgnorableWSNodes((Element) child);
+ }
+ }
+ }
+
+ public boolean isIgnorableWSNode(Node node) {
+ // TODO: What about XML space="preserve"?
+ return node.getNodeType() == Node.TEXT_NODE &&
+ node.getTextContent().matches("[\\t\\n\\x0B\\f\\r\\s]+");
+ }
+
+ // =================================================================================================
+
+ public void warning(SAXParseException e) throws SAXException {
+ LOG.warning(e.toString());
+ }
+
+ public void error(SAXParseException e) throws SAXException {
+ throw new SAXException(new ParserException(e));
+ }
+
+ public void fatalError(SAXParseException e) throws SAXException {
+ throw new SAXException(new ParserException(e));
+ }
+
+ protected ParserException unwrapException(Exception ex) {
+ // Another historic moment in Java XML API design!
+ if (ex.getCause() != null && ex.getCause() instanceof ParserException) {
+ return (ParserException) ex.getCause();
+ }
+ return new ParserException(ex);
+ }
+
+ // =================================================================================================
+
+ public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
+ // By default this builds an EntityResolver that _stays offline_.
+ // Damn you XML clowns, just because a URI looks like a URL does NOT mean you should fetch it!
+ InputSource is;
+ if (systemId.startsWith("file://")) {
+ is = new InputSource(new FileInputStream(new File(URI.create(systemId))));
+ } else {
+ is = new InputSource(new ByteArrayInputStream(new byte[0]));
+ }
+ is.setPublicId(publicId);
+ is.setSystemId(systemId);
+ return is;
+
+ }
+
+ // ======================================= Utility Methods =============================================
+
+ public static String escape(String string) {
+ return escape(string, false, false);
+ }
+
+ public static String escape(String string, boolean convertNewlines, boolean convertSpaces) {
+ if (string == null) return null;
+ StringBuilder sb = new StringBuilder();
+ String entity;
+ char c;
+ for (int i = 0; i < string.length(); ++i) {
+ entity = null;
+ c = string.charAt(i);
+ switch (c) {
+ case '<':
+ entity = "&#60;";
+ break;
+ case '>':
+ entity = "&#62;";
+ break;
+ case '&':
+ entity = "&#38;";
+ break;
+ case '"':
+ entity = "&#34;";
+ break;
+ }
+ if (entity != null) {
+ sb.append(entity);
+ } else {
+ sb.append(c);
+ }
+ }
+ String result = sb.toString();
+ if (convertSpaces) {
+ // Converts the _beginning_ of line whitespaces into non-breaking spaces
+ Matcher matcher = Pattern.compile("(\\n+)(\\s*)(.*)").matcher(result);
+ StringBuffer temp = new StringBuffer();
+ while (matcher.find()) {
+ String group = matcher.group(2);
+ StringBuilder spaces = new StringBuilder();
+ for (int i = 0; i < group.length(); i++) {
+ spaces.append("&#160;");
+ }
+ matcher.appendReplacement(temp, "$1" + spaces.toString() + "$3");
+ }
+ matcher.appendTail(temp);
+ result = temp.toString();
+ }
+ if (convertNewlines) {
+ result = result.replaceAll("\n", "<br/>");
+ }
+ return result;
+ }
+
+ public static String stripElements(String xml) {
+ if (xml == null) return null;
+ return xml.replaceAll("<([a-zA-Z]|/).*?>", "");
+ }
+
+ public static void accept(Node node, NodeVisitor visitor) {
+ if (node == null) return;
+ if (visitor.isHalted()) return;
+ NodeList children = node.getChildNodes();
+ for (int i = 0; i < children.getLength(); i++) {
+ Node child = children.item(i);
+ boolean cont = true;
+ if (child.getNodeType() == visitor.nodeType) {
+ visitor.visit(child);
+ if (visitor.isHalted()) break;
+ }
+ accept(child, visitor);
+ }
+ }
+
+ public static abstract class NodeVisitor {
+ private short nodeType;
+
+ protected NodeVisitor(short nodeType) {
+ assert nodeType < Node.NOTATION_NODE; // All other node types are below
+ this.nodeType = nodeType;
+ }
+
+ public boolean isHalted() {
+ return false;
+ }
+
+ public abstract void visit(Node node);
+ }
+
+ public static String wrap(String wrapperName, String fragment) {
+ return wrap(wrapperName, null, fragment);
+ }
+
+ public static String wrap(String wrapperName, String xmlns, String fragment) {
+ StringBuilder wrapper = new StringBuilder();
+ wrapper.append("<").append(wrapperName);
+ if (xmlns != null) {
+ wrapper.append(" xmlns=\"").append(xmlns).append("\"");
+ }
+ wrapper.append(">");
+ wrapper.append(fragment);
+ wrapper.append("</").append(wrapperName).append(">");
+ return wrapper.toString();
+ }
+
+}
diff --git a/container/src/main/java/org/openremote/container/xml/NamespaceContextMap.java b/container/src/main/java/org/openremote/container/xml/NamespaceContextMap.java
new file mode 100644
index 000000000..1ff6c42f5
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/xml/NamespaceContextMap.java
@@ -0,0 +1,61 @@
+/*
+ * 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.xml;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.NamespaceContext;
+import java.util.HashMap;
+import java.util.Iterator;
+
+/**
+ * This should have been part of the JDK.
+ * <p>
+ * The dumb XPath API needs a map to lookup namespace URIs using prefix keys. Unfortunately,
+ * the authors did not know <tt>java.util.Map</tt>.
+ * </p>
+ *
+ * @author Christian Bauer
+ */
+public abstract class NamespaceContextMap extends HashMap<String, String> implements NamespaceContext {
+
+ public String getNamespaceURI(String prefix) {
+ if (prefix == null) {
+ throw new IllegalArgumentException("No prefix provided!");
+ } else if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
+ return getDefaultNamespaceURI();
+ } else if (get(prefix) != null) {
+ return get(prefix);
+ } else {
+ return XMLConstants.NULL_NS_URI;
+ }
+ }
+
+ // Whatever, we don't care
+ public String getPrefix(String namespaceURI) {
+ return null;
+ }
+
+ // Whatever, we don't care
+ public Iterator getPrefixes(String s) {
+ return null;
+ }
+
+ protected abstract String getDefaultNamespaceURI();
+}
diff --git a/container/src/main/java/org/openremote/container/xml/ParserException.java b/container/src/main/java/org/openremote/container/xml/ParserException.java
new file mode 100644
index 000000000..351b478b5
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/xml/ParserException.java
@@ -0,0 +1,47 @@
+/*
+ * 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.xml;
+
+import org.xml.sax.SAXParseException;
+
+/**
+ * Unified exception thrown by the <tt>DOMParser</tt> and <tt>SAXParser</tt>.
+ */
+public class ParserException extends Exception {
+
+ public ParserException() {
+ }
+
+ public ParserException(String s) {
+ super(s);
+ }
+
+ public ParserException(String s, Throwable throwable) {
+ super(s, throwable);
+ }
+
+ public ParserException(Throwable throwable) {
+ super(throwable);
+ }
+
+ public ParserException(SAXParseException ex) {
+ super("(Line/Column: " + ex.getLineNumber() + ":" + ex.getColumnNumber() + ") " + ex.getMessage());
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/xml/SAXParser.java b/container/src/main/java/org/openremote/container/xml/SAXParser.java
new file mode 100644
index 000000000..992c7b26b
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/xml/SAXParser.java
@@ -0,0 +1,208 @@
+/*
+ * 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.xml;
+
+import org.xml.sax.*;
+import org.xml.sax.helpers.AttributesImpl;
+import org.xml.sax.helpers.DefaultHandler;
+import org.xml.sax.helpers.XMLReaderFactory;
+
+import javax.xml.XMLConstants;
+import javax.xml.parsers.SAXParserFactory;
+import javax.xml.transform.Source;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+import java.net.URI;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.logging.Logger;
+
+public class SAXParser {
+
+ private static final Logger LOG = Logger.getLogger(SAXParser.class.getName());
+
+ final private XMLReader xr;
+
+ public SAXParser() {
+ this(null);
+ }
+
+ public SAXParser(DefaultHandler handler) {
+ this.xr = create();
+ if (handler != null)
+ xr.setContentHandler(handler);
+ }
+
+ public void setContentHandler(ContentHandler handler) {
+ xr.setContentHandler(handler);
+ }
+
+ protected XMLReader create() {
+ try {
+ if (getSchemaSources() != null) {
+ // Jump through all the hoops and create a validating reader
+ SAXParserFactory factory = SAXParserFactory.newInstance();
+ factory.setNamespaceAware(true);
+ factory.setSchema(createSchema(getSchemaSources()));
+ XMLReader xmlReader = factory.newSAXParser().getXMLReader();
+ xmlReader.setErrorHandler(getErrorHandler());
+ return xmlReader;
+ }
+ return XMLReaderFactory.createXMLReader();
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ protected Schema createSchema(Source[] schemaSources) {
+ try {
+ SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+ schemaFactory.setResourceResolver(new CatalogResourceResolver(
+ new HashMap<URI, URL>() {{
+ put(DOM.XML_SCHEMA_NAMESPACE, DOM.XML_SCHEMA_RESOURCE);
+ }}
+ ));
+ return schemaFactory.newSchema(schemaSources);
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ protected Source[] getSchemaSources() {
+ return null;
+ }
+
+ protected ErrorHandler getErrorHandler() {
+ return new SimpleErrorHandler();
+ }
+
+ public void parse(InputSource source) throws ParserException {
+ try {
+ xr.parse(source);
+ } catch (Exception ex) {
+ throw new ParserException(ex);
+ }
+ }
+
+ /**
+ * Always throws exceptions and stops parsing.
+ */
+ public class SimpleErrorHandler implements ErrorHandler {
+ public void warning(SAXParseException e) throws SAXException {
+ throw new SAXException(e);
+ }
+
+ public void error(SAXParseException e) throws SAXException {
+ throw new SAXException(e);
+ }
+
+ public void fatalError(SAXParseException e) throws SAXException {
+ throw new SAXException(e);
+ }
+ }
+
+ public static class Handler<I> extends DefaultHandler {
+
+ protected SAXParser parser;
+ protected I instance;
+ protected Handler parent;
+ protected StringBuilder characters = new StringBuilder();
+ protected Attributes attributes;
+
+ public Handler(I instance) {
+ this(instance, null, null);
+ }
+
+ public Handler(I instance, SAXParser parser) {
+ this(instance, parser, null);
+ }
+
+ public Handler(I instance, Handler parent) {
+ this(instance, parent.getParser(), parent);
+ }
+
+ public Handler(I instance, SAXParser parser, Handler parent) {
+ this.instance = instance;
+ this.parser = parser;
+ this.parent = parent;
+ if (parser != null) {
+ parser.setContentHandler(this);
+ }
+ }
+
+ public I getInstance() {
+ return instance;
+ }
+
+ public SAXParser getParser() {
+ return parser;
+ }
+
+ public Handler getParent() {
+ return parent;
+ }
+
+ protected void switchToParent() {
+ if (parser != null && parent != null) {
+ parser.setContentHandler(parent);
+ attributes = null;
+ }
+ }
+
+ public String getCharacters() {
+ return characters.toString();
+ }
+
+ @Override
+ public void startElement(String uri, String localName, String qName,
+ Attributes attributes) throws SAXException {
+ this.characters = new StringBuilder();
+ this.attributes = new AttributesImpl(attributes); // see http://docstore.mik.ua/orelly/xml/sax2/ch05_01.htm, section 5.1.1
+ LOG.fine(getClass().getSimpleName() + " starting: " + localName);
+ }
+
+ @Override
+ public void characters(char[] ch, int start, int length) throws SAXException {
+ characters.append(ch, start, length);
+ }
+
+ @Override
+ public void endElement(String uri, String localName,
+ String qName) throws SAXException {
+
+ if (isLastElement(uri, localName, qName)) {
+ LOG.fine(getClass().getSimpleName() + ": last element, switching to parent: " + localName);
+ switchToParent();
+ return;
+ }
+
+ LOG.fine(getClass().getSimpleName() + " ending: " + localName);
+ }
+
+ protected boolean isLastElement(String uri, String localName, String qName) {
+ return false;
+ }
+
+ protected Attributes getAttributes() {
+ return attributes;
+ }
+ }
+
+}
diff --git a/container/src/main/resources/org.openremote.schemas/xml.xsd b/container/src/main/resources/org.openremote.schemas/xml.xsd
new file mode 100644
index 000000000..1163623f5
--- /dev/null
+++ b/container/src/main/resources/org.openremote.schemas/xml.xsd
@@ -0,0 +1,287 @@
+<?xml version='1.0'?>
+<?xml-stylesheet href="../2008/09/xsd.xsl" type="text/xsl"?>
+<xs:schema targetNamespace="http://www.w3.org/XML/1998/namespace"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ xmlns ="http://www.w3.org/1999/xhtml"
+ xml:lang="en">
+
+ <xs:annotation>
+ <xs:documentation>
+ <div>
+ <h1>About the XML namespace</h1>
+
+ <div class="bodytext">
+ <p>
+ This schema document describes the XML namespace, in a form
+ suitable for import by other schema documents.
+ </p>
+ <p>
+ See <a href="http://www.w3.org/XML/1998/namespace.html">
+ http://www.w3.org/XML/1998/namespace.html</a> and
+ <a href="http://www.w3.org/TR/REC-xml">
+ http://www.w3.org/TR/REC-xml</a> for information
+ about this namespace.
+ </p>
+ <p>
+ Note that local names in this namespace are intended to be
+ defined only by the World Wide Web Consortium or its subgroups.
+ The names currently defined in this namespace are listed below.
+ They should not be used with conflicting semantics by any Working
+ Group, specification, or document instance.
+ </p>
+ <p>
+ See further below in this document for more information about <a
+ href="#usage">how to refer to this schema document from your own
+ XSD schema documents</a> and about <a href="#nsversioning">the
+ namespace-versioning policy governing this schema document</a>.
+ </p>
+ </div>
+ </div>
+ </xs:documentation>
+ </xs:annotation>
+
+ <xs:attribute name="lang">
+ <xs:annotation>
+ <xs:documentation>
+ <div>
+
+ <h3>lang (as an attribute name)</h3>
+ <p>
+ denotes an attribute whose value
+ is a language code for the natural language of the content of
+ any element; its value is inherited. This name is reserved
+ by virtue of its definition in the XML specification.</p>
+
+ </div>
+ <div>
+ <h4>Notes</h4>
+ <p>
+ Attempting to install the relevant ISO 2- and 3-letter
+ codes as the enumerated possible values is probably never
+ going to be a realistic possibility.
+ </p>
+ <p>
+ See BCP 47 at <a href="http://www.rfc-editor.org/rfc/bcp/bcp47.txt">
+ http://www.rfc-editor.org/rfc/bcp/bcp47.txt</a>
+ and the IANA language subtag registry at
+ <a href="http://www.iana.org/assignments/language-subtag-registry">
+ http://www.iana.org/assignments/language-subtag-registry</a>
+ for further information.
+ </p>
+ <p>
+ The union allows for the 'un-declaration' of xml:lang with
+ the empty string.
+ </p>
+ </div>
+ </xs:documentation>
+ </xs:annotation>
+ <xs:simpleType>
+ <xs:union memberTypes="xs:language">
+ <xs:simpleType>
+ <xs:restriction base="xs:string">
+ <xs:enumeration value=""/>
+ </xs:restriction>
+ </xs:simpleType>
+ </xs:union>
+ </xs:simpleType>
+ </xs:attribute>
+
+ <xs:attribute name="space">
+ <xs:annotation>
+ <xs:documentation>
+ <div>
+
+ <h3>space (as an attribute name)</h3>
+ <p>
+ denotes an attribute whose
+ value is a keyword indicating what whitespace processing
+ discipline is intended for the content of the element; its
+ value is inherited. This name is reserved by virtue of its
+ definition in the XML specification.</p>
+
+ </div>
+ </xs:documentation>
+ </xs:annotation>
+ <xs:simpleType>
+ <xs:restriction base="xs:NCName">
+ <xs:enumeration value="default"/>
+ <xs:enumeration value="preserve"/>
+ </xs:restriction>
+ </xs:simpleType>
+ </xs:attribute>
+
+ <xs:attribute name="base" type="xs:anyURI"> <xs:annotation>
+ <xs:documentation>
+ <div>
+
+ <h3>base (as an attribute name)</h3>
+ <p>
+ denotes an attribute whose value
+ provides a URI to be used as the base for interpreting any
+ relative URIs in the scope of the element on which it
+ appears; its value is inherited. This name is reserved
+ by virtue of its definition in the XML Base specification.</p>
+
+ <p>
+ See <a
+ href="http://www.w3.org/TR/xmlbase/">http://www.w3.org/TR/xmlbase/</a>
+ for information about this attribute.
+ </p>
+ </div>
+ </xs:documentation>
+ </xs:annotation>
+ </xs:attribute>
+
+ <xs:attribute name="id" type="xs:ID">
+ <xs:annotation>
+ <xs:documentation>
+ <div>
+
+ <h3>id (as an attribute name)</h3>
+ <p>
+ denotes an attribute whose value
+ should be interpreted as if declared to be of type ID.
+ This name is reserved by virtue of its definition in the
+ xml:id specification.</p>
+
+ <p>
+ See <a
+ href="http://www.w3.org/TR/xml-id/">http://www.w3.org/TR/xml-id/</a>
+ for information about this attribute.
+ </p>
+ </div>
+ </xs:documentation>
+ </xs:annotation>
+ </xs:attribute>
+
+ <xs:attributeGroup name="specialAttrs">
+ <xs:attribute ref="xml:base"/>
+ <xs:attribute ref="xml:lang"/>
+ <xs:attribute ref="xml:space"/>
+ <xs:attribute ref="xml:id"/>
+ </xs:attributeGroup>
+
+ <xs:annotation>
+ <xs:documentation>
+ <div>
+
+ <h3>Father (in any context at all)</h3>
+
+ <div class="bodytext">
+ <p>
+ denotes Jon Bosak, the chair of
+ the original XML Working Group. This name is reserved by
+ the following decision of the W3C XML Plenary and
+ XML Coordination groups:
+ </p>
+ <blockquote>
+ <p>
+ In appreciation for his vision, leadership and
+ dedication the W3C XML Plenary on this 10th day of
+ February, 2000, reserves for Jon Bosak in perpetuity
+ the XML name "xml:Father".
+ </p>
+ </blockquote>
+ </div>
+ </div>
+ </xs:documentation>
+ </xs:annotation>
+
+ <xs:annotation>
+ <xs:documentation>
+ <div xml:id="usage" id="usage">
+ <h2><a name="usage">About this schema document</a></h2>
+
+ <div class="bodytext">
+ <p>
+ This schema defines attributes and an attribute group suitable
+ for use by schemas wishing to allow <code>xml:base</code>,
+ <code>xml:lang</code>, <code>xml:space</code> or
+ <code>xml:id</code> attributes on elements they define.
+ </p>
+ <p>
+ To enable this, such a schema must import this schema for
+ the XML namespace, e.g. as follows:
+ </p>
+ <pre>
+ &lt;schema . . .>
+ . . .
+ &lt;import namespace="http://www.w3.org/XML/1998/namespace"
+ schemaLocation="http://www.w3.org/2001/xml.xsd"/>
+ </pre>
+ <p>
+ or
+ </p>
+ <pre>
+ &lt;import namespace="http://www.w3.org/XML/1998/namespace"
+ schemaLocation="http://www.w3.org/2009/01/xml.xsd"/>
+ </pre>
+ <p>
+ Subsequently, qualified reference to any of the attributes or the
+ group defined below will have the desired effect, e.g.
+ </p>
+ <pre>
+ &lt;type . . .>
+ . . .
+ &lt;attributeGroup ref="xml:specialAttrs"/>
+ </pre>
+ <p>
+ will define a type which will schema-validate an instance element
+ with any of those attributes.
+ </p>
+ </div>
+ </div>
+ </xs:documentation>
+ </xs:annotation>
+
+ <xs:annotation>
+ <xs:documentation>
+ <div id="nsversioning" xml:id="nsversioning">
+ <h2><a name="nsversioning">Versioning policy for this schema document</a></h2>
+ <div class="bodytext">
+ <p>
+ In keeping with the XML Schema WG's standard versioning
+ policy, this schema document will persist at
+ <a href="http://www.w3.org/2009/01/xml.xsd">
+ http://www.w3.org/2009/01/xml.xsd</a>.
+ </p>
+ <p>
+ At the date of issue it can also be found at
+ <a href="http://www.w3.org/2001/xml.xsd">
+ http://www.w3.org/2001/xml.xsd</a>.
+ </p>
+ <p>
+ The schema document at that URI may however change in the future,
+ in order to remain compatible with the latest version of XML
+ Schema itself, or with the XML namespace itself. In other words,
+ if the XML Schema or XML namespaces change, the version of this
+ document at <a href="http://www.w3.org/2001/xml.xsd">
+ http://www.w3.org/2001/xml.xsd
+ </a>
+ will change accordingly; the version at
+ <a href="http://www.w3.org/2009/01/xml.xsd">
+ http://www.w3.org/2009/01/xml.xsd
+ </a>
+ will not change.
+ </p>
+ <p>
+ Previous dated (and unchanging) versions of this schema
+ document are at:
+ </p>
+ <ul>
+ <li><a href="http://www.w3.org/2009/01/xml.xsd">
+ http://www.w3.org/2009/01/xml.xsd</a></li>
+ <li><a href="http://www.w3.org/2007/08/xml.xsd">
+ http://www.w3.org/2007/08/xml.xsd</a></li>
+ <li><a href="http://www.w3.org/2004/10/xml.xsd">
+ http://www.w3.org/2004/10/xml.xsd</a></li>
+ <li><a href="http://www.w3.org/2001/03/xml.xsd">
+ http://www.w3.org/2001/03/xml.xsd</a></li>
+ </ul>
+ </div>
+ </div>
+ </xs:documentation>
+ </xs:annotation>
+
+</xs:schema>
+
diff --git a/controller/build.gradle b/controller/build.gradle
index 21918c672..e9c725d18 100644
--- a/controller/build.gradle
+++ b/controller/build.gradle
@@ -11,6 +11,8 @@ dependencies {
compile "org.drools:drools-compiler:6.5.0.Final"
compile "org.drools:drools-decisiontables:6.5.0.Final"
+ compile "com.luckycatlabs:SunriseSunsetCalculator:$sunriseSunsetCalculatorVersion"
+
testCompile "junit:junit:$junitVersion"
testCompile "org.spockframework:spock-core:$spockVersion"
}
diff --git a/controller/src/main/java/org/openremote/controller/ControllerService.java b/controller/src/main/java/org/openremote/controller/ControllerService.java
index 83dcd1389..ae641ed1d 100644
--- a/controller/src/main/java/org/openremote/controller/ControllerService.java
+++ b/controller/src/main/java/org/openremote/controller/ControllerService.java
@@ -2,34 +2,62 @@ package org.openremote.controller;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
+import org.openremote.controller.command.CommandFactory;
+import org.openremote.controller.deploy.ControllerDOM;
+import org.openremote.controller.deploy.ControllerDOMParser;
+import org.openremote.controller.event.EventProcessor;
import org.openremote.controller.event.EventProcessorChain;
+import org.openremote.controller.event.facade.CommandFacade;
+import org.openremote.controller.model.Deployment;
+import org.openremote.controller.model.Sensor;
import org.openremote.controller.statuscache.ChangedStatusTable;
import org.openremote.controller.statuscache.StatusCache;
+import java.io.InputStream;
+
public class ControllerService implements ContainerService {
- final protected EventProcessorChain eventProcessorChain;
+ final protected ControllerDOMParser controllerDOMParser = new ControllerDOMParser();
+
+ final protected InputStream deploymentXml;
+ final protected CommandFactory commandFactory;
+ final protected EventProcessor[] eventProcessors;
+ protected ControllerDOM controllerDOM;
+ protected Deployment deployment;
+ protected CommandFacade commandFacade;
protected StatusCache cache;
- public ControllerService(EventProcessorChain eventProcessorChain) {
- this.eventProcessorChain =eventProcessorChain;
+ public ControllerService(InputStream deploymentXml, CommandFactory commandFactory, EventProcessor[] eventProcessors) {
+ this.deploymentXml = deploymentXml;
+ this.commandFactory = commandFactory;
+ this.eventProcessors = eventProcessors;
}
@Override
public void init(Container container) throws Exception {
+ controllerDOM = controllerDOMParser.parse(deploymentXml, true);
}
@Override
public void configure(Container container) throws Exception {
+ deployment = new Deployment(controllerDOM, commandFactory);
+
+ commandFacade = new CommandFacade(deployment);
+ EventProcessorChain eventProcessorChain = new EventProcessorChain(commandFacade, eventProcessors);
+
ChangedStatusTable changeStatusTable = new ChangedStatusTable();
cache = new StatusCache(changeStatusTable, eventProcessorChain);
}
@Override
public void start(Container container) throws Exception {
- if (cache != null)
+ if (cache != null) {
cache.start();
+ for (Sensor sensor : deployment.getSensors()) {
+ cache.registerAndStartSensor(sensor);
+ }
+ }
}
@Override
@@ -39,6 +67,14 @@ public class ControllerService implements ContainerService {
}
}
+ public Deployment getDeployment() {
+ return deployment;
+ }
+
+ public CommandFacade getCommandFacade() {
+ return commandFacade;
+ }
+
public StatusCache getCache() {
return cache;
}
diff --git a/controller/src/main/java/org/openremote/controller/command/CommandFactory.java b/controller/src/main/java/org/openremote/controller/command/CommandFactory.java
new file mode 100644
index 000000000..cd736301a
--- /dev/null
+++ b/controller/src/main/java/org/openremote/controller/command/CommandFactory.java
@@ -0,0 +1,25 @@
+package org.openremote.controller.command;
+
+import org.openremote.controller.command.builtin.DateTimeCommand;
+import org.openremote.controller.command.builtin.VirtualCommand;
+import org.openremote.controller.model.CommandDefinition;
+
+/**
+ * Build protocol- and device-specific command implementation.
+ */
+public class CommandFactory {
+
+ public Command build(CommandDefinition commandDefinition) {
+
+ // Handle some built-in protocols
+ switch (commandDefinition.getProtocolType()) {
+ case "virtual":
+ return new VirtualCommand(commandDefinition);
+ case "datetime":
+ return new DateTimeCommand(commandDefinition);
+ }
+
+ return null;
+ }
+
+}
diff --git a/controller/src/main/java/org/openremote/controller/command/ExecutableCommandFactory.java b/controller/src/main/java/org/openremote/controller/command/ExecutableCommandFactory.java
deleted file mode 100644
index ecf906da9..000000000
--- a/controller/src/main/java/org/openremote/controller/command/ExecutableCommandFactory.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package org.openremote.controller.command;
-
-import org.openremote.controller.model.CommandDefinition;
-
-public abstract class ExecutableCommandFactory {
-
- public ExecutableCommand 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 ExecutableCommand buildCommand(CommandDefinition commandDefinition);
-}
diff --git a/controller/src/main/java/org/openremote/controller/command/PullCommand.java b/controller/src/main/java/org/openremote/controller/command/PullCommand.java
index b1859b7bf..bb39018e4 100644
--- a/controller/src/main/java/org/openremote/controller/command/PullCommand.java
+++ b/controller/src/main/java/org/openremote/controller/command/PullCommand.java
@@ -2,24 +2,24 @@ package org.openremote.controller.command;
import org.openremote.controller.model.Sensor;
-public abstract class PullCommand implements EventProducerCommand {
+public interface PullCommand extends EventProducerCommand {
- public final static int POLLING_INTERVAL = 500;
+ int POLLING_INTERVAL = 500;
/**
* Read a device status and translate it to a sensor's datatype.
*/
- public abstract String read(Sensor sensor);
+ 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.
+ * Used by {@link Sensor} 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() {
+ default 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.java
index fb450f37e..389b0a52f 100644
--- a/controller/src/main/java/org/openremote/controller/command/PushCommand.java
+++ b/controller/src/main/java/org/openremote/controller/command/PushCommand.java
@@ -10,15 +10,11 @@ import org.openremote.controller.model.Sensor;
* 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
+ * Push command implementations use the sensor
* {@link org.openremote.controller.model.Sensor#update} method to push state changes
* into the controller, as shown in the example below:
*
@@ -61,18 +57,20 @@ import org.openremote.controller.model.Sensor;
* 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
+ * This method may be invoked multiple times if the command instance is associated
+ * with several sensors. How many instances of the command exist and how multiple
+ * associations are handled is the responsibility of the command/factory implementation.
*/
- void setSensor(Sensor sensor);
+ void start(Sensor sensor);
+ /**
+ * This method may be invoked multiple times if the command instance is associated
+ * with several sensors. How many instances of the command exist and how multiple
+ * associations are handled is the responsibility of the command/factory implementation.
+ */
void stop(Sensor sensor);
}
diff --git a/controller/src/main/java/org/openremote/controller/command/builtin/DateTimeCommand.java b/controller/src/main/java/org/openremote/controller/command/builtin/DateTimeCommand.java
new file mode 100644
index 000000000..9a99fb397
--- /dev/null
+++ b/controller/src/main/java/org/openremote/controller/command/builtin/DateTimeCommand.java
@@ -0,0 +1,208 @@
+package org.openremote.controller.command.builtin;
+
+import com.luckycatlabs.sunrisesunset.SunriseSunsetCalculator;
+import com.luckycatlabs.sunrisesunset.dto.Location;
+import org.openremote.container.util.TextUtil;
+import org.openremote.controller.command.PushCommand;
+import org.openremote.controller.model.CommandDefinition;
+import org.openremote.controller.model.Sensor;
+
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.TimeZone;
+import java.util.logging.Logger;
+
+/**
+ * DateTime commands can be used to display date or time on the console
+ * or use certain DateTime events to trigger rules. To calculate sunrise and sunset the location has to be given as longitude, latidude
+ * and timezone. Timezone is the string identifier which is available in Java eg. Europe/Berlin
+ * <p>
+ * The following commands are available in the moment:
+ * - date (returns a date/time as string depending on the given formatter)
+ * - sunrise (returns the sunrise time as string depending on the given formatter)
+ * - sunset (returns the sunset time as string depending on the given formatter)
+ * - minutesUntilSunrise (returns an integer with the minutes until sunrise)
+ * - minutesUntilSunset (returns an integer with the minutes until sunset)
+ * - isDay (returns a boolean string)
+ * - isNight (returns a boolean string)
+ *
+ * @author Marcus
+ */
+public class DateTimeCommand implements PushCommand, Runnable {
+
+ private static final Logger LOG = Logger.getLogger(DateTimeCommand.class.getName());
+
+ private TimeZone timezone;
+ private String command;
+ private SimpleDateFormat dateFormatter;
+ private SunriseSunsetCalculator calculator;
+
+ /**
+ * The polling interval which is used for the sensor update thread
+ */
+ private Integer pollingInterval;
+
+ private Thread pollingThread;
+ private Sensor sensor;
+
+ boolean doPoll = false;
+
+
+ public DateTimeCommand(CommandDefinition commandDefinition) {
+ this(
+ commandDefinition.getProperty("latitude"),
+ commandDefinition.getProperty("longitude"),
+ commandDefinition.getProperty("timezone"),
+ commandDefinition.getProperty("command"),
+ commandDefinition.getProperty("format"),
+ TextUtil.convertPollingIntervalString(commandDefinition.getProperty("pollingInterval", "60000"))
+ );
+ }
+
+ public DateTimeCommand(String latitude, String longitude, String timezone, String command, String format, Integer pollingInterval) {
+
+ if (command.equals("sunrise") || command.equals("sunset") || command.equals("minutesUntilSunrise")
+ || command.equals("minutesUntilSunset") || command.equals("isDay") || command.equals("isNight")) {
+ if (null == longitude || null == latitude) {
+ throw new IllegalArgumentException("Unable to create DateTime command for sunrise/sunset related command, " +
+ "missing configuration parameter(s)");
+ }
+ }
+
+ if (timezone == null) {
+ this.timezone = TimeZone.getDefault();
+ } else {
+ this.timezone = TimeZone.getTimeZone(timezone);
+ }
+
+ if (format != null) {
+ dateFormatter = new SimpleDateFormat(format);
+ } else {
+ dateFormatter = new SimpleDateFormat();
+ }
+
+ dateFormatter.setTimeZone(this.timezone);
+
+ this.command = command;
+ this.pollingInterval = pollingInterval;
+
+ if (!command.equalsIgnoreCase("date")) {
+ Location location = new Location(latitude, longitude);
+ this.calculator = new SunriseSunsetCalculator(location, timezone);
+ LOG.fine(
+ "DaylightCalculatorCommand created with values latitude=" + latitude + ", longitude=" + longitude + ", timezone=" + timezone
+ );
+ }
+ }
+
+ public String calculateData() {
+ if (command.equalsIgnoreCase("date")) {
+ return dateFormatter.format(Calendar.getInstance(this.timezone).getTime());
+ } else if (command.equalsIgnoreCase("sunrise")) {
+ Calendar now = Calendar.getInstance(timezone);
+ Calendar officialSunriseDate = calculator.getOfficialSunriseCalendarForDate(now);
+ return dateFormatter.format(officialSunriseDate.getTime());
+ } else if (command.equalsIgnoreCase("sunset")) {
+ Calendar now = Calendar.getInstance(timezone);
+ Calendar officialSunsetDate = calculator.getOfficialSunsetCalendarForDate(now);
+ return dateFormatter.format(officialSunsetDate.getTime());
+ } else if (command.equalsIgnoreCase("minutesUntilSunrise")) {
+ Calendar now = Calendar.getInstance(timezone);
+ Calendar officialSunriseDate = calculator.getOfficialSunriseCalendarForDate(now);
+ if (now.after(officialSunriseDate)) {
+ Calendar tomorrow = (Calendar) now.clone();
+ tomorrow.add(Calendar.DAY_OF_YEAR, 1);
+ officialSunriseDate = calculator.getOfficialSunriseCalendarForDate(tomorrow);
+ }
+ int daysUntilSunrise = officialSunriseDate.get(Calendar.DAY_OF_YEAR) - now.get(Calendar.DAY_OF_YEAR);
+ int hoursUntilSunrise = officialSunriseDate.get(Calendar.HOUR_OF_DAY) - now.get(Calendar.HOUR_OF_DAY);
+ int minutesUntilSunrise = officialSunriseDate.get(Calendar.MINUTE) - now.get(Calendar.MINUTE);
+ return Integer.toString((daysUntilSunrise * 24 * 60) + (hoursUntilSunrise * 60) + minutesUntilSunrise);
+ } else if (command.equalsIgnoreCase("minutesUntilSunset")) {
+ Calendar now = Calendar.getInstance(timezone);
+ Calendar officialSunsetDate = calculator.getOfficialSunsetCalendarForDate(now);
+ if (now.after(officialSunsetDate)) {
+ Calendar tomorrow = (Calendar) now.clone();
+ tomorrow.add(Calendar.DAY_OF_YEAR, 1);
+ officialSunsetDate = calculator.getOfficialSunsetCalendarForDate(tomorrow);
+ }
+ int daysUntilSunset = officialSunsetDate.get(Calendar.DAY_OF_YEAR) - now.get(Calendar.DAY_OF_YEAR);
+ int hoursUntilSunset = officialSunsetDate.get(Calendar.HOUR_OF_DAY) - now.get(Calendar.HOUR_OF_DAY);
+ int minutesUntilSunset = officialSunsetDate.get(Calendar.MINUTE) - now.get(Calendar.MINUTE);
+ return Integer.toString((daysUntilSunset * 24 * 60) + (hoursUntilSunset * 60) + minutesUntilSunset);
+ } else if (command.equalsIgnoreCase("isDay")) {
+ Calendar now = Calendar.getInstance(timezone);
+ Calendar officialSunriseDate = calculator.getOfficialSunriseCalendarForDate(now);
+ Calendar officialSunsetDate = calculator.getOfficialSunsetCalendarForDate(now);
+ if (now.after(officialSunriseDate) && now.before(officialSunsetDate)) {
+ return "true";
+ } else {
+ return "false";
+ }
+ } else if (command.equalsIgnoreCase("isNight")) {
+ Calendar now = Calendar.getInstance(timezone);
+ Calendar officialSunriseDate = calculator.getOfficialSunriseCalendarForDate(now);
+ Calendar officialSunsetDate = calculator.getOfficialSunsetCalendarForDate(now);
+ if (now.after(officialSunriseDate) && now.before(officialSunsetDate)) {
+ return "false";
+ } else {
+ return "true";
+ }
+ }
+ LOG.severe("DateTimeCommand does not know about this command: " + command);
+ return "Unknown command";
+ }
+
+ @Override
+ public void start(Sensor sensor) {
+ LOG.fine("*** setSensor called as part of EventListener init *** sensor is: " + sensor);
+ if (pollingInterval == null) {
+ throw new RuntimeException("Could not set sensor because no polling interval was given");
+ }
+ this.sensor = sensor;
+ pollingThread = new Thread(this);
+ pollingThread.setName("Polling thread for: " + sensor);
+ pollingThread.start();
+ }
+
+
+ @Override
+ public void stop(Sensor sensor) {
+ this.doPoll = false;
+ }
+
+ @Override
+ public void run() {
+ LOG.fine("Sensor thread started for sensor: " + sensor);
+ this.doPoll = true;
+ while (this.doPoll) {
+ String readValue = this.calculateData();
+ if (!"N/A".equals(readValue)) {
+ sensor.update(readValue);
+ }
+ try {
+ Thread.sleep(pollingInterval); // We recalculate at requested polling interval
+ } catch (InterruptedException e) {
+ this.doPoll = false;
+ pollingThread.interrupt();
+ }
+ }
+ LOG.fine("*** Out of run method: " + sensor);
+ }
+
+ public TimeZone getTimezone() {
+ return timezone;
+ }
+
+ public String getCommand() {
+ return command;
+ }
+
+ @Override
+ public String toString() {
+ return "DateTimeCommand{" +
+ "timezone=" + timezone +
+ ", command='" + command + '\'' +
+ '}';
+ }
+}
diff --git a/controller/src/main/java/org/openremote/controller/command/builtin/VirtualCommand.java b/controller/src/main/java/org/openremote/controller/command/builtin/VirtualCommand.java
new file mode 100644
index 000000000..61bc5c7eb
--- /dev/null
+++ b/controller/src/main/java/org/openremote/controller/command/builtin/VirtualCommand.java
@@ -0,0 +1,180 @@
+package org.openremote.controller.command.builtin;
+
+import org.openremote.controller.command.ExecutableCommand;
+import org.openremote.controller.command.PullCommand;
+import org.openremote.controller.model.*;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.logging.Logger;
+
+/**
+ * OpenRemote virtual command implementation.
+ * <p>
+ * Maintains a virtual-machine-wide state for each address. This can be used for testing.
+ * Incoming read() and send() requests operate on a map where the command's {@code <address>}
+ * field is used as a key and either the command name, or command parameter (if provided) is
+ * stored as a virtual device state value for that address.
+ */
+public class VirtualCommand implements ExecutableCommand, PullCommand {
+
+ private static final Logger LOG = Logger.getLogger(VirtualCommand.class.getName());
+
+ private final static Map<String, String> virtualDevices = new ConcurrentHashMap<String, String>(20);
+ private String address = null;
+ private String command = null;
+ private String commandParam = null;
+
+ public VirtualCommand(CommandDefinition commandDefinition) {
+ this(
+ commandDefinition.getProperty("address"),
+ commandDefinition.getProperty("status")
+ );
+ }
+
+ /**
+ * Constructs a new "virtual" device command with a given address and command.
+ * <p>
+ * When this command's {@link #send} method is called, the command name is stored as a
+ * virtual device state value for the given device address.
+ *
+ * @param address arbitrary address string that is used to store the command value in memory
+ * @param command arbitrary command string that is stored in memory and can be later retrieved
+ * via invoking {@link #read}.
+ */
+ public VirtualCommand(String address, String command) {
+ this.address = address;
+ this.command = command;
+ }
+
+ /**
+ * Constructs a new "virtual" device command with a given address, command, and command parameter.
+ * <p>
+ * When this command's {@link #send(String)} method is called, the command's parameter value is stored
+ * as a virtual device state value for the given address. This type of command can therefore
+ * be used to test components such as sliders that send values as command parameters.
+ *
+ * @param address arbitrary address string that is used to store the command parameter in
+ * memory
+ * @param command command name TODO (not used)
+ * @param commandParam command parameter value -- stored as a virtual device state value in
+ * memory and can be later retrieved using this command's {@link #read}
+ * method.
+ */
+ public VirtualCommand(String address, String command, String commandParam) {
+ this(address, command);
+ this.commandParam = commandParam;
+ }
+
+ /**
+ * Allows this command implementation to be used with components that require write command
+ * implementations.
+ * <p>
+ * Stores the command name (or command parameter, if provided) as a "virtual" device state
+ * value when a send() is triggered. The state is stored and indexed by this command's address.
+ * <p>
+ * If command parameter has been provided (such as slider value) then that is stored as device
+ * state instead of command's name.
+ */
+ @Override
+ public void send(String arg) {
+ // TODO arg
+ if (commandParam == null) {
+ virtualDevices.put(address, command);
+ } else {
+ virtualDevices.put(address, commandParam);
+ }
+ }
+
+ /**
+ * Allows this command implementation to be used as pull commands for sensors.
+ * <p>
+ * Stored values are looked up using address string as key on read() requests. Device state
+ * values can be stored for any given address using {@link #send} method of this class.
+ * <p>
+ * If the sensor associated with this command is of 'switch' type, the stored value should
+ * match 'on' or 'off' ('off' will be returned if the stored value cannot be translated or
+ * if no value has been stored for this command's address yet).
+ * <p>
+ * If the sensor associated with this command is of 'level' type, the stored value should
+ * be an integer string within range of [0-100]. String '0' will be returned if the stored
+ * device value for this address cannot be translated to integer or if no value has been
+ * stored for this command's addres yet.
+ * <p>
+ * Range behaves the same as 'level' but allows arbitrary integer to be stored.
+ * <p>
+ * Sensor type 'custom' allows arbitrary string values to be returned from this implementation.
+ *
+ * @param sensor the sensor
+ * @return the value stored for this command's address (in memory) or a default value based
+ * on the associated sensor type, if no value has been stored yet in memory
+ */
+ @Override
+ public String read(Sensor sensor) {
+ String state = virtualDevices.get(address);
+
+ if (sensor instanceof SwitchSensor) {
+ if (state == null) {
+ return "off";
+ } else if (state.trim().equalsIgnoreCase("on")) {
+ return "on";
+ } else if (state.trim().equalsIgnoreCase("off")) {
+ return "off";
+ } else {
+ LOG.warning("Was expecting either 'on' or 'off' for SwitchSensor, got: " + state);
+ return "off";
+ }
+ } else if (sensor instanceof LevelSensor) {
+ if (state == null) {
+ return "0";
+ } else {
+ try {
+ int value = Integer.parseInt(state.trim());
+
+ if (value > 100) {
+ return "100";
+ }
+
+ if (value < 0) {
+ return "0";
+ }
+
+ return "" + value;
+ } catch (NumberFormatException e) {
+ LOG.warning("Can't parse LevelSensor value into a valid number: " + e.getMessage());
+ return "0";
+ }
+ }
+ } else if (sensor instanceof RangeSensor) {
+ if (state == null) {
+ return "0";
+ } else {
+ try {
+ int value = Integer.parseInt(state.trim());
+
+ return "" + value;
+ } catch (NumberFormatException e) {
+ LOG.warning("Can't parse RangeSensor value into a valid number: " + e.getMessage());
+ return "0";
+ }
+ }
+ } else if (sensor instanceof CustomStateSensor) {
+ return (state == null) ? "" : state;
+ } else {
+ throw new Error(
+ "Unrecognized sensor type '" + sensor + "'. Virtual command implementation must " +
+ "be updated to support this sensor type."
+ );
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "VirtualCommand{" +
+ "address='" + address + '\'' +
+ ", command='" + command + '\'' +
+ ", commandParam='" + commandParam + '\'' +
+ '}';
+ }
+}
+
diff --git a/controller/src/main/java/org/openremote/controller/deploy/ControllerDOM.java b/controller/src/main/java/org/openremote/controller/deploy/ControllerDOM.java
new file mode 100644
index 000000000..805444475
--- /dev/null
+++ b/controller/src/main/java/org/openremote/controller/deploy/ControllerDOM.java
@@ -0,0 +1,115 @@
+package org.openremote.controller.deploy;
+
+import org.openremote.container.xml.DOM;
+import org.openremote.controller.model.CommandDefinition;
+import org.openremote.controller.model.SensorDefinition;
+import org.w3c.dom.Document;
+
+import javax.xml.xpath.XPath;
+import java.util.*;
+
+public class ControllerDOM extends DOM {
+
+ public static final String NAMESPACE_URI = "http://www.openremote.org";
+
+ final protected XPath xpath;
+ final protected CommandDefinition[] commandDefinitions;
+ final protected SensorDefinition[] sensorDefinitions;
+
+ public ControllerDOM(Document dom, XPath xpath) {
+ super(dom);
+ this.xpath = xpath;
+
+ try {
+ List<CommandDefinition> commandDefinitionList = new ArrayList<>();
+ ControllerElement[] commandElements = getRoot(xpath).getFirstChild("commands").getChildren();
+ for (ControllerElement commandElement : commandElements) {
+ Integer commandID = Integer.valueOf(commandElement.getAttribute("id"));
+ String protocolType = commandElement.getAttribute("protocol");
+ Map<String, String> properties = new LinkedHashMap<>();
+ for (ControllerElement propertyElement : commandElement.getChildren("property")) {
+ properties.put(propertyElement.getAttribute("name"), propertyElement.getAttribute("value"));
+ }
+ commandDefinitionList.add(
+ new CommandDefinition(commandID, protocolType, properties)
+ );
+ }
+ commandDefinitions = commandDefinitionList.toArray(new CommandDefinition[commandDefinitionList.size()]);
+
+ List<SensorDefinition> sensorDefinitionList = new ArrayList<>();
+ ControllerElement[] sensorElements = getRoot(xpath).getFirstChild("sensors").getChildren();
+ for (ControllerElement sensorElement : sensorElements) {
+ Integer sensorID = Integer.valueOf(sensorElement.getAttribute("id"));
+ String sensorName = sensorElement.getAttribute("name");
+ String sensorType = sensorElement.getAttribute("type").toLowerCase(Locale.ROOT);
+
+ Integer commandRefID = null;
+ ControllerElement includeElement = sensorElement.getFirstChild("include");
+ if (includeElement != null && "command".equals(includeElement.getAttribute("type"))) {
+ commandRefID = Integer.valueOf(includeElement.getAttribute("ref"));
+ }
+ if (commandRefID == null) {
+ throw new IllegalStateException(
+ "Missing command reference in sensor definition: " + sensorID + "/" + sensorName
+ );
+ }
+
+ CommandDefinition commandDefinition = null;
+ for (CommandDefinition cmdDefinition : commandDefinitionList) {
+ if (cmdDefinition.getCommandID() == commandRefID) {
+ commandDefinition = cmdDefinition;
+ break;
+ }
+ }
+ if (commandDefinition == null) {
+ throw new IllegalStateException(
+ "Unknown command '" + commandRefID + "' referenced in sensor definition: " + sensorID + "/" + sensorName
+ );
+ }
+
+ // TODO This is horrible, not uniform
+ Map<String, String> properties = new LinkedHashMap<>();
+ for (ControllerElement stateElement : sensorElement.getChildren("state")) {
+ properties.put("state-" + stateElement.getAttribute("name"), stateElement.getAttribute("value"));
+ }
+ ControllerElement minElement = sensorElement.getFirstChild("min");
+ if (minElement != null)
+ properties.put("range-min", minElement.getAttribute("value"));
+ ControllerElement maxElement = sensorElement.getFirstChild("max");
+ if (maxElement != null)
+ properties.put("range-max", maxElement.getAttribute("value"));
+
+ sensorDefinitionList.add(
+ new SensorDefinition(sensorID, sensorName, sensorType, commandDefinition, properties)
+ );
+ }
+ this.sensorDefinitions = sensorDefinitionList.toArray(new SensorDefinition[sensorDefinitionList.size()]);
+
+ } catch (Exception ex) {
+ throw new RuntimeException("Error building controller model from XML document", ex);
+ }
+ }
+
+ @Override
+ public String getRootElementNamespace() {
+ return NAMESPACE_URI;
+ }
+
+ @Override
+ public ControllerElement getRoot(XPath xPath) {
+ return new ControllerElement(xPath, getW3CDocument().getDocumentElement());
+ }
+
+ @Override
+ public ControllerDOM copy() {
+ return new ControllerDOM((Document) getW3CDocument().cloneNode(true), xpath);
+ }
+
+ public CommandDefinition[] getCommandDefinitions() {
+ return commandDefinitions;
+ }
+
+ public SensorDefinition[] getSensorDefinitions() {
+ return sensorDefinitions;
+ }
+}
\ No newline at end of file
diff --git a/controller/src/main/java/org/openremote/controller/deploy/ControllerDOMParser.java b/controller/src/main/java/org/openremote/controller/deploy/ControllerDOMParser.java
new file mode 100644
index 000000000..d520bc37d
--- /dev/null
+++ b/controller/src/main/java/org/openremote/controller/deploy/ControllerDOMParser.java
@@ -0,0 +1,39 @@
+package org.openremote.controller.deploy;
+
+import org.openremote.container.xml.DOMParser;
+import org.openremote.container.xml.NamespaceContextMap;
+import org.w3c.dom.Document;
+
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.xpath.XPath;
+
+public class ControllerDOMParser extends DOMParser<ControllerDOM> {
+
+ public static final String SCHEMA_XSD = "/org/openremote/controller/schemas/controller-2.0-M7.xsd";
+
+ public ControllerDOMParser() {
+ super(new StreamSource(ControllerDOMParser.class.getResourceAsStream(SCHEMA_XSD)));
+ }
+
+ @Override
+ protected ControllerDOM createDOM(Document document) {
+ return new ControllerDOM(document, createXPath());
+ }
+
+ public NamespaceContextMap createDefaultNamespaceContext(String... optionalPrefixes) {
+ NamespaceContextMap ctx = new NamespaceContextMap() {
+ @Override
+ protected String getDefaultNamespaceURI() {
+ return ControllerDOM.NAMESPACE_URI;
+ }
+ };
+ for (String optionalPrefix : optionalPrefixes) {
+ ctx.put(optionalPrefix, ControllerDOM.NAMESPACE_URI);
+ }
+ return ctx;
+ }
+
+ public XPath createXPath() {
+ return super.createXPath(createDefaultNamespaceContext(ControllerElement.XPATH_PREFIX));
+ }
+}
diff --git a/controller/src/main/java/org/openremote/controller/deploy/ControllerElement.java b/controller/src/main/java/org/openremote/controller/deploy/ControllerElement.java
new file mode 100644
index 000000000..6e1a138f6
--- /dev/null
+++ b/controller/src/main/java/org/openremote/controller/deploy/ControllerElement.java
@@ -0,0 +1,45 @@
+package org.openremote.controller.deploy;
+
+import org.openremote.container.xml.DOMElement;
+import org.w3c.dom.Element;
+
+import javax.xml.xpath.XPath;
+
+public class ControllerElement extends DOMElement<ControllerElement, ControllerElement> {
+
+ public static final String XPATH_PREFIX = "c";
+
+ public ControllerElement(XPath xpath, Element element) {
+ super(xpath, element);
+ }
+
+ @Override
+ protected String prefix(String localName) {
+ return XPATH_PREFIX + ":" + localName;
+ }
+
+ @Override
+ protected Builder<ControllerElement> createParentBuilder(DOMElement el) {
+ return new Builder<ControllerElement>(el) {
+ @Override
+ public ControllerElement build(Element element) {
+ return new ControllerElement(getXpath(), element);
+ }
+ };
+ }
+
+ @Override
+ protected ArrayBuilder<ControllerElement> createChildBuilder(DOMElement el) {
+ return new ArrayBuilder<ControllerElement>(el) {
+ @Override
+ public ControllerElement[] newChildrenArray(int length) {
+ return new ControllerElement[length];
+ }
+
+ @Override
+ public ControllerElement build(Element element) {
+ return new ControllerElement(getXpath(), element);
+ }
+ };
+ }
+}
diff --git a/controller/src/main/java/org/openremote/controller/event/CommandFacade.java b/controller/src/main/java/org/openremote/controller/event/CommandFacade.java
deleted file mode 100644
index f0c93a911..000000000
--- a/controller/src/main/java/org/openremote/controller/event/CommandFacade.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package org.openremote.controller.event;
-
-import org.openremote.controller.model.CommandDefinition;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.logging.Logger;
-
-public class CommandFacade {
-
- private static final Logger LOG = Logger.getLogger(CommandFacade.class.getName());
-
- final protected Map<String, CommandDefinition> namedCommands = new HashMap<>();
-
- public CommandFacade(Collection<CommandDefinition> commandDefinitions) {
- for (CommandDefinition cmd : commandDefinitions) {
- String cmdName = cmd.getProperty(CommandDefinition.NAME_PROPERTY);
- if (cmdName != null && !cmdName.equals("")) {
- namedCommands.put(cmdName, cmd);
- } else {
- LOG.warning("Ignoring command definition without command name: " + cmd);
- }
- }
- }
-
- public void command(String name) {
- command(name, null); // null == no param
- }
-
- public void command(String name, String param) {
- if (name == null || name.equals("")) {
- LOG.info("Empty command name, ignoring execution (are all your rules executing commands with proper names?)");
- return;
- }
-
- CommandDefinition cmd = namedCommands.get(name);
-
- if (cmd == null) {
- LOG.warning("Command definition not found, ignoring execution: " + name);
- return;
- }
-
- LOG.fine("Preparing and executing: " + cmd);
- 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/EventProcessor.java b/controller/src/main/java/org/openremote/controller/event/EventProcessor.java
index 2c95b0c2a..0c79e84a6 100644
--- a/controller/src/main/java/org/openremote/controller/event/EventProcessor.java
+++ b/controller/src/main/java/org/openremote/controller/event/EventProcessor.java
@@ -1,9 +1,8 @@
package org.openremote.controller.event;
-public abstract class EventProcessor {
+import org.openremote.controller.event.facade.CommandFacade;
- public void init() throws Exception{
- }
+public abstract class EventProcessor {
public void start(CommandFacade commandFacade) throws Exception{
}
diff --git a/controller/src/main/java/org/openremote/controller/event/EventProcessorChain.java b/controller/src/main/java/org/openremote/controller/event/EventProcessorChain.java
index ffa249c3d..63a94731b 100644
--- a/controller/src/main/java/org/openremote/controller/event/EventProcessorChain.java
+++ b/controller/src/main/java/org/openremote/controller/event/EventProcessorChain.java
@@ -1,5 +1,7 @@
package org.openremote.controller.event;
+import org.openremote.controller.event.facade.CommandFacade;
+
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
@@ -22,13 +24,6 @@ public class EventProcessorChain {
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() {
@@ -65,7 +60,7 @@ public class EventProcessorChain {
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);
+ LOG.log(Level.FINE, "Ignoring event push, context was terminated, stopped event processor chain at: " + processor);
return;
} else {
LOG.fine("Event '" + ctx.getEvent() + "' processed by: " + processor.getName());
diff --git a/controller/src/main/java/org/openremote/controller/event/facade/CommandFacade.java b/controller/src/main/java/org/openremote/controller/event/facade/CommandFacade.java
new file mode 100644
index 000000000..c3f979c72
--- /dev/null
+++ b/controller/src/main/java/org/openremote/controller/event/facade/CommandFacade.java
@@ -0,0 +1,79 @@
+package org.openremote.controller.event.facade;
+
+import org.openremote.controller.command.Command;
+import org.openremote.controller.command.ExecutableCommand;
+import org.openremote.controller.event.EventProcessor;
+import org.openremote.controller.model.CommandDefinition;
+import org.openremote.controller.model.Deployment;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Can be used by {@link EventProcessor}s to trigger {@link ExecutableCommand}s (e.g. in rules).
+ */
+public class CommandFacade {
+
+ private static final Logger LOG = Logger.getLogger(CommandFacade.class.getName());
+
+ final protected Deployment deployment;
+
+ public CommandFacade(Deployment deployment) {
+ this.deployment = deployment;
+ }
+
+ public void command(String commandName) {
+ command(commandName, null);
+ }
+
+ public void command(String commandName, int value) {
+ command(commandName, Integer.toString(value));
+ }
+
+ public void command(String commandName, String arg) {
+ CommandDefinition commandDefinition = deployment.getCommandDefinition(commandName);
+ if (commandDefinition == null) {
+ LOG.warning("Command definition not found, ignoring execution: " + commandName);
+ return;
+ }
+ execute(commandDefinition, arg);
+ }
+
+ /**
+ * Executes a command. This normally means a device protocol is used to communicate with
+ * some physical device.
+ */
+ public void execute(CommandDefinition commandDefinition) {
+ execute(commandDefinition, null);
+ }
+
+ /**
+ * Build a {@link Command} from this definition and, if possible, execute it with the given argument.
+ *
+ * @param arg command parameter value
+ */
+ public void execute(CommandDefinition commandDefinition, String arg) {
+ Command command;
+ try {
+ command = deployment.getCommandFactory().build(commandDefinition);
+ if (command == null) {
+ LOG.log(Level.WARNING,
+ "No command was produced (can the protocol build an ExecutableCommand?): " + commandDefinition
+ );
+ } else if (command instanceof ExecutableCommand) {
+ LOG.fine("Executing command '" + command + "' with: " + arg);
+ ExecutableCommand executableCommand = (ExecutableCommand) command;
+ try {
+ executableCommand.send(arg);
+ } catch (Exception ex) {
+ LOG.log(Level.SEVERE, "Error executing command '" + command + "' with: " + arg, ex);
+ }
+ } else {
+ LOG.log(Level.WARNING, "Ignoring, not an ExecutableCommand: " + command);
+ }
+ } catch (Throwable t) {
+ LOG.log(Level.SEVERE, "Error building command: " + commandDefinition, t);
+ }
+ }
+}
+
diff --git a/controller/src/main/java/org/openremote/controller/event/EventFacade.java b/controller/src/main/java/org/openremote/controller/event/facade/EventFacade.java
similarity index 54%
rename from controller/src/main/java/org/openremote/controller/event/EventFacade.java
rename to controller/src/main/java/org/openremote/controller/event/facade/EventFacade.java
index cc1b1e860..c1bae3967 100644
--- a/controller/src/main/java/org/openremote/controller/event/EventFacade.java
+++ b/controller/src/main/java/org/openremote/controller/event/facade/EventFacade.java
@@ -1,7 +1,14 @@
-package org.openremote.controller.event;
+package org.openremote.controller.event.facade;
+
+import org.openremote.controller.event.Event;
+import org.openremote.controller.event.EventContext;
+
+import java.util.logging.Logger;
public class EventFacade {
+ private static final Logger LOG = Logger.getLogger(EventFacade.class.getName());
+
protected EventContext eventContext;
public void pushEventContext(EventContext ctx) {
@@ -10,6 +17,7 @@ public class EventFacade {
protected void dispatchEvent(final Event event) {
eventContext.terminate();
+ LOG.fine("Dispatching on new thread: " + event);
Thread t = new Thread(
() -> eventContext.getStatusCache().update(event)
);
diff --git a/controller/src/main/java/org/openremote/controller/statuscache/LevelFacade.java b/controller/src/main/java/org/openremote/controller/event/facade/LevelFacade.java
similarity index 89%
rename from controller/src/main/java/org/openremote/controller/statuscache/LevelFacade.java
rename to controller/src/main/java/org/openremote/controller/event/facade/LevelFacade.java
index a19dc465f..53e1a6ad6 100644
--- a/controller/src/main/java/org/openremote/controller/statuscache/LevelFacade.java
+++ b/controller/src/main/java/org/openremote/controller/event/facade/LevelFacade.java
@@ -1,6 +1,5 @@
-package org.openremote.controller.statuscache;
+package org.openremote.controller.event.facade;
-import org.openremote.controller.event.SingleValueEventFacade;
import org.openremote.controller.event.LevelEvent;
public class LevelFacade extends SingleValueEventFacade<LevelFacade.LevelAdapter, LevelEvent> {
@@ -24,6 +23,7 @@ public class LevelFacade extends SingleValueEventFacade<LevelFacade.LevelAdapter
}
public void value(int value) {
+ // TODO Duplicate max/min logic?!
if (value < 0) {
value = 0;
} else if (value > 100) {
diff --git a/controller/src/main/java/org/openremote/controller/statuscache/RangeFacade.java b/controller/src/main/java/org/openremote/controller/event/facade/RangeFacade.java
similarity index 91%
rename from controller/src/main/java/org/openremote/controller/statuscache/RangeFacade.java
rename to controller/src/main/java/org/openremote/controller/event/facade/RangeFacade.java
index 459dd446d..562d82fb2 100644
--- a/controller/src/main/java/org/openremote/controller/statuscache/RangeFacade.java
+++ b/controller/src/main/java/org/openremote/controller/event/facade/RangeFacade.java
@@ -1,6 +1,5 @@
-package org.openremote.controller.statuscache;
+package org.openremote.controller.event.facade;
-import org.openremote.controller.event.SingleValueEventFacade;
import org.openremote.controller.event.RangeEvent;
import java.util.logging.Logger;
@@ -11,6 +10,7 @@ public class RangeFacade extends SingleValueEventFacade<RangeFacade.RangeAdapter
@Override
protected RangeEvent createDefaultEvent(int sourceID, String sourceName) {
+ // TODO We drop the min/max here, not good
return new RangeEvent(sourceID, sourceName, 0, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
diff --git a/controller/src/main/java/org/openremote/controller/event/SingleValueEventFacade.java b/controller/src/main/java/org/openremote/controller/event/facade/SingleValueEventFacade.java
similarity index 88%
rename from controller/src/main/java/org/openremote/controller/event/SingleValueEventFacade.java
rename to controller/src/main/java/org/openremote/controller/event/facade/SingleValueEventFacade.java
index 4c5db572d..96d9bc2cf 100644
--- a/controller/src/main/java/org/openremote/controller/event/SingleValueEventFacade.java
+++ b/controller/src/main/java/org/openremote/controller/event/facade/SingleValueEventFacade.java
@@ -1,5 +1,6 @@
-package org.openremote.controller.event;
+package org.openremote.controller.event.facade;
+import org.openremote.controller.event.Event;
import org.openremote.controller.model.Sensor;
public abstract class SingleValueEventFacade<T, U extends Event> extends EventFacade {
diff --git a/controller/src/main/java/org/openremote/controller/statuscache/SwitchFacade.java b/controller/src/main/java/org/openremote/controller/event/facade/SwitchFacade.java
similarity index 94%
rename from controller/src/main/java/org/openremote/controller/statuscache/SwitchFacade.java
rename to controller/src/main/java/org/openremote/controller/event/facade/SwitchFacade.java
index 55a8e4c7a..f90505996 100644
--- a/controller/src/main/java/org/openremote/controller/statuscache/SwitchFacade.java
+++ b/controller/src/main/java/org/openremote/controller/event/facade/SwitchFacade.java
@@ -1,7 +1,6 @@
-package org.openremote.controller.statuscache;
+package org.openremote.controller.event.facade;
import org.openremote.controller.event.Event;
-import org.openremote.controller.event.EventFacade;
import org.openremote.controller.model.Sensor;
import org.openremote.controller.event.SwitchEvent;
diff --git a/controller/src/main/java/org/openremote/controller/model/CommandDefinition.java b/controller/src/main/java/org/openremote/controller/model/CommandDefinition.java
index e1fbac581..4e25d0980 100644
--- a/controller/src/main/java/org/openremote/controller/model/CommandDefinition.java
+++ b/controller/src/main/java/org/openremote/controller/model/CommandDefinition.java
@@ -1,22 +1,13 @@
package org.openremote.controller.model;
-import org.openremote.controller.command.ExecutableCommand;
-import org.openremote.controller.command.ExecutableCommandFactory;
-
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.
+ * Command deployment model
*/
public class CommandDefinition {
- private static final Logger LOG = Logger.getLogger(CommandDefinition.class.getName());
-
/**
* Command property name that contains a logical command name that can be used by scripts,
* rules, REST API calls, etc.
@@ -26,25 +17,29 @@ public class CommandDefinition {
/**
* Default value returned by {@link #getName()} if no name has been set in command's properties.
*/
- public final static String NAME_PROPERTY_DEFAULT_VALUE = "<no name>";
+ public final static String NAME_PROPERTY_DEFAULT_VALUE = "<No Name>";
+
+ /**
+ * Command property that contains the name of the related device.
+ */
+ public final static String DEVICE_NAME_PROPERTY = "urn:openremote:device-command:device-name";
/**
- * Command factory delegates creation of command execution model to specific protocol specific
- * builders (Such as X10, KNX, one-wire, etc.)
+ * Command property that contains the ID of the related device.
*/
- final private ExecutableCommandFactory executableCommandFactory;
+ public final static String DEVICE_ID_PROPERTY = "urn:openremote:device-command:device-id";
/**
* 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;
+ final protected String protocolType;
/**
* A unique command identifier. This corresponds to the 'id' attribute in controller XML
* definition's {@code <command>} element.
*/
- final private int id;
+ final protected int commandID;
/**
* List of generic command properties. The correspond to {@code <property>} elements nested
@@ -56,14 +51,12 @@ public class CommandDefinition {
* NOTE: property *names* are *not* case sensitive. All property names are converted to lower
* case.
*/
- final private Map<String, String> properties;
+ final protected Map<String, String> properties;
/**
* Constructs a command data model.
*
- * @param executableCommandFactory 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
+ * @param commandID 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
@@ -72,21 +65,25 @@ public class CommandDefinition {
* command instances. Certain property values such as {@link #NAME_PROPERTY}
* may have special meaning.
*/
- public CommandDefinition(ExecutableCommandFactory executableCommandFactory, int id, String protocolType, Map<String, String> properties) {
- this.executableCommandFactory = executableCommandFactory;
- this.id = id;
+ public CommandDefinition(int commandID, String protocolType, Map<String, String> properties) {
+ if (protocolType == null)
+ throw new IllegalArgumentException("Command protocol type can't be null");
+ this.commandID = commandID;
this.protocolType = protocolType;
+ if (properties == null)
+ throw new IllegalArgumentException("Command definition properties are required: " + this);
this.properties = properties;
+ if (getDeviceID() == null)
+ throw new IllegalStateException("Command definition must have device identifier: " + this);
+ if (getDeviceName() == null)
+ throw new IllegalStateException("Command definition must have device name: " + this);
}
/**
- * 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
+ * Returns the unique identifier of the command.
*/
- public int getID() {
- return id;
+ public int getCommandID() {
+ return commandID;
}
/**
@@ -97,12 +94,24 @@ public class CommandDefinition {
*/
public String getName() {
String name = getProperty(NAME_PROPERTY);
- if (name == null || name.equals("")) {
+ if (name.length() == 0) {
return NAME_PROPERTY_DEFAULT_VALUE;
}
return name;
}
+ public String getDeviceName() {
+ return getProperty(CommandDefinition.DEVICE_NAME_PROPERTY).trim();
+ }
+
+ public Integer getDeviceID() {
+ try {
+ return Integer.parseInt(getProperty(CommandDefinition.DEVICE_ID_PROPERTY));
+ } catch (NumberFormatException ex) {
+ return null;
+ }
+ }
+
/**
* Returns the protocol type of the command that corresponds to 'protocol' attribute of
* {@code <command>} element in controller's XML definition.
@@ -121,44 +130,33 @@ public class CommandDefinition {
* @return Command property value, or empty string if not found.
*/
public String getProperty(String name) {
+ return getProperty(name, "");
+ }
+
+ public String getProperty(String name, String defaultValue) {
String value = properties.get(name.trim().toLowerCase(Locale.ROOT));
- return (value == null) ? "" : value;
+ return (value == null) ? defaultValue : 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
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ CommandDefinition that = (CommandDefinition) o;
+ return commandID == that.commandID;
}
- /**
- * Build an {@link ExecutableCommand} from this definition and execute it with the given argument.
- *
- * @param arg command parameter value
- */
- public void execute(String arg) {
- try {
- ExecutableCommand command = executableCommandFactory.getCommand(this);
- if (command == null) {
- LOG.log(Level.WARNING,
- "No command was produced (can the protocol build an ExecutableCommand?): " + this
- );
- return;
- }
- LOG.fine("Executing command '" + command + "' with: " + arg);
- command.send(arg);
- } catch (Throwable t) {
- LOG.log(Level.SEVERE, "Unable to execute command: " + this, t);
- }
+ @Override
+ public int hashCode() {
+ return commandID;
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"protocolType='" + protocolType + '\'' +
- ", id=" + id +
+ ", ID=" + getCommandID() +
+ ", name=" + getName() +
", properties=" + properties +
'}';
}
diff --git a/controller/src/main/java/org/openremote/controller/model/StateSensor.java b/controller/src/main/java/org/openremote/controller/model/CustomStateSensor.java
similarity index 56%
rename from controller/src/main/java/org/openremote/controller/model/StateSensor.java
rename to controller/src/main/java/org/openremote/controller/model/CustomStateSensor.java
index 5b5c3e958..bd54c4c97 100644
--- a/controller/src/main/java/org/openremote/controller/model/StateSensor.java
+++ b/controller/src/main/java/org/openremote/controller/model/CustomStateSensor.java
@@ -5,12 +5,10 @@ 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;
/**
@@ -25,70 +23,12 @@ import java.util.logging.Logger;
* <p>
* See {@link DistinctStates} for more details.
*/
-public class StateSensor extends Sensor {
+public class CustomStateSensor extends Sensor {
- private static final Logger LOG = Logger.getLogger(StateSensor.class.getName());
+ private static final Logger LOG = Logger.getLogger(CustomStateSensor.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);
- }
+ final protected DistinctStates states;
+ final protected boolean strictStateMapping;
/**
* Constructs a new sensor with a given sensor ID, event producer and distinct state values
@@ -101,40 +41,34 @@ public class StateSensor extends Sensor {
* 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
+ * @param producer the data/event producing command implementation that backs this sensor
+ * @param states distinct state values and their mappings this sensor will return
+ * @param strictStateMapping Indicates whether this sensor instance should enforce strict state mapping rules -- when
+ * enabled, only state values explicitly declared for this sensor will be accepted and returned.
+ * If set to false, all values are allowed but those with value mappings will be converted.
*/
- 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));
-
+ protected CustomStateSensor(SensorDefinition sensorDefinition, EventProducerCommand producer, DistinctStates states, boolean strictStateMapping) {
+ super(sensorDefinition, producer);
if (states == null) {
this.states = new DistinctStates();
} else {
this.states = states;
}
+ this.strictStateMapping = strictStateMapping;
}
/**
* Constructs an event from the raw protocol output string. This implementation checks the
* incoming value for possible state mappings and returns an event containing the mapped
* state value where necessary. Arbitrary, non-declared states are rejected unless
- * {@link #setStrictStateMapping} has been set to false. When set to true, an
+ * {@link #strictStateMapping} has been set to false. When set to true, an
* instance of {@link org.openremote.controller.model.Sensor.UnknownEvent} is returned
* for any non-declared state.
*
* @return An event containing the state returned by the associated event producer or
* a translated (mapped) version of the state string. Can return
* {@link org.openremote.controller.model.Sensor.UnknownEvent} in case where
- * {@link #setStrictStateMapping} is true and a state value is returned from the
+ * {@link #strictStateMapping} is true and a state value is returned from the
* event producer that has not been declared as a distinct state for this sensor.
*/
@Override
@@ -144,14 +78,8 @@ public class StateSensor extends Sensor {
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()}
- );
-
+ if (strictStateMapping) {
+ LOG.warning("Event producer's value is not consistent with '" + getSensorDefinition() + "': " + value);
return new UnknownEvent(this);
} else {
return createEvent(value);
@@ -165,18 +93,6 @@ public class StateSensor extends Sensor {
}
}
-
- /**
- * 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.
@@ -185,10 +101,7 @@ public class StateSensor extends Sensor {
* @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);
+ return new CustomStateEvent(getSensorDefinition().getSensorID(), getSensorDefinition().getName(), value);
}
/**
@@ -201,10 +114,7 @@ public class StateSensor extends Sensor {
* @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);
+ return new CustomStateEvent(getSensorDefinition().getSensorID(), getSensorDefinition().getName(), value, originalValue);
}
/**
@@ -300,10 +210,9 @@ public class StateSensor extends Sensor {
@Override
public String toString() {
- return "StateSensor{" +
- ", sensorID=" + getSensorID() +
- ", commandID=" + getCommandID() +
- ", hasStrictStateMapping=" + hasStrictStateMapping +
+ return getClass().getSimpleName() + "{" +
+ "sensorDefinition=" + getSensorDefinition() +
+ ", hasStrictStateMapping=" + strictStateMapping +
", states=" + states +
'}';
}
diff --git a/controller/src/main/java/org/openremote/controller/model/Deployment.java b/controller/src/main/java/org/openremote/controller/model/Deployment.java
new file mode 100644
index 000000000..18f0e52a6
--- /dev/null
+++ b/controller/src/main/java/org/openremote/controller/model/Deployment.java
@@ -0,0 +1,138 @@
+package org.openremote.controller.model;
+
+import org.openremote.controller.command.Command;
+import org.openremote.controller.command.CommandFactory;
+import org.openremote.controller.command.EventProducerCommand;
+import org.openremote.controller.deploy.ControllerDOM;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class Deployment {
+
+ final protected CommandFactory commandFactory;
+ final protected Map<String, Device> devices = new HashMap<>();
+ final protected Map<Integer, Sensor> sensors = new HashMap<>();
+
+ public Deployment(ControllerDOM controllerDOM, CommandFactory commandFactory) {
+ this.commandFactory = commandFactory;
+
+ for (SensorDefinition sensorDefinition : controllerDOM.getSensorDefinitions()) {
+ Sensor sensor = buildSensor(sensorDefinition);
+ sensors.put(sensor.getSensorDefinition().getSensorID(), sensor);
+ }
+
+ for (CommandDefinition commandDefinition : controllerDOM.getCommandDefinitions()) {
+ Device device = devices.get(commandDefinition.getDeviceName());
+ if (device == null) {
+ device = new Device(commandDefinition.getDeviceID(), commandDefinition.getDeviceName());
+ devices.put(device.getName(), device);
+ } else if (device.getDeviceID() != commandDefinition.getDeviceID()) {
+ throw new IllegalStateException(
+ "Device '" + device.getName() + "' with ID " + device.getDeviceID() + " conflicts with: " + commandDefinition
+ );
+ }
+ device.addCommandDefinition(commandDefinition);
+ }
+ }
+
+ public CommandFactory getCommandFactory() {
+ return commandFactory;
+ }
+
+ public CommandDefinition getCommandDefinition(int commandID) {
+ for (Device device : devices.values()) {
+ CommandDefinition commandDefinition = device.getCommandDefinition(commandID);
+ if (commandDefinition != null)
+ return commandDefinition;
+ }
+ return null;
+ }
+
+ public CommandDefinition getCommandDefinition(String deviceName, String commandName) {
+ if (deviceName == null || commandName == null || deviceName.length() == 0 || commandName.length() == 0) {
+ return null;
+ }
+ Device device = devices.get(deviceName);
+ return device != null ? device.getCommandDefinition(commandName) : null;
+ }
+
+ public CommandDefinition getCommandDefinition(String commandName) {
+ if (commandName == null || commandName.length() == 0) {
+ return null;
+ }
+ for (Device device : devices.values()) {
+ CommandDefinition commandDefinition = device.getCommandDefinition(commandName);
+ if (commandDefinition != null)
+ return commandDefinition;
+ }
+ return null;
+ }
+
+ public Device getDevice(String deviceName) {
+ return devices.get(deviceName);
+ }
+
+ public Device[] getDevices() {
+ return devices.values().toArray(new Device[devices.values().size()]);
+ }
+
+ public Sensor[] getSensors() {
+ return sensors.values().toArray(new Sensor[sensors.values().size()]);
+ }
+
+ public Sensor getSensor(int sensorID) {
+ return sensors.get(sensorID);
+ }
+
+ protected Sensor buildSensor(SensorDefinition sensorDefinition) {
+ Sensor sensor;
+
+ Command definedCommand = commandFactory.build(sensorDefinition.getCommandDefinition());
+ EventProducerCommand sensorCommand;
+ if (definedCommand instanceof EventProducerCommand) {
+ sensorCommand = (EventProducerCommand) definedCommand;
+ } else {
+ throw new IllegalStateException(
+ "Sensor must reference event producer command, not '" + definedCommand + "': " + sensorDefinition
+ );
+ }
+
+ switch (sensorDefinition.getType()) {
+ case "range":
+ String minValue = sensorDefinition.getProperties().get("range-min");
+ if (minValue == null)
+ throw new IllegalStateException("Sensor of range type must have min/max value defined: " + sensorDefinition);
+ String maxValue = sensorDefinition.getProperties().get("range-max");
+ if (maxValue == null)
+ throw new IllegalStateException("Sensor of range type must have min/max value defined: " + sensorDefinition);
+ sensor = new RangeSensor(sensorDefinition, sensorCommand, Integer.valueOf(minValue), Integer.valueOf(maxValue));
+ break;
+ case "level":
+ sensor = new LevelSensor(sensorDefinition, sensorCommand);
+ break;
+ case "custom":
+ CustomStateSensor.DistinctStates distinctStates = new CustomStateSensor.DistinctStates();
+ for (Map.Entry<String, String> entry : sensorDefinition.getProperties().entrySet()) {
+ if (entry.getKey().startsWith("state-")) {
+ distinctStates.addStateMapping(entry.getKey().substring(6), entry.getValue());
+ }
+ }
+ sensor = new CustomStateSensor(sensorDefinition, sensorCommand, distinctStates, false);
+ break;
+ case "switch":
+ distinctStates = new CustomStateSensor.DistinctStates();
+ for (Map.Entry<String, String> entry : sensorDefinition.getProperties().entrySet()) {
+ if (entry.getKey().startsWith("state-")) {
+ distinctStates.addStateMapping(entry.getKey().substring(6), entry.getValue());
+ }
+ }
+ sensor = new SwitchSensor(sensorDefinition, sensorCommand, distinctStates);
+ break;
+ default:
+ throw new IllegalArgumentException("Unsupported sensor type: " + sensorDefinition);
+ }
+ return sensor;
+ }
+
+}
diff --git a/controller/src/main/java/org/openremote/controller/model/Device.java b/controller/src/main/java/org/openremote/controller/model/Device.java
new file mode 100644
index 000000000..70e57b989
--- /dev/null
+++ b/controller/src/main/java/org/openremote/controller/model/Device.java
@@ -0,0 +1,55 @@
+package org.openremote.controller.model;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+public class Device {
+
+ final protected int deviceID;
+ final protected String name;
+ final protected Map<Integer, CommandDefinition> commandDefinitions = new ConcurrentHashMap<>();
+
+ public Device(int deviceID, String name) {
+ this.deviceID = deviceID;
+ this.name = name;
+ }
+
+ public int getDeviceID() {
+ return deviceID;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public CommandDefinition getCommandDefinition(int commandID) {
+ return commandDefinitions.get(commandID);
+ }
+
+ public CommandDefinition getCommandDefinition(String commandName) {
+ for (CommandDefinition commandDefinition : commandDefinitions.values()) {
+ if (commandDefinition.getName().equals(commandName))
+ return commandDefinition;
+ }
+ return null;
+ }
+
+ public void addCommandDefinition(CommandDefinition commandDefinition) {
+ commandDefinitions.put(commandDefinition.getCommandID(), commandDefinition);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ Device device = (Device) o;
+
+ return deviceID == device.deviceID;
+ }
+
+ @Override
+ public int hashCode() {
+ return deviceID;
+ }
+}
diff --git a/controller/src/main/java/org/openremote/controller/model/LevelSensor.java b/controller/src/main/java/org/openremote/controller/model/LevelSensor.java
index 65731f401..6bcd68b75 100644
--- a/controller/src/main/java/org/openremote/controller/model/LevelSensor.java
+++ b/controller/src/main/java/org/openremote/controller/model/LevelSensor.java
@@ -3,35 +3,40 @@ 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);
+ public LevelSensor(SensorDefinition sensorDefinition, EventProducerCommand eventProducerCommand) {
+ super(sensorDefinition, eventProducerCommand, 0, 100);
}
@Override
public Event processEvent(String value) {
try {
- return new LevelEvent(getSensorID(), getName(), new Integer(value.trim()));
+ return new LevelEvent(
+ getSensorDefinition().getSensorID(),
+ getSensorDefinition().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}
- );
+ LOG.warning("Level sensor '" + getSensorDefinition() + "' produced a non-integer value: " + value);
}
return new UnknownEvent(this);
}
}
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "sensorDefinition=" + getSensorDefinition() +
+ ", minValue=" + getMinValue() +
+ ", maxValue=" + getMaxValue() +
+ '}';
+ }
}
diff --git a/controller/src/main/java/org/openremote/controller/model/RangeSensor.java b/controller/src/main/java/org/openremote/controller/model/RangeSensor.java
index 56cde627a..845ee6ecd 100644
--- a/controller/src/main/java/org/openremote/controller/model/RangeSensor.java
+++ b/controller/src/main/java/org/openremote/controller/model/RangeSensor.java
@@ -3,10 +3,7 @@ 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 {
@@ -16,8 +13,8 @@ public class RangeSensor extends Sensor {
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<>());
+ public RangeSensor(SensorDefinition sensorDefinition, EventProducerCommand eventProducerCommand, int minValue, int maxValue) {
+ super(sensorDefinition, eventProducerCommand);
if (minValue > maxValue)
throw new IllegalArgumentException("Sensor value min '" + minValue + "' is larger than max '" + maxValue + "'");
this.minValue = minValue;
@@ -35,14 +32,16 @@ public class RangeSensor extends Sensor {
@Override
protected Event processEvent(String value) {
try {
- return new RangeEvent(getSensorID(), getName(), new Integer(value.trim()), getMinValue(), getMaxValue());
+ return new RangeEvent(
+ getSensorDefinition().getSensorID(),
+ getSensorDefinition().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}
- );
+ LOG.warning("Range sensor '" + getSensorDefinition() + "' produced a non-integer value: " + value);
}
return new UnknownEvent(this);
}
@@ -51,12 +50,12 @@ public class RangeSensor extends Sensor {
@Override
public String toString() {
- return "RangeSensor{" +
- ", sensorID=" + getSensorID() +
- ", commandID=" + getCommandID() +
+ return getClass().getSimpleName() + "{" +
+ "sensorDefinition=" + getSensorDefinition() +
", 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.java
index 75123f9b7..6caf6453d 100644
--- a/controller/src/main/java/org/openremote/controller/model/Sensor.java
+++ b/controller/src/main/java/org/openremote/controller/model/Sensor.java
@@ -8,8 +8,6 @@ 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;
@@ -27,18 +25,9 @@ import java.util.logging.Logger;
* 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.
* <p>
- * 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.
- * <p>
- * Therefore the object hierarchy for sensors is as follows:
- * <p>
- * <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.
+ * Sensors are registered with {@link org.openremote.controller.statuscache.StatusCache}.
+ * Sensors create {@link org.openremote.controller.event.Event}s, which represent the
+ * data from devices.
*/
public abstract class Sensor {
@@ -58,20 +47,7 @@ public abstract class Sensor {
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;
+ private SensorDefinition sensorDefinition;
/**
* Reference to the state cache that receives and processes the events generated from this sensor.
@@ -79,105 +55,32 @@ public abstract class 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.
- * <p>
- * 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.
+ * An event producer command provides values to a sensor, typically through pull or push.
*/
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.
+ * This is a polling thread implementation for sensors that use {@link PullCommand}.
*/
- private Map<String, String> sensorProperties;
+ private SensorReader sensorReader;
/**
* 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) {
+ protected Sensor(SensorDefinition sensorDefinition, EventProducerCommand eventProducerCommand) {
if (eventProducerCommand == null) {
- throw new IllegalArgumentException("Sensor requires event producer command: " + sensorID);
- }
-
- if (sensorProperties == null) {
- sensorProperties = new HashMap<>(0);
+ throw new IllegalArgumentException("Event producer command required: " + sensorDefinition);
}
-
- this.sensorName = name;
- this.sensorID = sensorID;
- this.statusCache = cache;
+ this.sensorDefinition = sensorDefinition;
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.
- * <p>
- * 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;
+ public SensorDefinition getSensorDefinition() {
+ return sensorDefinition;
}
/**
@@ -190,15 +93,17 @@ public abstract class Sensor {
* @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
+ if (statusCache == null) {
+ LOG.fine("Ignoring update, sensor is not running: " + getSensorDefinition());
+ return;
+ }
// Allow for sensor type specific processing of the value.
// This can be used for mappings, validating value ranges, etc. before the value is
// pushed into device state cache and event processor chain.
Event evt = processEvent(state);
- LOG.fine("Processed '" + state + "', received: " + evt.getValue());
+ LOG.fine("Update on ID " + getSensorDefinition().getSensorID() + ", processed '" + state + "', created: " + evt);
statusCache.update(evt);
}
@@ -211,33 +116,34 @@ public abstract class Sensor {
/**
* 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.
+ * {@link PushCommand#start(Sensor)} method. For {@link PullCommand} implementations,
+ * this will start a polling thread to invoke their {@link PullCommand#read(Sensor)} method.
*/
- public void start() {
+ public void start(StatusCache statusCache) {
+ this.statusCache = statusCache;
if (isPushCommand()) {
PushCommand pushCommand = (PushCommand) eventProducerCommand;
try {
- pushCommand.setSensor(this);
+ pushCommand.start(this);
} catch (Throwable t) {
LOG.log(Level.SEVERE, "There was an implementation error in the push command associated with " +
" sensor '" + this + "'. The command implementation may not have started correctly.", t);
}
+ } else if (eventProducerCommand instanceof PullCommand) {
+ sensorReader = new SensorReader((PullCommand) eventProducerCommand);
+ sensorReader.start();
} else {
- deviceReader = new DeviceReader();
- deviceReader.start();
+ LOG.info("No action implemented for command type: " + eventProducerCommand);
}
}
/**
- * 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()
+ * Stops this sensor. In case this sensor has been bound to a push command, this invokes the
+ * {@link PushCommand#stop(Sensor)} method. In case of a {@link PullCommand}, the polling thread
+ * is stopped.
*/
public void stop() {
+ statusCache = null;
if (isPushCommand()) {
PushCommand pushCommand = (PushCommand) eventProducerCommand;
try {
@@ -246,15 +152,13 @@ public abstract class Sensor {
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();
- }
+ } else if (sensorReader != null) {
+ sensorReader.stop();
}
}
public boolean isRunning() {
- return deviceReader != null && deviceReader.pollingThreadRunning;
+ return sensorReader != null && sensorReader.pollingThreadRunning;
}
/**
@@ -264,48 +168,31 @@ public abstract class Sensor {
*
* @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 {
+ private class SensorReader implements Runnable {
+
+ final protected PullCommand pullCommand;
/**
* 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}.
+ * {@link SensorReader#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}
- );
+ public SensorReader(PullCommand pullCommand) {
+ this.pullCommand = pullCommand;
+ interval = pullCommand.getPollingInterval() > 0
+ ? pullCommand.getPollingInterval()
+ : PullCommand.POLLING_INTERVAL;
+ LOG.info("Created polling thread interval '" + interval + "' for: " + sensorDefinition);
}
/**
@@ -320,7 +207,7 @@ public abstract class Sensor {
/**
* 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()}.
+ * {@link SensorReader#start()}.
*/
public void stop() {
pollingThreadRunning = false;
@@ -334,43 +221,29 @@ public abstract class Sensor {
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}
+ new Object[]{pollingThread.getName(), e.getMessage(), 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.
+ * Once every given interval defined in {@link PullCommand#POLLING_INTERVAL}, invokes the command.
+ * Depending on command 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) {
+ LOG.fine("Polling: " + Sensor.this);
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.
* <p>
@@ -378,11 +251,6 @@ public abstract class Sensor {
* this may yield an active request using the connecting transport to device unless the
* command implementation caches certain values and returns them from memory.
* <p>
- * In case of 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.
- * <p>
* In case of errors, {@link #UNKNOWN_STATUS} is returned.
* <p>
* This default read() implementation does not validate the input from protocol pull commands
@@ -395,28 +263,11 @@ public abstract class Sensor {
* {@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()
- );
+ try {
+ return pullCommand.read(Sensor.this);
+ } catch (Throwable t) {
+ LOG.log(Level.SEVERE, "Implementation error in pull command: " + eventProducerCommand, t);
+ return UNKNOWN_STATUS;
}
}
}
@@ -431,7 +282,7 @@ public abstract class Sensor {
public static class UnknownEvent extends Event<String> {
public UnknownEvent(Sensor sensor) {
- super(sensor.getSensorID(), sensor.getName());
+ super(sensor.getSensorDefinition().getSensorID(), sensor.getSensorDefinition().getName());
}
@Override
@@ -476,30 +327,16 @@ public abstract class Sensor {
}
}
- /**
- * Test sensor object equality based on unique identifier (as returned by {@link #getSensorID}.
- * <p>
- * 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;
-
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
Sensor sensor = (Sensor) o;
-
- return sensor.getSensorID() == this.getSensorID();
+ return sensorDefinition.equals(sensor.sensorDefinition);
}
@Override
public int hashCode() {
- return sensorID;
+ return sensorDefinition.hashCode();
}
}
diff --git a/controller/src/main/java/org/openremote/controller/model/SensorDefinition.java b/controller/src/main/java/org/openremote/controller/model/SensorDefinition.java
new file mode 100644
index 000000000..233168b85
--- /dev/null
+++ b/controller/src/main/java/org/openremote/controller/model/SensorDefinition.java
@@ -0,0 +1,92 @@
+package org.openremote.controller.model;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Sensor deployment model
+ */
+public class SensorDefinition {
+
+ final protected int sensorID;
+ final protected String name;
+ final protected String type;
+ final protected CommandDefinition commandDefinition;
+ final protected Map<String, String> properties;
+
+ /**
+ * Constructs a new sensor definition with a given name, ID, 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 type A sensor type.
+ * @param commandDefinition A command definition used to update sensor values.
+ * @param properties Additional sensor properties. These properties can be used by the protocol
+ * implementors to direct their implementation according to sensor configuration.
+ */
+ public SensorDefinition(int sensorID, String name, String type, CommandDefinition commandDefinition, Map<String, String> properties) {
+ if (properties == null) {
+ properties = new HashMap<>(0);
+ }
+ this.sensorID = sensorID;
+ this.name = name;
+ this.type = type;
+ this.commandDefinition = commandDefinition;
+ this.properties = properties;
+ }
+
+ public int getSensorID() {
+ return sensorID;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public CommandDefinition getCommandDefinition() {
+ return commandDefinition;
+ }
+
+ /**
+ * Returns sensor's properties. Properties are simply string based name-value mappings.
+ * Concrete sensor implementations may specify which particular properties they expose.
+ * <p>
+ * 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(properties);
+ return props;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ SensorDefinition that = (SensorDefinition) o;
+ return sensorID == that.sensorID;
+ }
+
+ @Override
+ public int hashCode() {
+ return sensorID;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "ID=" + getSensorID() +
+ ", name=" + getName() +
+ ", type=" + getType() +
+ ", properties=" + properties +
+ ", commandDefinition=" + getCommandDefinition() +
+ '}';
+ }
+
+}
diff --git a/controller/src/main/java/org/openremote/controller/model/SwitchSensor.java b/controller/src/main/java/org/openremote/controller/model/SwitchSensor.java
index 7d03b6048..2d1c08035 100644
--- a/controller/src/main/java/org/openremote/controller/model/SwitchSensor.java
+++ b/controller/src/main/java/org/openremote/controller/model/SwitchSensor.java
@@ -4,9 +4,7 @@ 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;
/**
@@ -15,54 +13,22 @@ import java.util.logging.Logger;
* values ("open/close", "running/stoppped", etc.) or to translate return values to local
* languages.
*/
-public class SwitchSensor extends StateSensor {
+public class SwitchSensor extends CustomStateSensor {
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.
- *
+ * <p>
* 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 producer the data/event producing command implementation that backs this sensor
* @param states state string mappings for the default 'on' and 'off' values
*/
- public SwitchSensor(String name, int sensorID, StatusCache cache, EventProducerCommand producer, int commandID, DistinctStates states) {
- super(name, sensorID, cache, producer, commandID, states, false);
+ public SwitchSensor(SensorDefinition sensorDefinition, EventProducerCommand producer, DistinctStates states) {
+ super(sensorDefinition, producer, states, true);
}
/**
@@ -82,7 +48,7 @@ public class SwitchSensor extends StateSensor {
/**
* Constructs an event for this sensor instance with a given mapped (translated) event value
* and the original event value which was used for the translation.
- *
+ * <p>
* The original value must be either 'on' or 'off' (case insensitive), otherwise a
* {@link org.openremote.controller.model.Sensor.UnknownEvent} is returned instead. The
* translated value can be any arbitrary string value.
@@ -96,27 +62,27 @@ public class SwitchSensor extends StateSensor {
protected Event createEvent(String value, String originalValue) {
try {
return new SwitchEvent(
- getSensorID(), getName(), value, SwitchEvent.State.valueOf(Strings.toUpperCase(originalValue.trim()))
+ getSensorDefinition().getSensorID(),
+ getSensorDefinition().getName(),
+ value,
+ SwitchEvent.State.valueOf(Strings.toUpperCase(originalValue.trim())) // TODO WTF
);
} 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}
+ LOG.warning(
+ "Switch event value not 'on' or 'off', got '" + originalValue + "' in: " + getSensorDefinition()
);
}
-
return new UnknownEvent(this);
}
}
@Override
public String toString() {
- return "SwitchSensor{" +
- ", sensorID=" + getSensorID() +
- ", commandID=" + getCommandID()
- + "}";
+ return getClass().getSimpleName() + "{" +
+ "sensorDefinition=" + getSensorDefinition() +
+ ", states=" + states +
+ '}';
}
}
diff --git a/controller/src/main/java/org/openremote/controller/rules/RuleEngine.java b/controller/src/main/java/org/openremote/controller/rules/RuleEngine.java
index d40fe3505..9d3f02a9d 100644
--- a/controller/src/main/java/org/openremote/controller/rules/RuleEngine.java
+++ b/controller/src/main/java/org/openremote/controller/rules/RuleEngine.java
@@ -20,12 +20,6 @@
*/
package org.openremote.controller.rules;
-import com.fasterxml.jackson.annotation.JsonAutoDetect;
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.PropertyAccessor;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationFeature;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
@@ -46,13 +40,13 @@ import org.kie.internal.builder.DecisionTableConfiguration;
import org.kie.internal.builder.DecisionTableInputType;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.openremote.container.Container;
-import org.openremote.controller.event.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 org.openremote.controller.event.facade.CommandFacade;
+import org.openremote.controller.event.facade.LevelFacade;
+import org.openremote.controller.event.facade.RangeFacade;
+import org.openremote.controller.event.facade.SwitchFacade;
import java.util.Collection;
import java.util.HashMap;
@@ -139,10 +133,6 @@ public abstract class RuleEngine extends EventProcessor {
}
}
- @Override
- public void init() throws Exception {
- }
-
@Override
public void start(CommandFacade commandFacade) throws Exception {
KieServices kieServices = KieServices.Factory.get();
@@ -176,52 +166,20 @@ public abstract class RuleEngine extends EventProcessor {
rulePersistence = new RulePersistence();
ruleUtil = new RuleUtil();
- 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 {
- knowledgeSession.setGlobal("persistence", rulePersistence);
- } catch (Throwable t) {
- }
-
- try {
- knowledgeSession.setGlobal("util", ruleUtil);
- } catch (Throwable t) {
- }
-
- try {
- knowledgeSession.setGlobal("JSON", Container.JSON);
- } catch (Throwable t) {
- }
-
- try {
- knowledgeSession.setGlobal("LOG", LOG);
- } catch (Throwable t) {
- }
+ setGlobal("execute", commandFacade);
+ setGlobal("switches", switchFacade);
+ setGlobal("ranges", rangeFacade);
+ setGlobal("levels", levelFacade);
+ setGlobal("persistence", rulePersistence);
+ setGlobal("util", ruleUtil);
+ setGlobal("JSON", Container.JSON);
+ setGlobal("LOG", LOG);
try {
RuleExecutionLogger ruleExecutionLogger = new RuleExecutionLogger();
knowledgeSession.addEventListener(ruleExecutionLogger);
} catch (Throwable t) {
- LOG.fine("Exception in addEventListener");
+ throw new Exception(t);
}
LOG.fine("Rule engine started");
@@ -244,6 +202,14 @@ public abstract class RuleEngine extends EventProcessor {
kb = null;
}
+ protected void setGlobal(String identifier, Object object) {
+ try {
+ knowledgeSession.setGlobal(identifier, object);
+ } catch (Throwable t) {
+ // Ignore, Drools complains if the DRL doesn't declare the global, but it works
+ }
+ }
+
protected void addResources(KieServices kieServices, KieFileSystem kfs) {
getResources(kieServices).forEach(resource -> {
String sourcePath = resource.getSourcePath();
diff --git a/controller/src/main/java/org/openremote/controller/rules/RuleExecutionLogger.java b/controller/src/main/java/org/openremote/controller/rules/RuleExecutionLogger.java
index a83b6b791..2443dcd9e 100644
--- a/controller/src/main/java/org/openremote/controller/rules/RuleExecutionLogger.java
+++ b/controller/src/main/java/org/openremote/controller/rules/RuleExecutionLogger.java
@@ -82,11 +82,11 @@ public class RuleExecutionLogger extends DefaultAgendaEventListener {
if (antecedent instanceof Sensor) //may be unnecessary if we never have raw sensor objects in WM
{
Sensor theSensor = (Sensor) antecedent;
- String sensorName = theSensor.getName();
+ String sensorName = theSensor.getSensorDefinition().getName();
theValue = String.format("Sensor: %s\n", sensorName);
theValue = String.format("%s\t\tSensor Properties\n", theValue);
- Map<String, String> sensorValues = theSensor.getProperties();
+ Map<String, String> sensorValues = theSensor.getSensorDefinition().getProperties();
for (Map.Entry<String, String> entry : sensorValues.entrySet()) {
String entryName = entry.getKey();
@@ -119,7 +119,7 @@ public class RuleExecutionLogger extends DefaultAgendaEventListener {
if (declarationValue instanceof Sensor) //may be unnecessary if we never have raw sensor objects in WM
{
- convertedDeclarationValue = ((Sensor) declarationValue).getName();
+ convertedDeclarationValue = ((Sensor) declarationValue).getSensorDefinition().getName();
}
if (declarationValue instanceof Event) {
String sensorName = ((Event) declarationValue).getSource();
diff --git a/controller/src/main/java/org/openremote/controller/statuscache/StatusCache.java b/controller/src/main/java/org/openremote/controller/statuscache/StatusCache.java
index 9f905b757..d2fb9819c 100644
--- a/controller/src/main/java/org/openremote/controller/statuscache/StatusCache.java
+++ b/controller/src/main/java/org/openremote/controller/statuscache/StatusCache.java
@@ -42,8 +42,8 @@ public class StatusCache {
*/
private volatile Boolean isShutdownInProcess = false;
- public StatusCache(ChangedStatusTable cst, EventProcessorChain epc) {
- this.eventProcessorChain = epc;
+ public StatusCache(ChangedStatusTable cst, EventProcessorChain eventProcessorChain) {
+ this.eventProcessorChain = eventProcessorChain;
this.sensorMap = new SensorMap(cst);
}
@@ -57,29 +57,17 @@ public class StatusCache {
*
* @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]
-
+ public synchronized void registerAndStartSensor(Sensor sensor) {
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)...
-
+ Sensor previous = sensors.put(sensor.getSensorDefinition().getSensorID(), sensor);
if (previous != null) {
- throw new IllegalArgumentException(
- "Duplicate registration of sensor ID '" + sensor.getSensorID() + "', already registered as sensor named '" + previous.getName()
- );
+ throw new IllegalArgumentException("Duplicate registration: " + sensor.getSensorDefinition());
}
-
sensorMap.init(sensor);
- LOG.info("Registered sensor: " + sensor);
+ sensor.start(this);
+ LOG.info("Registered and started sensor: " + sensor);
}
/**
@@ -196,7 +184,6 @@ public class StatusCache {
private void stopSensors() {
for (Sensor sensor : sensors.values()) {
LOG.info("Stopping sensor: " + sensor);
-
try {
sensor.stop();
} catch (Throwable t) {
@@ -216,8 +203,8 @@ public class StatusCache {
}
private void init(Sensor sensor) {
- nameIdIndex.put(sensor.getName(), sensor.getSensorID());
- currentState.put(sensor.getSensorID(), new Sensor.UnknownEvent(sensor));
+ nameIdIndex.put(sensor.getSensorDefinition().getName(), sensor.getSensorDefinition().getSensorID());
+ currentState.put(sensor.getSensorDefinition().getSensorID(), new Sensor.UnknownEvent(sensor));
}
private Iterator<Event> getSnapshot() {
@@ -234,7 +221,7 @@ public class StatusCache {
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.updateStatusChangedIDs(sensor.getSensorDefinition().getSensorID());
}
deviceStatusChanges.clearAllRecords();
}
diff --git a/controller/src/main/resources/org/openremote/controller/schemas/controller-2.0-M7.xsd b/controller/src/main/resources/org/openremote/controller/schemas/controller-2.0-M7.xsd
new file mode 100644
index 000000000..b92df65af
--- /dev/null
+++ b/controller/src/main/resources/org/openremote/controller/schemas/controller-2.0-M7.xsd
@@ -0,0 +1,1181 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsd:schema xmlns:xsd = "http://www.w3.org/2001/XMLSchema"
+ xmlns = "http://www.openremote.org" targetNamespace = "http://www.openremote.org">
+
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ OpenRemote Controller XML Schema, version 2.0.
+ Authors: Juha Lindfors, Dan Cong, Javen Zhang.
+
+ This defines the following:
+
+ 1. device component: such as a switch or a slider... whose id is consistent with
+ the one in panel.xml
+ 2. status sensor : used to do polling to get current status of a device
+ 3. device command: such as "TV on", to support different device command protocol
+ 4. configuration: controller configuration properties
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <!--
+ =================================================================================================
+
+ Top-level <openremote> tag
+
+ =================================================================================================
+ -->
+ <xsd:element name = "openremote">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ The top level (typically root) element.
+
+ The document is structured into four main sections: components, sensors, commands and
+ configuration.
+
+ Components aggregate sets of commands and sensors into component level abstractions such
+ as switches, sliders, labels, and so on. These are directly mapped via their ID to their
+ corresponding panel UI widgets.
+
+ Sensors abstract incoming events from devices, either through polling or listening to
+ devices that actively broadcast their state changes. Sensors are bound to components
+ that support displaying state changes via sensor's ID attribute. Sensors in this
+ revision support four distinct datatypes: boolean switches (on/off), arbitrary range
+ values (integers), a specific level range (integer between 0-100) and finite set of
+ custom state strings.
+
+ Commands abstract device read and write requests to protocol level wire format. Commands
+ support set of properties that can be used to translate them to the desired protocol
+ payload or serialization format. Protocol integration and adding new protocols happens
+ via this abstraction.
+
+ Configuration section are controller configuration properties that can be used to
+ change the behavior of the controller itself either by editing the configuration locally
+ or through online tools.
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element ref = "components" />
+ <xsd:element ref = "sensors" />
+ <xsd:element ref = "commands" />
+ <xsd:element ref = "config" />
+ </xsd:sequence>
+ </xsd:complexType>
+
+ <xsd:unique name="uniqueIdsAccrossWholeDocument">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+ Ensures that id field has unique value throught the whole document.
+ All such fields should be of type idType.
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:selector xpath=".//*"/>
+ <xsd:field xpath="@id"/>
+ </xsd:unique>
+ </xsd:element>
+
+
+
+ <!--
+ =================================================================================================
+
+ Section <components> tag
+
+ =================================================================================================
+ -->
+ <xsd:element name = "components">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ A component collection which includes components such as button, switch,
+ gesture, label, etc.
+
+ Each component is associated with an ID that is bound to a corresponding ID on the
+ panel UI via panel.xml definition. This ID is also exposed through the controller's
+ REST interface. Therefore, the panel definitions and implementations are independent
+ of the protocol details and mappings on the controller and operate purely on the
+ component ID (and to some extent, sensor ID) level of abstraction.
+
+ Components aggregate protocol commands and sensors into a logical entity that can
+ also be referenced through the controller's rule and scripting interfaces.
+
+ This element itself aggregates further component elements, i.e.
+
+ <openremote ...>
+ <components>
+ <[component]>
+ ...
+ <[component]/>
+
+ <[component]>
+ ...
+ <[component]/>
+
+ <[component]>
+ ...
+ <[component]/>
+ </components>
+
+ <sensors>
+ ...
+ </sensors>
+ ...
+ </openremote>
+
+ Where [component] tags above are specific types of component elements, e.g. switch,
+ image, slider, label, etc.
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:group ref = "componentGroup" minOccurs = "0" maxOccurs = "unbounded"></xsd:group>
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+ <!--
+ =================================================================================================
+
+ Section <sensors> tag
+
+ =================================================================================================
+ -->
+ <xsd:element name = "sensors">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ Collection of sensors defined for the controller.
+
+ Sensors operate on protocol handlers to execute read requests on devices to fetch the
+ current device state, either through polling commands (for 'passive' devices) or through
+ event listener implementations on devices that actively broadcast their state changes.
+
+ A sensor can be bound to one or many components via its ID attribute. The currently held
+ in-memory state of the sensor can also be retrieved through controller's REST/XML/JSON
+ interface using the ID attribute.
+
+ In the current controller revision, each polling sensor (passive devices) has an active
+ thread associated with it in the Java runtime. This facilitates concurrent retrieval of
+ device state. Sensors bound to event listeners do not create threads of their own but
+ the event listener implementations themselves are usually multi-threaded.
+
+ This element itself groups all sensors in the controller, i.e.
+
+ <openremote ...>
+ <components>
+ ...
+ </components>
+
+ <sensors>
+ <sensor id = "nnn" name = "Sensor's human readable name"
+ type = "[switch|range|level|custom]">
+
+ <include type = "command" ref = "nnn"/>
+
+ <[property]/>
+ <[property]/>
+ </sensor>
+
+ <sensor ...>
+ ...
+ </sensor>
+ </sensors>
+
+ <commands>
+ ...
+ </commands>
+ ...
+ </openremote>
+
+ Where in addition to an ID, each sensor has a (human-readable) name and a datatype.
+
+ Sensors bind themselves to protocols via the command association through a child
+ <include> element. Whether a sensor is actively polling a device or actively listening
+ to device broadcasts depends on the protocol command implementation it is bound to.
+
+ In addition, sensors may have specific list of property elements depending on its
+ datatype. For example, range-type sensors have additional propery elements <min> and
+ <max> that define the range boundaries. Custom-type sensors define a finite set of
+ states they may return via explicit <state> property elements.
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element ref = "sensor" minOccurs = "0" maxOccurs = "unbounded"/>
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+
+
+ <!--
+ =================================================================================================
+
+ Section <commands> tag
+
+ =================================================================================================
+ -->
+ <xsd:element name = "commands">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ Commands represent protocol handlers that are used to bind actions through panel user
+ interfaces, scripts and rules to protocol-specific serialization or payload details.
+
+ Commands are constructed as protocol-specific property lists where details of the
+ properties and their values are left to protocol implementers to resolve. A command
+ can represent either a read (poll) command or write command, an event listener, or some
+ other suitable protocol structure.
+
+ Commands are bound to either sensors (read commands and event listeners) or to components
+ directly (write commands) through their ID referenced in the <include> of components
+ and sensors.
+
+ This element itself groups all protocol handlers in the controller, i.e.
+
+ <openremote ...>
+ ...
+ <sensors>
+ ...
+ </sensors>
+
+ <commands>
+ <command id = "nnn" protocol = "protocol-id">
+ <property name = "property-name" value = "property-value"/>
+ <property name = "property-name" value = "property-value"/>
+ </command>
+
+ <command id = "nnn" protocol = "protocol-id">
+ <property name = "property-name" value = "property-value"/>
+ <property name = "property-name" value = "property-value"/>
+ </command>
+
+ <command id = "nnn" protocol = "protocol-id">
+ <property name = "property-name" value = "property-value"/>
+ <property name = "property-name" value = "property-value"/>
+ </command>
+ </commands>
+
+ <config>
+ ...
+ </config>
+ </openremote>
+
+ Where a "protocol-id" attribute uniquely identifies a protocol implementation, and
+ "property-name" and "property-value" attributes are name-value pairs that contain
+ protocol implementation-specific details.
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element ref = "command" minOccurs = "0" maxOccurs = "unbounded"/>
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+ <!--
+ =================================================================================================
+
+ Identifier (component, sensor, command) definition.
+
+ =================================================================================================
+ -->
+ <xsd:simpleType name = "idType">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ This is a unique natural number (upper bound 32-bit signed integer) identifier shared
+ by all types within a controller.xml document instance, including component IDs,
+ sensor IDs and command IDs.
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:restriction base = "xsd:int">
+ <xsd:minInclusive value = "1"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <!--
+ =================================================================================================
+
+ Component types (child element of <components>)
+
+ =================================================================================================
+ -->
+ <xsd:group name = "componentGroup">
+ <xsd:annotation>
+ <xsd:documentation>
+ <![CDATA[
+
+ Specific component definitions. Components aggregate protocol handling commands and
+ sensor into logical groups based on the type of the component. Component's ID is
+ directly bound to panel UI widget IDs at a logical level (but not exposing protocol
+ mapping details). Component definitions are also useful abstractions with the
+ scripting and rules used within the controller.
+
+ Current revision supports the following types of components:
+
+ 1. Switches - two write commands to set device to on/off, sensor for reading (boolean)
+ on/off state from device
+ 2. Slider - one write command to set device or property to a new (integer) value,
+ one sensor (range or level datatype) to read current device value
+ 3. Button - one write command to send a new value to device
+
+ 4. Label - one sensor to display a text representation of a bound
+ sensor value
+ 5. Image - one sensor to display an image corresponding to a specified state value
+ returned by a sensor (switch-type sensor or custom sensor)
+ 6. ColorPicker - one write command to send a new value to device
+
+ ]]>
+ </xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:choice>
+ <xsd:element ref = "switch" />
+ <xsd:element ref = "slider"/>
+ <xsd:element ref = "button"/>
+ <xsd:element ref = "label" />
+ <xsd:element ref = "gesture" />
+ <xsd:element ref = "image"/>
+ <xsd:element ref = "colorpicker"/>
+ </xsd:choice>
+ </xsd:group>
+
+
+
+
+ <!--
+ =================================================================================================
+
+ Switch Component (child element of <components>)
+
+ =================================================================================================
+ -->
+ <xsd:element name = "switch">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ Switch component is a two-state on/off switch with separate command sequences for
+ both 'on' and 'off' functionality and a configurable sensor to reflect the device's
+ current state.
+
+ Both 'on' and 'off' command sequences may include multiple commands that are executed
+ in response to a switch state change. A sensor bound to a switch component must also
+ have 'switch' as its datatype.
+
+ A switch component must have a controller unique integer identifier.
+
+ An example of a switch component definition might look like this:
+
+ <components>
+ <switch id = "nnn">
+ <on>
+ <include type = "command" ref = "nnn" />
+ <include type = "command" ref = "nnn" />
+ <include type = "command" ref = "nnn" />
+ </on>
+
+ <off>
+ <include type = "command" ref = "nnn" />
+ </off>
+
+ <include type = "sensor" ref = "nnn" />
+ </switch>
+ ...
+ </components>
+
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element ref = "on" minOccurs = "1" maxOccurs = "1"/>
+ <xsd:element ref = "off" minOccurs = "1" maxOccurs = "1" />
+ <xsd:element ref = "include" minOccurs = "0" maxOccurs = "unbounded"/>
+ </xsd:sequence>
+ <xsd:attribute name = "id" type = "idType" use = "required" />
+ </xsd:complexType>
+ </xsd:element>
+
+
+ <!-- ===== SWITCH 'ON' OPERATION ===== -->
+
+ <xsd:element name = "on">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ The 'on' operation of a switch. The contents can be one or more <include> and <delay>
+ elements that defines the sequence of write commands (and optional delays between
+ commands) that should be executed in response to a switch 'on' state change request.
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:group ref = "macroGroup" />
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+
+
+ <!-- ===== SWITCH 'OFF' OPERATION ===== -->
+
+ <xsd:element name = "off">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ The 'off' operation of a switch. The contents can be one or more <include> and <delay>
+ elements that defines the sequence of write commands (and optional delays between
+ commands) that should be executed in response to a switch 'off' state change request.
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:group ref = "macroGroup" />
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+ <!--
+ =================================================================================================
+
+ Slider Component (child element of <components>)
+
+ =================================================================================================
+ -->
+ <xsd:element name = "slider">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ Slider component can be used to send a range of integer values to a device depending
+ on slider state. Sliders can be 'active' in a sense that they can allow users to
+ actively change their value (usually through an UI widget that allows a new value to
+ be set), or passive ('read-only') in a sense that they only update and display current
+ sensor state without allowing user to make updates.
+
+ The 'setValue' operation is used to reference a write command which sets a new device
+ value in response to a slider modification in the panel UI, or a script or rule in
+ the controller. A sensor bound using 'include' element to a slider component is
+ used to update the slider value in response to an event from a read command or event
+ listener.
+
+ A slider component must have a controller unique integer identifier.
+
+ An example of a slider component definition might look like this:
+
+ <components>
+ <slider id = "nnn">
+ <setValue>
+ <include type = "command" ref = "nnn" />
+ </setValue>
+
+ <include type = "sensor" ref = "nnn" />
+ </slider>
+ ...
+ </components>
+
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element ref = "setValue" minOccurs = "0" maxOccurs = "unbounded"/>
+ <xsd:element ref = "include" minOccurs = "0" maxOccurs = "unbounded"/>
+ </xsd:sequence>
+ <xsd:attribute name = "id" type = "idType" use = "required" />
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+ <!-- ===== SLIDER 'SETVALUE' OPERATION ===== -->
+
+ <xsd:element name = "setValue">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ Specifies one or more write commands (using a nested <include> elements) that is used
+ to update device(s) in response to a slider component update.
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element ref = "include" minOccurs = "0" maxOccurs = "unbounded"/>
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+ <!--
+ =================================================================================================
+
+ Button Component (child element of <components>)
+
+ =================================================================================================
+ -->
+ <xsd:element name = "button">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ A button component is a simple one-way component to send write commands to a device.
+ One or more commands may be sent in sequence, and delays can be used where necessary
+ between commands.
+
+ A button component must have a controller unique integer identifier.
+
+ An example button element is as follows:
+
+ <components>
+ <button id = "nnn">
+ <include type = "command" ref = "nnn" />
+ <include type = "command" ref = "nnn" />
+ <delay>500</delay>
+ <include type = "command" ref = "nnn" />
+ </button>
+ ...
+ </components>
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:group ref = "macroGroup" minOccurs = "0" maxOccurs = "unbounded"/>
+ </xsd:sequence>
+ <xsd:attribute name = "id" type = "idType" use = "required" />
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+
+ <!--
+ =================================================================================================
+
+ ColorPicker Component (child element of <components>)
+
+ =================================================================================================
+ -->
+ <xsd:element name="colorpicker">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ A color picker component is a simple one-way component to send write commands to a device.
+ One or more commands may be sent in sequence but no delays are allowed.
+
+ A color picker component must have a controller unique integer identifier.
+
+ An example color picker element is as follows:
+
+ <components>
+ <colorpicker id = "nnn">
+ <include type = "command" ref = "nnn" />
+ <include type = "command" ref = "nnn" />
+ </colorpicker>
+ ...
+ </components>
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element ref="include" minOccurs="0" maxOccurs="unbounded"/>
+ </xsd:sequence>
+ <xsd:attribute name="id" type="idType" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+
+ <!--
+ =================================================================================================
+
+ Label Component (child element of <components>)
+
+ =================================================================================================
+ -->
+ <xsd:element name = "label">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ A 'label' component is controller-side representation of an UI label widget that may
+ be updated based on a sensor value.
+
+ A label component may include a single 'sensor' type which is used as an input for
+ a dynamic UI labels content.
+
+ A label component must have a controller unique integer identifier.
+
+ An example label element is as follows:
+
+ <components>
+ <label id = "nnn">
+ <include type = "sensor" ref = "nnn" />
+ </label>
+ ...
+ </components>
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element ref = "include" minOccurs = "0" maxOccurs = "unbounded"/>
+ </xsd:sequence>
+ <xsd:attribute name = "id" type = "idType" use = "required" />
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+ <!--
+ =================================================================================================
+
+ Image Component (child element of <components>)
+
+ =================================================================================================
+ -->
+ <xsd:element name = "image">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ An 'image' component is controller-side representation of a panel UI image that may
+ be updated based on a sensor value.
+
+ An image component may include a single 'sensor' type which is used as an input for
+ a dynamic UI image content.
+
+ An image component must have a controller unique integer identifier.
+
+ An example image element is as follows:
+
+ <components>
+ <image id = "nnn">
+ <include type = "sensor" ref = "nnn" />
+ </image>
+ ...
+ </components>
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element ref = "include" minOccurs = "0" maxOccurs = "unbounded"/>
+ </xsd:sequence>
+ <xsd:attribute name = "id" type = "idType" use = "required" />
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+ <!--
+ =================================================================================================
+
+ Gesture (child element of <components>)
+
+ =================================================================================================
+ -->
+ <xsd:element name = "gesture">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ A gesture component represents a command executed on the controller-side
+ in response to a user gesture on the panel UI.
+
+ A gesture component must have a controller unique integer identifier.
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:group ref = "macroGroup" minOccurs = "0" maxOccurs = "unbounded"/>
+ </xsd:sequence>
+ <xsd:attribute name = "id" type = "idType" use = "required" />
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+
+ <!--
+ =================================================================================================
+
+ Sensor definition (child element of <sensors>)
+
+ =================================================================================================
+ -->
+ <xsd:element name = "sensor">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ Sensor definition. Sensors abstract events of external device state, either through polling
+ (explicit device read requests) or through event listeners (listening for active device state
+ broadcasts).
+
+ A sensor is bound to one or many components through its unique identifier. A sensor is
+ associated with a datatype that indicates the types of values it can return.
+
+ The current revision supports following datatypes for sensors: switch, level,
+ range and custom state. Component types may place restrictions on what types of sensors
+ they can be associated with.
+
+ Sensors are associated with an active thread in the Java runtime. Sensors associated with
+ read commands (polling) have a thread associated each. Sensors associated with event
+ listeners do not create active threads on behalf of the controller but often create
+ listening threads as part of the protocol implementation.
+
+ Sensor state can be also retrieved directly through controller's REST API using the
+ sensor's unique identifier as key. See
+ http://www.openremote.org/display/docs/Controller+2.0+API+Documentation for additional
+ detail.
+
+ A typical sensor element in a controller.xml document looks like this:
+
+ ...
+ <sensors>
+ <sensor id = "nnn" type = "[switch|level|range|custom]" name = "Doorbell">
+ ...
+ </sensor>
+ </sensors>
+ ...
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:group ref = "sensorGroup" minOccurs = "0" maxOccurs = "unbounded" />
+ </xsd:sequence>
+ <xsd:attribute name = "id" type = "idType" use = "required" />
+ <xsd:attribute name = "type" type = "sensorType" use = "required" />
+ <xsd:attribute name = "name" type = "xsd:string" use = "required" />
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+ <!-- ===== SENSOR PROPERTIES ===== -->
+
+ <xsd:group name="sensorGroup">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ A sensor may contain additional child elements that further defines its properties.
+ Sensor properties may be optional or mandatory depending the sensor's type.
+
+ In addition, a sensor has an <include> element which references the 'event producer'
+ the sensor uses to collect its state values. An event producer is either a polling
+ read command or an event listener. Both types of event producers use the sensor's
+ unique identifier as a key to store device state to controller's in-memory state
+ cache.
+
+ The following sensor properties are used with specified sensor types:
+
+ 1. Switch sensor -- No mandatory additional sensor properties. May use <state> elements
+ to map "on" and "off" states to other values (for example to
+ "open" and "close" for a door sensor) which may in turn be bound to
+ a label component which is able to display customized values. This
+ state mapping mechanism may also be used to translate textual
+ descriptions of the switch state to localized languages.
+
+ 2. Range sensor -- Mandatory <min> and <max> elements are used to define the boundary
+ values of the range sensor.
+
+ 3. Level sensor -- No additional sensor properties. Has an implicit range of [0-100]
+ to which the device range values are scaled to.
+
+ 4. Custom sensor -- Maps specific state values from device to an alternative values
+ exposed to panels via a <state> elements
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+ <xsd:choice>
+ <xsd:element ref = "include" minOccurs = "0" maxOccurs = "unbounded" />
+ <xsd:element ref = "state" minOccurs = "0" maxOccurs = "unbounded" />
+ <xsd:element ref = "min" minOccurs = "0" maxOccurs = "1" />
+ <xsd:element ref = "max" minOccurs = "0" maxOccurs = "1" />
+ </xsd:choice>
+ </xsd:group>
+
+
+ <!-- Sensor <min> property -->
+
+ <xsd:element name = "min">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ The <min> property defines the lower boundary of a range. Valid (and mandatory)
+ for range-type sensors.
+
+ An example of a range sensor definition:
+
+ ...
+ <sensors>
+ <sensor id = "nnn" name = "Outdoor Temp" type = "range">
+ <min value = "-50"/>
+ <max value = "50"/>
+ <include type = "command" ref = "mmm"/>
+ </sensor>
+ </sensors>
+ ...
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:attribute name = "value" type = "xsd:int" use = "required" />
+ </xsd:complexType>
+ </xsd:element>
+
+
+ <!-- Sensor <max> property -->
+
+ <xsd:element name = "max">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ The <max> property defines the upper boundary of a range. Valid (and mandatory)
+ for range-type sensors.
+
+ An example of a range sensor definition:
+
+ ...
+ <sensors>
+ <sensor id = "nnn" name = "Outdoor Temp" type = "range">
+ <min value = "-50"/>
+ <max value = "50"/>
+
+ <include type = "command" ref = "mmm"/>
+ </sensor>
+ </sensors>
+ ...
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:attribute name = "value" type = "xsd:int" use = "required" />
+ </xsd:complexType>
+ </xsd:element>
+
+
+ <!-- Sensor <state> property -->
+
+ <xsd:element name = "state">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ The <state> property defines a finite set of explicit state values that a custom-state
+ sensor may return. If a value is also defined then the sensor's return values are mapped
+ to the state names as well. This can be used for mapping explicit state values to more
+ human-consumable values for the panel UI for example, or as a translation mechanism for
+ localized interfaces.
+
+ When both name and value attributes are defined in a <state> element, it can also be used
+ with a switch-type sensor to translate the usual on/off values to other values.
+
+ An example of a custom-type sensor is as follows:
+
+ ...
+ <sensors>
+ <sensor id = "nnn" name = "Cloud Report" type = "custom">
+ <state name = "Rain Clouds"/>
+ <state name = "Cloudy"/>
+ <state name = "Partly Cloudy"/>
+ <state name = "Sunny"/>
+
+ <include type = "command" ref = "mmm"/>
+ </sensor>
+ </sensors>
+ ...
+
+ Where in the above example, the sensor accepts four distinct values from the referenced
+ event producer (read command or event listener).
+
+ A mapping sensor could be used as follows:
+
+ ...
+ <sensors>
+ <sensor id = "nnn" name = "Cloud Report" type = "custom">
+ <state name = "Rain Clouds" value = "1" />
+ <state name = "Cloudy" value = "2" />
+ <state name = "Partly Cloudy" value = "3" />
+ <state name = "Sunny" value = "4" />
+
+ <include type = "command" ref = "mmm"/>
+ </sensor>
+ </sensors>
+ ...
+
+ In the example above, the event producer returns values ranging from one to four which
+ are then mapped to descriptive string values in the controller's in-memory device state
+ cache. This sensor with descriptive string values can then be bound to a label
+ component in the panel UI, for example, allowing it to display user-friendly description
+ of the data returned by the event producers.
+
+ Finally, the same mechanism can be used to translate events from event producers, in
+ this case from a boolean switch sensor :
+
+ ...
+ <sensors>
+ <sensor id = "nnn" name = "Localized Door Sensor" type = "switch">
+ <state name = "Ouvert" value = "on" />
+ <state name = "Ferme" value = "off" />
+
+ <include type = "command" ref = "mmm"/>
+ </sensor>
+ </sensors>
+ ...
+
+ Note that the event processing chain in the controller's in-memory state cache can
+ be used for similar effect and for more complex processing use-cases. Also bear in
+ mind that UI rendering components bound to such sensor must support the known state
+ strings or arbitrary state strings.
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:attribute name = "name" use = "required" />
+ <xsd:attribute name = "value" use = "optional" />
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+ <!-- ===== SENSOR DATATYPES ===== -->
+
+ <xsd:simpleType name = "sensorType">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ Sensor data type definitions:
+
+ 1) Switch: returns boolean 'on' or 'off' strings
+ 2) Level: An integer value as a string that is scaled to an implicit range of [0-100]
+ 3) Range: Integer value as a string within a given boundary range
+ 5) Custom: A customized finite set of state strings
+
+ ]]>
+ </xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:restriction base = "xsd:string">
+ <xsd:enumeration value = "switch" />
+ <xsd:enumeration value = "level" />
+ <xsd:enumeration value = "range" />
+ <xsd:enumeration value = "color" />
+ <xsd:enumeration value = "custom" />
+ </xsd:restriction>
+ </xsd:simpleType>
+
+
+
+
+ <!--
+ =================================================================================================
+
+ Protocol Handler (Command) definition (child element of <commands>)
+
+ =================================================================================================
+ -->
+ <xsd:element name = "command">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ Defines a protocol handler (command). Commands are created to handle protocol specific
+ behavior when necessary to invoke either from sensors or components. Commands can
+ represent device write requests, device state read requests or other protocol specific
+ functionality, as necessary (for example, event listeners).
+
+ A command has a mandatory per controller unique identifier that is used to bind it to
+ sensors and components. A single command definition can be bound to multiple components
+ and sensors.
+
+ Command also has a protocol identifier which is used to map its implementation to an
+ appropriate protocol in the controller. The valid values for 'protocol' attribute
+ depend on the controller's configuration -- which protocols have been installed and
+ what protocol identifiers they use.
+
+ A generic form of a <command> element in a controller.xml document is therefore:
+
+ <command id = "nnn" protocol = "protocol-id">
+ <property ... />
+ <property ... />
+ ...
+ </command>
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element ref = "property" minOccurs = "0" maxOccurs = "unbounded"/>
+ </xsd:sequence>
+ <xsd:attribute name = "id" type = "idType" use = "required" />
+ <xsd:attribute name = "protocol" type = "xsd:string" use = "required"/>
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+ <!--
+ =================================================================================================
+
+ INCLUDE ELEMENT
+
+ =================================================================================================
+ -->
+ <xsd:element name="include">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ Include element is used by components and sensors to reference to other components,
+ sensors or protocol handlers (commands).
+
+ The 'type' attribute indicates what type of component is being included or referenced.
+ Currently valid values are either 'sensor' or 'command'.
+
+ The 'ref' attribute must be the unique identifier of the referenced component or command.
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:attribute name = "type" type = "xsd:string" />
+ <xsd:attribute name = "ref" type = "idType" />
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+ <!--
+ =================================================================================================
+
+ PROPERTY ELEMENT
+
+ =================================================================================================
+ -->
+ <xsd:element name = "property">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ Property element is used for setting protocol handler (command) properties, controller
+ configuration properties, etc.
+
+ Property element is a name-value pair where name attributes are strings and value
+ attributes are string representations of datatypes (another string, integer as
+ string, etc.)
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:attribute name = "name" type = "xsd:string" use = "required" />
+ <xsd:attribute name = "value" type = "xsd:string" use = "required" />
+ </xsd:complexType>
+ </xsd:element>
+
+
+
+ <!--
+ =================================================================================================
+
+ Macro group definition.
+
+ =================================================================================================
+ -->
+ <xsd:group name = "macroGroup">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ A macro group defines a sequence of write commands (and optionally delays) that are
+ executed in response to a component invocation for components that support macro
+ inclusion.
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:choice>
+ <xsd:element ref = "delay" minOccurs = "0" maxOccurs = "unbounded"/>
+ <xsd:element ref = "include" minOccurs = "0" maxOccurs = "unbounded"/>
+ </xsd:choice>
+ </xsd:group>
+
+
+ <!--
+ =================================================================================================
+
+ DELAY ELEMENT
+
+ =================================================================================================
+ -->
+ <xsd:element name = "delay" type = "xsd:int" >
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ Defines a delay in milliseconds that can be used in a macro sequence.
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+ </xsd:element>
+
+
+
+
+ <!--
+ =================================================================================================
+
+ Section <config> tag
+
+ =================================================================================================
+ -->
+ <xsd:element name="config">
+ <xsd:annotation>
+ <xsd:documentation><![CDATA[
+
+ The <config> section is used to override default system configurations of controller
+
+
+ ]]></xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element ref = "property" minOccurs = "0" maxOccurs = "unbounded" />
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+
+</xsd:schema>
diff --git a/controller/src/test/groovy/org/openremote/test/rules/Bak.java b/controller/src/test/groovy/org/openremote/test/rules/Bak.java
deleted file mode 100644
index 5e689d89e..000000000
--- a/controller/src/test/groovy/org/openremote/test/rules/Bak.java
+++ /dev/null
@@ -1,1112 +0,0 @@
-package org.openremote.test.rules;
-
-public class Bak {
-
-//
-// /**
-// * 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
-// }
-//
-// }
-
-}
-
diff --git a/controller/src/test/groovy/org/openremote/test/rules/ClimateControlTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/ClimateControlTest.groovy
index a6f8b5f9e..96a373176 100644
--- a/controller/src/test/groovy/org/openremote/test/rules/ClimateControlTest.groovy
+++ b/controller/src/test/groovy/org/openremote/test/rules/ClimateControlTest.groovy
@@ -4,11 +4,9 @@ import org.kie.api.KieServices
import org.kie.api.io.Resource
import org.openremote.controller.ControllerService
import org.openremote.controller.command.ExecutableCommand
-import org.openremote.controller.command.ExecutableCommandFactory
-import org.openremote.controller.event.CommandFacade
-import org.openremote.controller.event.CustomStateEvent
+import org.openremote.controller.command.CommandFactory
+import org.openremote.controller.event.facade.CommandFacade
import org.openremote.controller.event.EventProcessorChain
-import org.openremote.controller.event.SwitchEvent
import org.openremote.controller.model.CommandDefinition
import org.openremote.controller.rules.RuleEngine
import org.openremote.test.ContainerTrait
@@ -21,7 +19,12 @@ class ClimateControlTest extends Specification implements ContainerTrait {
def "Climate control basic test"() {
- given: "event processors and rules"
+ given: "a controller deployment"
+ def controllerDeploymentXml = getClass().getResourceAsStream(
+ "/org/openremote/test/rules/climatecontrol/controller.xml"
+ )
+
+ and: "event processors and rules"
def ruleEngineProcessor = new RuleEngine() {
@Override
protected Stream<Resource> getResources(KieServices kieServices) {
@@ -34,32 +37,15 @@ class ClimateControlTest extends Specification implements ContainerTrait {
}
def grabProcessor = new EventGrabProcessor();
- String lastCommandValue = null
- int totalCommandCount = 0
- def commandFactory = new ExecutableCommandFactory() {
- @Override
- protected ExecutableCommand buildCommand(CommandDefinition commandDefinition) {
- return new ExecutableCommand() {
- @Override
- void send(String value) {
- lastCommandValue = value
- totalCommandCount++
- }
- }
- }
- }
- def commandDefinitions = [
- new CommandDefinition(commandFactory, 11, "test", [(CommandDefinition.NAME_PROPERTY): "temp"])
- ]
- def commandFacade = new CommandFacade(commandDefinitions)
- def eventProcessorChain = new EventProcessorChain(
- commandFacade,
+
+ and: "the started controller server"
+ def testCommandFactory = new TestCommandFactory();
+ def controllerService = new ControllerService(
+ controllerDeploymentXml,
+ testCommandFactory,
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)
diff --git a/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovy
index 91a990f5c..776b00f4f 100644
--- a/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovy
+++ b/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovy
@@ -3,15 +3,9 @@ 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
@@ -25,7 +19,12 @@ class MixedWithErrorsTest extends Specification implements ContainerTrait {
def "Execute good rules - ignore broken rules"() {
- given: "some sensor event processors and rules"
+ given: "a controller deployment"
+ def controllerDeploymentXml = getClass().getResourceAsStream(
+ "/org/openremote/test/rules/mixed-with-errors/controller.xml"
+ )
+
+ and: "some sensor event processors and rules"
def ruleEngineProcessor = new RuleEngine() {
@Override
protected Stream<Resource> getResources(KieServices kieServices) {
@@ -47,164 +46,24 @@ class MixedWithErrorsTest extends Specification implements ContainerTrait {
}
def grabProcessor = new EventGrabProcessor()
- def commandDefinitions = []
- def commandFacade = new CommandFacade(commandDefinitions)
- def eventProcessorChain = new EventProcessorChain(
- commandFacade,
+ and: "the started controller server"
+ def testCommandFactory = new TestCommandFactory();
+ def controllerService = new ControllerService(
+ controllerDeploymentXml,
+ testCommandFactory,
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!
+ when: "we wait a bit for initial state and rules to fire"
+ Thread.sleep(500)
- and: "the total event couht should match"
- grabProcessor.totalEventCount == 5
+ then: "the state should match"
+ controllerService.getCache().queryStatus(444) == "12345" // TODO This should be limited to max, which is 1000
+ controllerService.getCache().queryStatus(555) == "55"
cleanup: "the server should be stopped"
stopContainer(container)
diff --git a/controller/src/test/groovy/org/openremote/test/rules/SimpleRuleTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/SimpleRuleTest.groovy
index 56052805d..e8149585e 100644
--- a/controller/src/test/groovy/org/openremote/test/rules/SimpleRuleTest.groovy
+++ b/controller/src/test/groovy/org/openremote/test/rules/SimpleRuleTest.groovy
@@ -3,20 +3,14 @@ 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.
@@ -25,57 +19,42 @@ class SimpleRuleTest extends Specification implements ContainerTrait {
def "Sensor event replaced by rule-triggered event"() {
- given: "event processors and rules"
+ given: "a controller deployment"
+ def controllerDeploymentXml = getClass().getResourceAsStream(
+ "/org/openremote/test/rules/simple/controller.xml"
+ )
+
+ and: "event processors and rules"
def ruleEngineProcessor = new RuleEngine() {
@Override
protected Stream<Resource> getResources(KieServices kieServices) {
Stream.of(
kieServices.getResources().newClassPathResource(
"org/openremote/test/rules/simple/EventMod.drl"
- ).setResourceType(DRL)
+ )
)
}
}
def grabProcessor = new EventGrabProcessor();
- def commandDefinitions = []
- def commandFacade = new CommandFacade(commandDefinitions)
- def eventProcessorChain = new EventProcessorChain(
- commandFacade,
+ and: "the started controller server"
+ def controllerService = new ControllerService(
+ controllerDeploymentXml,
+ new TestCommandFactory(),
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);
+ when: "we wait for initial state polling of sensor and rule execution"
+ Thread.sleep(500);
then: "the rules should immediately switch the sensor off again"
def lastEvent = grabProcessor.lastEvent;
- lastEvent.getSourceID() == sensorId
- lastEvent.getSource() == sensorName
+ lastEvent.getSourceID() == 123
+ lastEvent.getSource() == "TestSensor"
lastEvent instanceof SwitchEvent
def grabbedSwitchEvent = (SwitchEvent) lastEvent;
grabbedSwitchEvent.getValue() == "off"
@@ -85,7 +64,27 @@ class SimpleRuleTest extends Specification implements ContainerTrait {
grabProcessor.totalEventCount == 1
and: "the cache state of the sensor should be 'off'"
- controllerService.getCache().queryStatus(sensorId) == "off"
+ controllerService.getCache().queryStatus(123) == "off"
+
+ and: "the deployment model should work"
+ controllerService.getDeployment().getCommandDefinition(456).getCommandID() == 456
+ controllerService.getDeployment().getCommandDefinition(123123) == null
+ controllerService.getDeployment().getCommandDefinition("TestDevice", "TestCommand").getCommandID() == 456
+ controllerService.getDeployment().getCommandDefinition("TestDevice", "NoSuchThing") == null
+ controllerService.getDeployment().getCommandDefinition("NoSuchThing", "NoSuchThing") == null
+ controllerService.getDeployment().getCommandDefinition("", "") == null
+ controllerService.getDeployment().getCommandDefinition(null, "") == null
+ controllerService.getDeployment().getCommandDefinition("", null) == null
+ controllerService.getDeployment().getCommandDefinition(null, null) == null
+ controllerService.getDeployment().getCommandDefinition("TestCommand").getCommandID() == 456
+ controllerService.getDeployment().getCommandDefinition("NoSuchThing") == null
+ controllerService.getDeployment().getCommandDefinition("") == null
+ controllerService.getDeployment().getCommandDefinition(null) == null
+ controllerService.getDeployment().getDevices().length == 1
+ controllerService.getDeployment().getDevices()[0].getName() == "TestDevice"
+ controllerService.getDeployment().getDevices()[0].getDeviceID() == 111
+ controllerService.getDeployment().getDevice("TestDevice").getName() == "TestDevice"
+ controllerService.getDeployment().getDevice("TestDevice").getDeviceID() == 111
cleanup: "the server should be stopped"
stopContainer(container)
diff --git a/controller/src/test/groovy/org/openremote/test/rules/TestCommandFactory.java b/controller/src/test/groovy/org/openremote/test/rules/TestCommandFactory.java
new file mode 100644
index 000000000..6461389ef
--- /dev/null
+++ b/controller/src/test/groovy/org/openremote/test/rules/TestCommandFactory.java
@@ -0,0 +1,51 @@
+package org.openremote.test.rules;
+
+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 org.openremote.controller.model.CommandDefinition;
+
+import java.util.logging.Logger;
+
+public class TestCommandFactory extends CommandFactory {
+
+ private static final Logger LOG = Logger.getLogger(TestCommandFactory.class.getName());
+
+ public String lastExecutionArgument;
+
+ interface TestPullCommand extends PullCommand {
+ @Override
+ default int getPollingInterval() {
+ return 10000; // We don't want polling to happen in "quick" tests (we get initial state poll)
+ }
+ }
+
+ @Override
+ public Command build(CommandDefinition commandDefinition) {
+ Command command = super.build(commandDefinition);
+ if (command != null)
+ return command;
+
+ if (!commandDefinition.getProtocolType().equals("test"))
+ throw new IllegalArgumentException("Don't know how to build protocol: " + commandDefinition.getProtocolType());
+
+ switch(commandDefinition.getProperty("what-are-we-testing")) {
+ case "a-test-custom-state":
+ return (TestPullCommand) sensor -> "foo";
+ case "a-test-switch":
+ return (TestPullCommand) sensor -> "on";
+ case "a-test-range":
+ return (TestPullCommand) sensor -> "123";
+ case "a-test-level":
+ return (TestPullCommand) sensor -> "55";
+ case "an-executable-command":
+ return (ExecutableCommand) value -> {
+ LOG.info("### Executing " + commandDefinition + " with arg: " + value);
+ lastExecutionArgument = value;
+ };
+ default:
+ throw new UnsupportedOperationException("Can't build test command: " + commandDefinition);
+ }
+ }
+}
diff --git a/controller/src/test/groovy/org/openremote/test/rules/VacationTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/VacationTest.groovy
index 768259cfc..217ee01aa 100644
--- a/controller/src/test/groovy/org/openremote/test/rules/VacationTest.groovy
+++ b/controller/src/test/groovy/org/openremote/test/rules/VacationTest.groovy
@@ -3,13 +3,8 @@ 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.command.ExecutableCommand
-import org.openremote.controller.command.ExecutableCommandFactory
-import org.openremote.controller.event.CommandFacade
import org.openremote.controller.event.CustomStateEvent
-import org.openremote.controller.event.EventProcessorChain
import org.openremote.controller.event.SwitchEvent
-import org.openremote.controller.model.CommandDefinition
import org.openremote.controller.rules.RuleEngine
import org.openremote.test.ContainerTrait
import org.openremote.test.util.EventGrabProcessor
@@ -23,7 +18,12 @@ class VacationTest extends Specification implements ContainerTrait {
def "Vacation example"() {
- given: "event processors and rules"
+ given: "a controller deployment"
+ def controllerDeploymentXml = getClass().getResourceAsStream(
+ "/org/openremote/test/rules/vacation/controller.xml"
+ )
+
+ and: "event processors and rules"
def ruleEngineProcessor = new RuleEngine() {
@Override
protected Stream<Resource> getResources(KieServices kieServices) {
@@ -36,79 +36,57 @@ class VacationTest extends Specification implements ContainerTrait {
}
def grabProcessor = new EventGrabProcessor();
- String lastCommandValue = null
- int totalCommandCount = 0
- def commandFactory = new ExecutableCommandFactory() {
- @Override
- protected ExecutableCommand buildCommand(CommandDefinition commandDefinition) {
- return new ExecutableCommand() {
- @Override
- void send(String value) {
- lastCommandValue = value
- totalCommandCount++
- }
- }
- }
- }
- def commandDefinitions = [
- new CommandDefinition(commandFactory, 11, "test", [(CommandDefinition.NAME_PROPERTY): "temp"])
- ]
- def commandFacade = new CommandFacade(commandDefinitions)
- def eventProcessorChain = new EventProcessorChain(
- commandFacade,
+ and: "the started controller server"
+ def testCommandFactory = new TestCommandFactory();
+ def controllerService = new ControllerService(
+ controllerDeploymentXml,
+ testCommandFactory,
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: "the time of day is day"
- def customStateEvent = new CustomStateEvent(222, "time of day", "day");
+ def customStateEvent = new CustomStateEvent(123, "time of day", "day");
controllerService.getCache().update(customStateEvent);
and: "we wait a bit for the rules to fire"
Thread.sleep(100);
- then: "the temperature should be set"
- lastCommandValue == "21"
- totalCommandCount == 1
+ then: "the temperature change should be executed"
+ testCommandFactory.lastExecutionArgument == "21"
when: "the time of day is night"
- customStateEvent = new CustomStateEvent(222, "time of day", "night");
+ customStateEvent = new CustomStateEvent(123, "time of day", "night");
controllerService.getCache().update(customStateEvent);
and: "we wait a bit for the rules to fire"
Thread.sleep(100);
- then: "the temperature should be set"
- lastCommandValue == "18"
- totalCommandCount == 2
+ then: "the temperature change should be executed"
+ testCommandFactory.lastExecutionArgument == "18"
when: "we go on vacation"
- def switchEvent = new SwitchEvent(333, "vacation start", "on", SwitchEvent.State.ON);
+ def switchEvent = new SwitchEvent(789, "vacation start", "on", SwitchEvent.State.ON);
controllerService.getCache().update(switchEvent);
and: "we wait a bit for the rules to fire"
Thread.sleep(100);
- then: "the temperature should be set"
- lastCommandValue == "15"
- totalCommandCount == 3
+ then: "the temperature change should be executed"
+ testCommandFactory.lastExecutionArgument == "15"
when: "the time of day is day"
- customStateEvent = new CustomStateEvent(222, "time of day", "day");
+ customStateEvent = new CustomStateEvent(123, "time of day", "day");
controllerService.getCache().update(customStateEvent);
and: "we wait a bit for the rules to fire"
Thread.sleep(100);
- then: "the temperature should be set"
- lastCommandValue == "15"
- totalCommandCount == 1
+ then: "the temperature change should be executed"
+ testCommandFactory.lastExecutionArgument == "15"
cleanup: "the server should be stopped"
stopContainer(container)
diff --git a/controller/src/test/resources/org/openremote/test/rules/climatecontrol/ClimateControl.drl b/controller/src/test/resources/org/openremote/test/rules/climatecontrol/ClimateControl.drl
index 3cb52c1ad..29c9e008b 100644
--- a/controller/src/test/resources/org/openremote/test/rules/climatecontrol/ClimateControl.drl
+++ b/controller/src/test/resources/org/openremote/test/rules/climatecontrol/ClimateControl.drl
@@ -8,7 +8,7 @@ import org.openremote.controller.model.*;
import org.openremote.controller.event.*;
import org.openremote.controller.event.*;
-global org.openremote.controller.event.CommandFacade execute;
+global org.openremote.controller.event.facade.CommandFacade execute;
global org.openremote.controller.rules.RulePersistence persistence;
global org.openremote.controller.rules.RuleUtil util;
global com.fasterxml.jackson.databind.ObjectMapper JSON;
diff --git a/controller/src/test/resources/org/openremote/test/rules/climatecontrol/controller.xml b/controller/src/test/resources/org/openremote/test/rules/climatecontrol/controller.xml
new file mode 100755
index 000000000..ebf43b4dd
--- /dev/null
+++ b/controller/src/test/resources/org/openremote/test/rules/climatecontrol/controller.xml
@@ -0,0 +1,2028 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<openremote xmlns="http://www.openremote.org"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.openremote.org http://www.openremote.org/schemas/controller.xsd">
+ <components>
+ <switch id="1545">
+ <on />
+ <off />
+ </switch>
+ <switch id="1486">
+ <on />
+ <off />
+ </switch>
+ <switch id="1469">
+ <on />
+ <off />
+ </switch>
+ <switch id="1548">
+ <on />
+ <off />
+ </switch>
+ <switch id="2399">
+ <on />
+ <off />
+ </switch>
+ <switch id="1802">
+ <on />
+ <off />
+ </switch>
+ <switch id="2376">
+ <on />
+ <off />
+ </switch>
+ <switch id="1803">
+ <on />
+ <off />
+ </switch>
+ <switch id="1353">
+ <on />
+ <off />
+ </switch>
+ <switch id="1656">
+ <on />
+ <off />
+ </switch>
+ <switch id="1774">
+ <on />
+ <off />
+ </switch>
+ <switch id="1463">
+ <on />
+ <off />
+ </switch>
+ <switch id="1632">
+ <on />
+ <off />
+ </switch>
+ <switch id="2294">
+ <on />
+ <off />
+ </switch>
+ <switch id="2348">
+ <on />
+ <off />
+ </switch>
+ <switch id="1462">
+ <on />
+ <off />
+ </switch>
+ <switch id="1721">
+ <on />
+ <off />
+ </switch>
+ <switch id="1717">
+ <on />
+ <off />
+ </switch>
+ <switch id="2316">
+ <on />
+ <off />
+ </switch>
+ <switch id="1624">
+ <on />
+ <off />
+ </switch>
+ <switch id="1571">
+ <on />
+ <off />
+ </switch>
+ <switch id="1718">
+ <on />
+ <off />
+ </switch>
+ <switch id="1794">
+ <on />
+ <off />
+ </switch>
+ <switch id="1741">
+ <on />
+ <off />
+ </switch>
+ <switch id="2291">
+ <on />
+ <off />
+ </switch>
+ <switch id="2490">
+ <on>
+ <include type="command" ref="2637" />
+ </on>
+ <off>
+ <include type="command" ref="2639" />
+ </off>
+ <include type="sensor" ref="358549" />
+ </switch>
+ <switch id="1546">
+ <on />
+ <off />
+ </switch>
+ <switch id="1403">
+ <on />
+ <off />
+ </switch>
+ <switch id="2315">
+ <on />
+ <off />
+ </switch>
+ <switch id="1435">
+ <on />
+ <off />
+ </switch>
+ <switch id="2503">
+ <on>
+ <include type="command" ref="2636" />
+ </on>
+ <off>
+ <include type="command" ref="2643" />
+ </off>
+ <include type="sensor" ref="358548" />
+ </switch>
+ <switch id="1454">
+ <on />
+ <off />
+ </switch>
+ <switch id="1352">
+ <on />
+ <off />
+ </switch>
+ <switch id="1633">
+ <on />
+ <off />
+ </switch>
+ <switch id="2288">
+ <on />
+ <off />
+ </switch>
+ <switch id="1639">
+ <on />
+ <off />
+ </switch>
+ <switch id="2375">
+ <on />
+ <off />
+ </switch>
+ <switch id="1354">
+ <on />
+ <off />
+ </switch>
+ <switch id="1775">
+ <on />
+ <off />
+ </switch>
+ <switch id="1402">
+ <on />
+ <off />
+ </switch>
+ <switch id="1551">
+ <on />
+ <off />
+ </switch>
+ <switch id="2290">
+ <on />
+ <off />
+ </switch>
+ <switch id="2382">
+ <on />
+ <off />
+ </switch>
+ <switch id="2314">
+ <on />
+ <off />
+ </switch>
+ <switch id="1572">
+ <on />
+ <off />
+ </switch>
+ <switch id="1547">
+ <on />
+ <off />
+ </switch>
+ <switch id="1358">
+ <on />
+ <off />
+ </switch>
+ <switch id="1716">
+ <on />
+ <off />
+ </switch>
+ <switch id="1573">
+ <on />
+ <off />
+ </switch>
+ <switch id="2289">
+ <on />
+ <off />
+ </switch>
+ <switch id="1715">
+ <on />
+ <off />
+ </switch>
+ <switch id="1355">
+ <on />
+ <off />
+ </switch>
+ <switch id="1401">
+ <on />
+ <off />
+ </switch>
+ <switch id="1743">
+ <on />
+ <off />
+ </switch>
+ <switch id="1605">
+ <on />
+ <off />
+ </switch>
+ <switch id="1434">
+ <on />
+ <off />
+ </switch>
+ <switch id="1809">
+ <on />
+ <off />
+ </switch>
+ <switch id="2347">
+ <on />
+ <off />
+ </switch>
+ <switch id="1604">
+ <on />
+ <off />
+ </switch>
+ <switch id="1826">
+ <on />
+ <off />
+ </switch>
+ <switch id="1742">
+ <on />
+ <off />
+ </switch>
+ <switch id="2367">
+ <on />
+ <off />
+ </switch>
+ <button id="2334" />
+ <button id="2517">
+ <include type="command" ref="2611" />
+ </button>
+ <button id="1766" />
+ <button id="1476" />
+ <button id="1708" />
+ <button id="1391" />
+ <button id="2495">
+ <include type="command" ref="2633" />
+ </button>
+ <button id="1782" />
+ <button id="2013" />
+ <button id="1592" />
+ <button id="1345" />
+ <button id="2498">
+ <include type="command" ref="2629" />
+ </button>
+ <button id="1447" />
+ <button id="1392" />
+ <button id="1471" />
+ <button id="2306" />
+ <button id="1477" />
+ <button id="1810" />
+ <button id="2068" />
+ <button id="1657" />
+ <button id="2000" />
+ <button id="2339" />
+ <button id="2521">
+ <include type="command" ref="2621" />
+ </button>
+ <button id="1646" />
+ <button id="2402" />
+ <button id="2303" />
+ <button id="2337" />
+ <button id="1704" />
+ <button id="2281" />
+ <button id="2338" />
+ <button id="2122" />
+ <button id="1537" />
+ <button id="2518">
+ <include type="command" ref="2614" />
+ </button>
+ <button id="1829" />
+ <button id="1783" />
+ <button id="1445" />
+ <button id="1658" />
+ <button id="2500" />
+ <button id="1785" />
+ <button id="1731" />
+ <button id="1614" />
+ <button id="1784" />
+ <button id="2280" />
+ <button id="2305" />
+ <button id="2360" />
+ <button id="1421" />
+ <button id="1487" />
+ <button id="2358" />
+ <button id="1732" />
+ <button id="1343" />
+ <button id="1538" />
+ <button id="1706" />
+ <button id="1564" />
+ <button id="2357" />
+ <button id="1390" />
+ <button id="1811" />
+ <button id="2054" />
+ <button id="1342" />
+ <button id="2282" />
+ <button id="1612" />
+ <button id="1565" />
+ <button id="1762" />
+ <button id="1393" />
+ <button id="1705" />
+ <button id="1816" />
+ <button id="1613" />
+ <button id="1615" />
+ <button id="1640" />
+ <button id="2409" />
+ <button id="1617" />
+ <button id="2422" />
+ <button id="1563" />
+ <button id="1344" />
+ <button id="1596" />
+ <button id="1641" />
+ <button id="2109" />
+ <button id="1828" />
+ <button id="1536" />
+ <button id="1827" />
+ <button id="2108" />
+ <button id="2384" />
+ <button id="2307" />
+ <button id="1490" />
+ <button id="2121" />
+ <button id="2277" />
+ <button id="1660" />
+ <button id="2515">
+ <include type="command" ref="2616" />
+ </button>
+ <button id="2356" />
+ <button id="1561" />
+ <button id="2336" />
+ <button id="2067" />
+ <button id="2389" />
+ <button id="2519">
+ <include type="command" ref="2617" />
+ </button>
+ <button id="2516">
+ <include type="command" ref="2619" />
+ </button>
+ <button id="2390" />
+ <button id="1786" />
+ <button id="1341" />
+ <button id="1443" />
+ <button id="1423" />
+ <button id="1442" />
+ <button id="1659" />
+ <button id="1787" />
+ <button id="1593" />
+ <button id="1534" />
+ <button id="1817" />
+ <button id="2278" />
+ <button id="1734" />
+ <button id="1707" />
+ <button id="2400" />
+ <button id="1763" />
+ <button id="1426" />
+ <button id="1765" />
+ <button id="1709" />
+ <button id="1444" />
+ <button id="1394" />
+ <button id="1446" />
+ <button id="2304" />
+ <button id="1346" />
+ <button id="2355" />
+ <button id="1764" />
+ <button id="2279" />
+ <button id="2522">
+ <include type="command" ref="2607" />
+ </button>
+ <button id="1470" />
+ <button id="2359" />
+ <button id="1735" />
+ <button id="2308" />
+ <button id="2335" />
+ <button id="1488" />
+ <button id="1647" />
+ <button id="2408" />
+ <button id="1539" />
+ <button id="1733" />
+ <button id="1595" />
+ <button id="1830" />
+ <button id="1560" />
+ <button id="2014" />
+ <button id="2403" />
+ <button id="2525" />
+ <button id="2055" />
+ <button id="2496">
+ <include type="command" ref="2634" />
+ </button>
+ <button id="1395" />
+ <button id="2497">
+ <include type="command" ref="2644" />
+ </button>
+ <button id="1591" />
+ <button id="2520">
+ <include type="command" ref="2627" />
+ </button>
+ <button id="1425" />
+ <button id="1730" />
+ <button id="2383" />
+ <button id="1761" />
+ <button id="2401" />
+ <button id="1535" />
+ <button id="1489" />
+ <button id="2421" />
+ <button id="1422" />
+ <label id="2057" />
+ <label id="2494" />
+ <label id="2441" />
+ <label id="1652" />
+ <label id="1428" />
+ <label id="2489" />
+ <label id="1460" />
+ <label id="1412" />
+ <label id="2285" />
+ <label id="1654" />
+ <label id="2345" />
+ <label id="2509" />
+ <label id="1398" />
+ <label id="2085" />
+ <label id="1714" />
+ <label id="2419" />
+ <label id="2369" />
+ <label id="1485" />
+ <label id="2140" />
+ <label id="2072" />
+ <label id="1740" />
+ <label id="1449" />
+ <label id="1767" />
+ <label id="2366" />
+ <label id="2058" />
+ <label id="2153" />
+ <label id="2056" />
+ <label id="2073" />
+ <label id="2119" />
+ <label id="1739" />
+ <label id="1351" />
+ <label id="2434" />
+ <label id="1459" />
+ <label id="1543" />
+ <label id="2035" />
+ <label id="1584" />
+ <label id="2433" />
+ <label id="2146" />
+ <label id="2293" />
+ <label id="1712" />
+ <label id="2089" />
+ <label id="2295" />
+ <label id="2373" />
+ <label id="2453" />
+ <label id="1578" />
+ <label id="2310" />
+ <label id="1414" />
+ <label id="2079" />
+ <label id="2410" />
+ <label id="1599" />
+ <label id="2116" />
+ <label id="2088" />
+ <label id="1566" />
+ <label id="1479" />
+ <label id="2454" />
+ <label id="1629" />
+ <label id="2100" />
+ <label id="2092" />
+ <label id="2143" />
+ <label id="1574" />
+ <label id="2512" />
+ <label id="2530">
+ <include type="sensor" ref="358541" />
+ </label>
+ <label id="2418" />
+ <label id="1772" />
+ <label id="1585" />
+ <label id="1416" />
+ <label id="1723" />
+ <label id="2342" />
+ <label id="1602" />
+ <label id="2128" />
+ <label id="2008" />
+ <label id="1450" />
+ <label id="2029" />
+ <label id="2429" />
+ <label id="1406" />
+ <label id="2514" />
+ <label id="1722" />
+ <label id="1429" />
+ <label id="1483" />
+ <label id="2511" />
+ <label id="1430" />
+ <label id="1555" />
+ <label id="1790" />
+ <label id="1567" />
+ <label id="2398" />
+ <label id="2533">
+ <include type="sensor" ref="358532" />
+ </label>
+ <label id="2436" />
+ <label id="1350" />
+ <label id="2346" />
+ <label id="2312" />
+ <label id="1579" />
+ <label id="2096" />
+ <label id="2502">
+ <include type="sensor" ref="358542" />
+ </label>
+ <label id="1399" />
+ <label id="2133" />
+ <label id="1569" />
+ <label id="2424" />
+ <label id="2510" />
+ <label id="1808" />
+ <label id="2391" />
+ <label id="2341" />
+ <label id="2060" />
+ <label id="1637" />
+ <label id="1771" />
+ <label id="1824" />
+ <label id="2526">
+ <include type="sensor" ref="358538" />
+ </label>
+ <label id="2313" />
+ <label id="2003" />
+ <label id="2487" />
+ <label id="2097" />
+ <label id="1770" />
+ <label id="1756" />
+ <label id="1407" />
+ <label id="1801" />
+ <label id="2423" />
+ <label id="2009" />
+ <label id="2491" />
+ <label id="2080" />
+ <label id="1461" />
+ <label id="2137" />
+ <label id="2323" />
+ <label id="2044" />
+ <label id="2040" />
+ <label id="2531" />
+ <label id="1468" />
+ <label id="2321" />
+ <label id="2152" />
+ <label id="1554" />
+ <label id="2425" />
+ <label id="2322" />
+ <label id="2328" />
+ <label id="1415" />
+ <label id="2125" />
+ <label id="2318" />
+ <label id="2059" />
+ <label id="2041" />
+ <label id="2078" />
+ <label id="2371" />
+ <label id="1805" />
+ <label id="1746" />
+ <label id="1348" />
+ <label id="2126" />
+ <label id="1755" />
+ <label id="2283" />
+ <label id="2136" />
+ <label id="1719" />
+ <label id="2370" />
+ <label id="2066" />
+ <label id="1478" />
+ <label id="2457" />
+ <label id="1628" />
+ <label id="1467" />
+ <label id="2118" />
+ <label id="1650" />
+ <label id="2445" />
+ <label id="1357" />
+ <label id="2098" />
+ <label id="1432" />
+ <label id="2117" />
+ <label id="2112" />
+ <label id="2132" />
+ <label id="2317" />
+ <label id="2016" />
+ <label id="2023" />
+ <label id="2129" />
+ <label id="1457">
+ <include type="sensor" ref="358500" />
+ </label>
+ <label id="1577" />
+ <label id="2426" />
+ <label id="1630" />
+ <label id="1754" />
+ <label id="2141" />
+ <label id="1362" />
+ <label id="2047" />
+ <label id="2438" />
+ <label id="2414" />
+ <label id="2075" />
+ <label id="2456" />
+ <label id="2142" />
+ <label id="2027" />
+ <label id="2440" />
+ <label id="2015" />
+ <label id="1621" />
+ <label id="1753" />
+ <label id="2395" />
+ <label id="2037" />
+ <label id="2529">
+ <include type="sensor" ref="358529" />
+ </label>
+ <label id="1360" />
+ <label id="1653" />
+ <label id="2365" />
+ <label id="2061" />
+ <label id="1791" />
+ <label id="2048" />
+ <label id="2114" />
+ <label id="2534" />
+ <label id="2149" />
+ <label id="2101" />
+ <label id="1580" />
+ <label id="2439" />
+ <label id="1408" />
+ <label id="2145" />
+ <label id="1453" />
+ <label id="2138" />
+ <label id="1598" />
+ <label id="2161" />
+ <label id="1797" />
+ <label id="2444" />
+ <label id="1433" />
+ <label id="1751" />
+ <label id="2394" />
+ <label id="1396" />
+ <label id="2127" />
+ <label id="2430" />
+ <label id="1349" />
+ <label id="1436" />
+ <label id="1738" />
+ <label id="2036" />
+ <label id="1597" />
+ <label id="2099" />
+ <label id="2325" />
+ <label id="1792" />
+ <label id="2455" />
+ <label id="2042" />
+ <label id="2065" />
+ <label id="2363" />
+ <label id="2415" />
+ <label id="2039" />
+ <label id="2488" />
+ <label id="2428" />
+ <label id="2124" />
+ <label id="1724" />
+ <label id="2094" />
+ <label id="1745" />
+ <label id="1458" />
+ <label id="1586" />
+ <label id="2091" />
+ <label id="1821" />
+ <label id="1800" />
+ <label id="1544" />
+ <label id="1737" />
+ <label id="2397" />
+ <label id="2287" />
+ <label id="1720" />
+ <label id="1710" />
+ <label id="1825" />
+ <label id="2396" />
+ <label id="1568" />
+ <label id="2022" />
+ <label id="2006" />
+ <label id="2095" />
+ <label id="1413" />
+ <label id="2032" />
+ <label id="2340" />
+ <label id="2309" />
+ <label id="1464" />
+ <label id="2034" />
+ <label id="1819" />
+ <label id="1540" />
+ <label id="1437">
+ <include type="sensor" ref="358496" />
+ </label>
+ <label id="1552" />
+ <label id="1410" />
+ <label id="2028" />
+ <label id="2329" />
+ <label id="1581" />
+ <label id="1553" />
+ <label id="2372" />
+ <label id="2030" />
+ <label id="2007" />
+ <label id="2493" />
+ <label id="2070" />
+ <label id="1796" />
+ <label id="2435" />
+ <label id="2420" />
+ <label id="2033" />
+ <label id="1626" />
+ <label id="1736" />
+ <label id="2103" />
+ <label id="2102" />
+ <label id="1725" />
+ <label id="2378" />
+ <label id="2113" />
+ <label id="2045" />
+ <label id="2437" />
+ <label id="2298" />
+ <label id="2296" />
+ <label id="2082" />
+ <label id="2344" />
+ <label id="1400" />
+ <label id="2086" />
+ <label id="2350" />
+ <label id="1631" />
+ <label id="2018" />
+ <label id="1622" />
+ <label id="1623" />
+ <label id="2416" />
+ <label id="2019" />
+ <label id="1748" />
+ <label id="2062" />
+ <label id="1606" />
+ <label id="1431" />
+ <label id="1769" />
+ <label id="1749" />
+ <label id="2450" />
+ <label id="1636" />
+ <label id="1776" />
+ <label id="2324" />
+ <label id="2135" />
+ <label id="2524" />
+ <label id="1397" />
+ <label id="1620" />
+ <label id="2049" />
+ <label id="1655" />
+ <label id="1482" />
+ <label id="2020" />
+ <label id="1806" />
+ <label id="2131" />
+ <label id="1452" />
+ <label id="2046" />
+ <label id="2123" />
+ <label id="1356" />
+ <label id="2156" />
+ <label id="2417" />
+ <label id="2024" />
+ <label id="1638" />
+ <label id="1550" />
+ <label id="2069" />
+ <label id="2452" />
+ <label id="2492" />
+ <label id="1619" />
+ <label id="1576" />
+ <label id="1405" />
+ <label id="1427" />
+ <label id="2413" />
+ <label id="2111" />
+ <label id="2392" />
+ <label id="2412" />
+ <label id="2379" />
+ <label id="2081" />
+ <label id="2501">
+ <include type="sensor" ref="358545" />
+ </label>
+ <label id="2380" />
+ <label id="2148" />
+ <label id="1361" />
+ <label id="2026" />
+ <label id="2364" />
+ <label id="1807" />
+ <label id="2005" />
+ <label id="2084" />
+ <label id="2031" />
+ <label id="2527">
+ <include type="sensor" ref="358534" />
+ </label>
+ <label id="1480" />
+ <label id="1600" />
+ <label id="2074" />
+ <label id="1634" />
+ <label id="2284" />
+ <label id="2349" />
+ <label id="2377" />
+ <label id="1793" />
+ <label id="1635" />
+ <label id="2523" />
+ <label id="1627" />
+ <label id="2528">
+ <include type="sensor" ref="358531" />
+ </label>
+ <label id="1409" />
+ <label id="1484" />
+ <label id="2431" />
+ <label id="2090" />
+ <label id="1823" />
+ <label id="2381" />
+ <label id="1788" />
+ <label id="2374" />
+ <label id="2139" />
+ <label id="1798" />
+ <label id="2343" />
+ <label id="1481" />
+ <label id="2021" />
+ <label id="2446" />
+ <label id="1795" />
+ <label id="2134" />
+ <label id="1575" />
+ <label id="1820" />
+ <label id="2362" />
+ <label id="2011" />
+ <label id="1648" />
+ <label id="1789" />
+ <label id="2292" />
+ <label id="1818" />
+ <label id="1804" />
+ <label id="1465" />
+ <label id="2411" />
+ <label id="2025" />
+ <label id="1822" />
+ <label id="2012" />
+ <label id="1747" />
+ <label id="2002" />
+ <label id="2499" />
+ <label id="1744" />
+ <label id="2155" />
+ <label id="2010" />
+ <label id="1618" />
+ <label id="2286" />
+ <label id="2368" />
+ <label id="1541" />
+ <label id="2038" />
+ <label id="1455" />
+ <label id="2115" />
+ <label id="2147" />
+ <label id="2064" />
+ <label id="1542" />
+ <label id="2320" />
+ <label id="2087" />
+ <label id="2326" />
+ <label id="2443" />
+ <label id="2448" />
+ <label id="2513" />
+ <label id="1713" />
+ <label id="1411" />
+ <label id="2393" />
+ <label id="1404" />
+ <label id="1768" />
+ <label id="1651" />
+ <label id="2327" />
+ <label id="2120" />
+ <label id="2071" />
+ <label id="1649" />
+ <label id="1456" />
+ <label id="1773" />
+ <label id="1752" />
+ <label id="2427" />
+ <label id="2043" />
+ <label id="1582" />
+ <label id="1750" />
+ <label id="2150" />
+ <label id="1625" />
+ <label id="2319" />
+ <label id="1601" />
+ <label id="2442" />
+ <label id="1448" />
+ <label id="2151" />
+ <label id="2451" />
+ <label id="2361" />
+ <label id="1607" />
+ <label id="2157" />
+ <label id="1451" />
+ <label id="2004" />
+ <label id="2311" />
+ <label id="1603" />
+ <label id="2532" />
+ <label id="2083" />
+ <label id="2093" />
+ <label id="2504" />
+ <label id="2432" />
+ <label id="1549" />
+ <label id="2449" />
+ <label id="1711" />
+ <label id="2130" />
+ <label id="2110" />
+ <label id="1466" />
+ <label id="1777" />
+ <label id="2447" />
+ <label id="2297" />
+ <label id="2063" />
+ <label id="2077" />
+ <label id="1359" />
+ <label id="2017" />
+ <label id="1347" />
+ <label id="1570" />
+ <label id="1799" />
+ <label id="2154" />
+ <label id="1583" />
+ <label id="2144" />
+ </components>
+ <sensors>
+ <sensor id="358442" name="VETD.Sun" type="custom">
+ <include type="command" ref="2549" />
+ </sensor>
+ <sensor id="358443" name="VETA.Fri" type="custom">
+ <include type="command" ref="2565" />
+ </sensor>
+ <sensor id="358444" name="VETA.dec" type="custom">
+ <include type="command" ref="2544" />
+ </sensor>
+ <sensor id="358445" name="VACATION.inc" type="custom">
+ <include type="command" ref="2552" />
+ </sensor>
+ <sensor id="358446" name="VETD.Mon" type="custom">
+ <include type="command" ref="2576" />
+ </sensor>
+ <sensor id="358447" name="VETA.Thu" type="custom">
+ <include type="command" ref="2542" />
+ </sensor>
+ <sensor id="358448" name="VETA.Mon" type="custom">
+ <include type="command" ref="2545" />
+ </sensor>
+ <sensor id="358449" name="VETD.Wed" type="custom">
+ <include type="command" ref="2559" />
+ </sensor>
+ <sensor id="358450" name="VETD.inc" type="custom">
+ <include type="command" ref="2558" />
+ </sensor>
+ <sensor id="358451" name="VETD" type="custom">
+ <include type="command" ref="2574" />
+ </sensor>
+ <sensor id="358452" name="VACATION" type="custom">
+ <include type="command" ref="2575" />
+ </sensor>
+ <sensor id="358453" name="TimerMMM" type="custom">
+ <include type="command" ref="2569" />
+ </sensor>
+ <sensor id="358454" name="VPRESENCE" type="custom">
+ <include type="command" ref="2541" />
+ <state name="Yes" value="Yes" />
+ <state name="No" value="No" />
+ </sensor>
+ <sensor id="358455" name="VPERSONSENSETIME" type="custom">
+ <include type="command" ref="2577" />
+ </sensor>
+ <sensor id="358456" name="VR1.ET.dec" type="custom">
+ <include type="command" ref="2547" />
+ </sensor>
+ <sensor id="358457" name="TimerEEEE" type="custom">
+ <include type="command" ref="2553" />
+ </sensor>
+ <sensor id="358458" name="VPERSONSENSE" type="custom">
+ <include type="command" ref="2556" />
+ </sensor>
+ <sensor id="358459" name="VETA.Sat" type="custom">
+ <include type="command" ref="2548" />
+ </sensor>
+ <sensor id="358460" name="VR1.ET" type="custom">
+ <include type="command" ref="2562" />
+ </sensor>
+ <sensor id="358461" name="VETD.dec" type="custom">
+ <include type="command" ref="2557" />
+ </sensor>
+ <sensor id="358462" name="VETA.inc" type="custom">
+ <include type="command" ref="2564" />
+ </sensor>
+ <sensor id="358463" name="VETA.Sun" type="custom">
+ <include type="command" ref="2572" />
+ </sensor>
+ <sensor id="358464" name="VATA" type="custom">
+ <include type="command" ref="2573" />
+ </sensor>
+ <sensor id="358465" name="VNEXTACTION" type="custom">
+ <include type="command" ref="2539" />
+ </sensor>
+ <sensor id="358466" name="VETA" type="custom">
+ <include type="command" ref="2568" />
+ </sensor>
+ <sensor id="358467" name="VArrivalBackground" type="custom">
+ <include type="command" ref="2561" />
+ <state name="off" value="off" />
+ <state name="on" value="on" />
+ </sensor>
+ <sensor id="358468" name="VTimer" type="custom">
+ <include type="command" ref="2543" />
+ </sensor>
+ <sensor id="358469" name="TimerHH" type="custom">
+ <include type="command" ref="2567" />
+ </sensor>
+ <sensor id="358470" name="VDepartureBackground" type="custom">
+ <include type="command" ref="2571" />
+ <state name="off" value="off" />
+ <state name="on" value="on" />
+ </sensor>
+ <sensor id="358471" name="VETD.Sat" type="custom">
+ <include type="command" ref="2554" />
+ </sensor>
+ <sensor id="358472" name="VETD.Thu" type="custom">
+ <include type="command" ref="2550" />
+ </sensor>
+ <sensor id="358473" name="Timerd" type="custom">
+ <include type="command" ref="2540" />
+ </sensor>
+ <sensor id="358474" name="VACATION.dec" type="custom">
+ <include type="command" ref="2555" />
+ </sensor>
+ <sensor id="358475" name="VETD.Tue" type="custom">
+ <include type="command" ref="2551" />
+ </sensor>
+ <sensor id="358476" name="VR1.ET.inc" type="custom">
+ <include type="command" ref="2566" />
+ </sensor>
+ <sensor id="358477" name="VETA.Wed" type="custom">
+ <include type="command" ref="2560" />
+ </sensor>
+ <sensor id="358478" name="TimerEEE" type="custom">
+ <include type="command" ref="2570" />
+ </sensor>
+ <sensor id="358479" name="VETD.Fri" type="custom">
+ <include type="command" ref="2546" />
+ </sensor>
+ <sensor id="358480" name="VATD" type="custom">
+ <include type="command" ref="2538" />
+ </sensor>
+ <sensor id="358481" name="VETA.Tue" type="custom">
+ <include type="command" ref="2537" />
+ </sensor>
+ <sensor id="358482" name="VTOTALSCOREr" type="range">
+ <include type="command" ref="2584" />
+ <min value="0" />
+ <max value="1000" />
+ </sensor>
+ <sensor id="358483" name="VTOTALSCORE" type="custom">
+ <include type="command" ref="2584" />
+ </sensor>
+ <sensor id="358484" name="VLEVEL" type="custom">
+ <include type="command" ref="2581" />
+ </sensor>
+ <sensor id="358485" name="VLEAF1" type="custom">
+ <include type="command" ref="2583" />
+ <state name="l1.png" value="l1.png" />
+ <state name="l2.png" value="l2.png" />
+ <state name="l0.png" value="l0.png" />
+ </sensor>
+ <sensor id="358486" name="VTOTALSCOREdisp" type="custom">
+ <include type="command" ref="2580" />
+ </sensor>
+ <sensor id="358487" name="VSCORE" type="custom">
+ <include type="command" ref="2586" />
+ </sensor>
+ <sensor id="358488" name="VLEAVES" type="custom">
+ <include type="command" ref="2582" />
+ </sensor>
+ <sensor id="358489" name="VLEAF3" type="custom">
+ <include type="command" ref="2579" />
+ <state name="l1.png" value="l1.png" />
+ <state name="l2.png" value="l2.png" />
+ <state name="l0.png" value="l0.png" />
+ </sensor>
+ <sensor id="358490" name="VLEAF2" type="custom">
+ <include type="command" ref="2585" />
+ <state name="l1.png" value="l1.png" />
+ <state name="l2.png" value="l2.png" />
+ <state name="l0.png" value="l0.png" />
+ </sensor>
+ <sensor id="358491" name="VSUMMER" type="custom">
+ <include type="command" ref="2599" />
+ <state name="Yes" value="Yes" />
+ <state name="No" value="No" />
+ </sensor>
+ <sensor id="358492" name="VADVICEDONE" type="custom">
+ <include type="command" ref="2598" />
+ </sensor>
+ <sensor id="358493" name="VR1.COMFORT.inc" type="custom">
+ <include type="command" ref="2592" />
+ </sensor>
+ <sensor id="358494" name="VR1.COMFORT" type="custom">
+ <include type="command" ref="2590" />
+ </sensor>
+ <sensor id="358495" name="VOUTSIDE" type="custom">
+ <include type="command" ref="2597" />
+ </sensor>
+ <sensor id="358496" name="VWINDOW" type="custom">
+ <include type="command" ref="2595" />
+ <state name="Open" value="Open" />
+ <state name="Closed" value="Closed" />
+ </sensor>
+ <sensor id="358497" name="VHEATINGSETPOINT" type="custom">
+ <include type="command" ref="2587" />
+ </sensor>
+ <sensor id="358498" name="VR1.TEMPERATURE.inc" type="custom">
+ <include type="command" ref="2591" />
+ </sensor>
+ <sensor id="358499" name="VR1.COMFORT.dec" type="custom">
+ <include type="command" ref="2593" />
+ </sensor>
+ <sensor id="358500" name="VROOMTEMPERATURE" type="custom">
+ <include type="command" ref="2594" />
+ </sensor>
+ <sensor id="358501" name="VHEATING" type="custom">
+ <include type="command" ref="2588" />
+ </sensor>
+ <sensor id="358502" name="VR1.TEMPERATURE.dec" type="custom">
+ <include type="command" ref="2596" />
+ </sensor>
+ <sensor id="358503" name="VR1.TEMPERATURE" type="custom">
+ <include type="command" ref="2589" />
+ </sensor>
+ <sensor id="358504" name="VADVICE" type="custom">
+ <include type="command" ref="2600" />
+ </sensor>
+ <sensor id="358505" name="GVconfig" type="custom">
+ <include type="command" ref="2601" />
+ </sensor>
+ <sensor id="358525" name="PID.sp.dec" type="custom">
+ <include type="command" ref="2625" />
+ </sensor>
+ <sensor id="358526" name="PID.kd.inc" type="custom">
+ <include type="command" ref="2606" />
+ </sensor>
+ <sensor id="358527" name="PID.db.inc" type="custom">
+ <include type="command" ref="2622" />
+ </sensor>
+ <sensor id="358528" name="PID.kp.dec" type="custom">
+ <include type="command" ref="2608" />
+ </sensor>
+ <sensor id="358529" name="PID.Se" type="custom">
+ <include type="command" ref="2609" />
+ </sensor>
+ <sensor id="358530" name="PID.ki.dec" type="custom">
+ <include type="command" ref="2620" />
+ </sensor>
+ <sensor id="358531" name="GV.PID.Sp" type="custom">
+ <include type="command" ref="2610" />
+ </sensor>
+ <sensor id="358532" name="PID.Output" type="custom">
+ <include type="command" ref="2615" />
+ </sensor>
+ <sensor id="358533" name="PID.db.dec" type="custom">
+ <include type="command" ref="2613" />
+ </sensor>
+ <sensor id="358534" name="GV.PID.Ki" type="custom">
+ <include type="command" ref="2604" />
+ </sensor>
+ <sensor id="358535" name="PID.kd.dec" type="custom">
+ <include type="command" ref="2612" />
+ </sensor>
+ <sensor id="358536" name="GV.PID.Db" type="custom">
+ <include type="command" ref="2624" />
+ </sensor>
+ <sensor id="358537" name="PID.sp.inc" type="custom">
+ <include type="command" ref="2626" />
+ </sensor>
+ <sensor id="358538" name="GV.PID.Kp" type="custom">
+ <include type="command" ref="2603" />
+ </sensor>
+ <sensor id="358539" name="PID.kp.inc" type="custom">
+ <include type="command" ref="2628" />
+ </sensor>
+ <sensor id="358540" name="PID.ki.inc" type="custom">
+ <include type="command" ref="2623" />
+ </sensor>
+ <sensor id="358541" name="GV.PID.Kd" type="custom">
+ <include type="command" ref="2602" />
+ </sensor>
+ <sensor id="358542" name="FS.Toutside" type="custom">
+ <include type="command" ref="2638" />
+ </sensor>
+ <sensor id="358543" name="FS.Toutside.inc" type="custom">
+ <include type="command" ref="2635" />
+ </sensor>
+ <sensor id="358544" name="FS.Tinside.dec" type="custom">
+ <include type="command" ref="2641" />
+ </sensor>
+ <sensor id="358545" name="FS.Tinside" type="custom">
+ <include type="command" ref="2632" />
+ </sensor>
+ <sensor id="358546" name="FS.Toutside.dec" type="custom">
+ <include type="command" ref="2640" />
+ </sensor>
+ <sensor id="358547" name="FS.Tinside.inc" type="custom">
+ <include type="command" ref="2642" />
+ </sensor>
+ <sensor id="358548" name="FS.PIR" type="switch">
+ <include type="command" ref="2631" />
+ <state name="on" />
+ <state name="off" />
+ </sensor>
+ <sensor id="358549" name="FS.Window" type="switch">
+ <include type="command" ref="2630" />
+ <state name="on" />
+ <state name="off" />
+ </sensor>
+ </sensors>
+ <commands>
+ <command id="2537" protocol="virtual">
+ <property name="address" value="vetatuesday" />
+ <property name="command" value="status" />
+ <property name="name" value="VETA.Tue" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2538" protocol="virtual">
+ <property name="address" value="VATD" />
+ <property name="command" value="status" />
+ <property name="name" value="VATD" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2539" protocol="virtual">
+ <property name="address" value="VNEXTACTION" />
+ <property name="command" value="status" />
+ <property name="name" value="VNEXTACTION" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2541" protocol="virtual">
+ <property name="address" value="VPRESENCE" />
+ <property name="command" value="status" />
+ <property name="name" value="VPRESENCE" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2542" protocol="virtual">
+ <property name="address" value="vetathursday" />
+ <property name="command" value="status" />
+ <property name="name" value="VETA.Thu" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2543" protocol="virtual">
+ <property name="address" value="VTimer" />
+ <property name="command" value="status" />
+ <property name="name" value="VTimer" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2544" protocol="virtual">
+ <property name="address" value="vetaalldec" />
+ <property name="command" value="ON" />
+ <property name="name" value="VETA.dec" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2545" protocol="virtual">
+ <property name="address" value="vetamonday" />
+ <property name="command" value="status" />
+ <property name="name" value="VETA.Mon" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2546" protocol="virtual">
+ <property name="address" value="vetdfriday" />
+ <property name="command" value="status" />
+ <property name="name" value="VETD.Fri" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2547" protocol="virtual">
+ <property name="address" value="vretdec" />
+ <property name="command" value="ON" />
+ <property name="name" value="VR1.ET.dec" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2548" protocol="virtual">
+ <property name="address" value="vetasat" />
+ <property name="command" value="status" />
+ <property name="name" value="VETA.Sat" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2549" protocol="virtual">
+ <property name="address" value="vetdsun" />
+ <property name="command" value="status" />
+ <property name="name" value="VETD.Sun" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2550" protocol="virtual">
+ <property name="address" value="vetdthursday" />
+ <property name="command" value="status" />
+ <property name="name" value="VETD.Thu" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2551" protocol="virtual">
+ <property name="address" value="vetdtuesday" />
+ <property name="command" value="status" />
+ <property name="name" value="VETD.Tue" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2552" protocol="virtual">
+ <property name="address" value="VABSENTinc" />
+ <property name="command" value="ON" />
+ <property name="name" value="VACATION.inc" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2554" protocol="virtual">
+ <property name="address" value="vetdsat" />
+ <property name="command" value="status" />
+ <property name="name" value="VETD.Sat" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2555" protocol="virtual">
+ <property name="address" value="VABSENTdec" />
+ <property name="command" value="ON" />
+ <property name="name" value="VACATION.dec" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2556" protocol="virtual">
+ <property name="address" value="VPERSONSENSE" />
+ <property name="command" value="status" />
+ <property name="name" value="VPERSONSENSE" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2557" protocol="virtual">
+ <property name="address" value="vetdalldec" />
+ <property name="command" value="ON" />
+ <property name="name" value="VETD.dec" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2558" protocol="virtual">
+ <property name="address" value="vetdallinc" />
+ <property name="command" value="ON" />
+ <property name="name" value="VETD.inc" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2559" protocol="virtual">
+ <property name="address" value="vetdwendsday" />
+ <property name="command" value="status" />
+ <property name="name" value="VETD.Wed" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2560" protocol="virtual">
+ <property name="address" value="vetawendsday" />
+ <property name="command" value="status" />
+ <property name="name" value="VETA.Wed" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2561" protocol="virtual">
+ <property name="address" value="VArrivalBackground" />
+ <property name="command" value="status" />
+ <property name="name" value="VArrivalBackground" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2562" protocol="virtual">
+ <property name="address" value="vret" />
+ <property name="command" value="status" />
+ <property name="name" value="VR1.ET" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2564" protocol="virtual">
+ <property name="address" value="vetaallinc" />
+ <property name="command" value="ON" />
+ <property name="name" value="VETA.inc" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2565" protocol="virtual">
+ <property name="address" value="vetafriday" />
+ <property name="command" value="status" />
+ <property name="name" value="VETA.Fri" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2566" protocol="virtual">
+ <property name="address" value="vretinc" />
+ <property name="command" value="ON" />
+ <property name="name" value="VR1.ET.inc" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2568" protocol="virtual">
+ <property name="address" value="vetaall" />
+ <property name="command" value="status" />
+ <property name="name" value="VETA" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2571" protocol="virtual">
+ <property name="address" value="VDepartureBackground" />
+ <property name="command" value="status" />
+ <property name="name" value="VDepartureBackground" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2572" protocol="virtual">
+ <property name="address" value="vetasun" />
+ <property name="command" value="status" />
+ <property name="name" value="VETA.Sun" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2573" protocol="virtual">
+ <property name="address" value="VATA" />
+ <property name="command" value="status" />
+ <property name="name" value="VATA" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2574" protocol="virtual">
+ <property name="address" value="vetdall" />
+ <property name="command" value="status" />
+ <property name="name" value="VETD" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2575" protocol="virtual">
+ <property name="address" value="VABSENT" />
+ <property name="command" value="status" />
+ <property name="name" value="VACATION" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2576" protocol="virtual">
+ <property name="address" value="vetdmonday" />
+ <property name="command" value="status" />
+ <property name="name" value="VETD.Mon" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2577" protocol="virtual">
+ <property name="address" value="VPERSONSENSETIME" />
+ <property name="command" value="status" />
+ <property name="name" value="VPERSONSENSETIME" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2578" protocol="virtual">
+ <property name="address" value="VTOTALSCOREinc" />
+ <property name="command" value="status" />
+ <property name="name" value="VTOTALSCORE.inc" />
+ <property name="urn:openremote:device-command:device-name" value="Efficiency" />
+ <property name="urn:openremote:device-command:device-id" value="35479" />
+ </command>
+ <command id="2579" protocol="virtual">
+ <property name="address" value="vleafthree" />
+ <property name="command" value="status" />
+ <property name="name" value="VLEAF3" />
+ <property name="urn:openremote:device-command:device-name" value="Efficiency" />
+ <property name="urn:openremote:device-command:device-id" value="35479" />
+ </command>
+ <command id="2580" protocol="virtual">
+ <property name="address" value="VTOTALSCOREdisp" />
+ <property name="command" value="status" />
+ <property name="name" value="VTOTALSCOREdisp" />
+ <property name="urn:openremote:device-command:device-name" value="Efficiency" />
+ <property name="urn:openremote:device-command:device-id" value="35479" />
+ </command>
+ <command id="2581" protocol="virtual">
+ <property name="address" value="VLEVEL" />
+ <property name="command" value="status" />
+ <property name="name" value="VLEVEL" />
+ <property name="urn:openremote:device-command:device-name" value="Efficiency" />
+ <property name="urn:openremote:device-command:device-id" value="35479" />
+ </command>
+ <command id="2582" protocol="virtual">
+ <property name="address" value="VLEAVES" />
+ <property name="command" value="status" />
+ <property name="name" value="VLEAVES" />
+ <property name="urn:openremote:device-command:device-name" value="Efficiency" />
+ <property name="urn:openremote:device-command:device-id" value="35479" />
+ </command>
+ <command id="2583" protocol="virtual">
+ <property name="address" value="vleafone" />
+ <property name="command" value="status" />
+ <property name="name" value="VLEAF1" />
+ <property name="urn:openremote:device-command:device-name" value="Efficiency" />
+ <property name="urn:openremote:device-command:device-id" value="35479" />
+ </command>
+ <command id="2584" protocol="virtual">
+ <property name="address" value="VTOTALSCORE" />
+ <property name="command" value="status" />
+ <property name="name" value="VTOTALSCORE" />
+ <property name="urn:openremote:device-command:device-name" value="Efficiency" />
+ <property name="urn:openremote:device-command:device-id" value="35479" />
+ </command>
+ <command id="2585" protocol="virtual">
+ <property name="address" value="vleaftwo" />
+ <property name="command" value="status" />
+ <property name="name" value="VLEAF2" />
+ <property name="urn:openremote:device-command:device-name" value="Efficiency" />
+ <property name="urn:openremote:device-command:device-id" value="35479" />
+ </command>
+ <command id="2586" protocol="virtual">
+ <property name="address" value="VSCORE" />
+ <property name="command" value="status" />
+ <property name="name" value="VSCORE" />
+ <property name="urn:openremote:device-command:device-name" value="Efficiency" />
+ <property name="urn:openremote:device-command:device-id" value="35479" />
+ </command>
+ <command id="2587" protocol="virtual">
+ <property name="address" value="VHEATINGSETPOINT" />
+ <property name="command" value="status" />
+ <property name="name" value="VHEATINGSETPOINT" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2588" protocol="virtual">
+ <property name="address" value="VHEATING" />
+ <property name="command" value="status" />
+ <property name="name" value="VHEATING" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2589" protocol="virtual">
+ <property name="address" value="vrtemperature" />
+ <property name="command" value="status" />
+ <property name="name" value="VR1.TEMPERATURE" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2590" protocol="virtual">
+ <property name="address" value="vrcomfort" />
+ <property name="command" value="status" />
+ <property name="name" value="VR1.COMFORT" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2591" protocol="virtual">
+ <property name="address" value="vrtemperatureinc" />
+ <property name="command" value="ON" />
+ <property name="name" value="VR1.TEMPERATURE.inc" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2592" protocol="virtual">
+ <property name="address" value="vrcomfortinc" />
+ <property name="command" value="ON" />
+ <property name="name" value="VR1.COMFORT.inc" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2593" protocol="virtual">
+ <property name="address" value="vrcomfortdec" />
+ <property name="command" value="ON" />
+ <property name="name" value="VR1.COMFORT.dec" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2594" protocol="virtual">
+ <property name="address" value="VROOMTEMPERATURE" />
+ <property name="command" value="status" />
+ <property name="name" value="VROOMTEMPERATURE" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2595" protocol="virtual">
+ <property name="address" value="VWINDOW" />
+ <property name="command" value="status" />
+ <property name="name" value="VWINDOW" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2596" protocol="virtual">
+ <property name="address" value="vrtemperaturedec" />
+ <property name="command" value="ON" />
+ <property name="name" value="VR1.TEMPERATURE.dec" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2597" protocol="virtual">
+ <property name="address" value="VOUTSIDE" />
+ <property name="command" value="status" />
+ <property name="name" value="VOUTSIDE" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2598" protocol="virtual">
+ <property name="address" value="VADVICEDONE" />
+ <property name="command" value="ON" />
+ <property name="name" value="VADVICEDONE" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2599" protocol="virtual">
+ <property name="address" value="VSUMMER" />
+ <property name="command" value="status" />
+ <property name="name" value="VSUMMER" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2600" protocol="virtual">
+ <property name="address" value="VADVICE" />
+ <property name="command" value="status" />
+ <property name="name" value="VADVICE" />
+ <property name="urn:openremote:device-command:device-name" value="Heating" />
+ <property name="urn:openremote:device-command:device-id" value="35480" />
+ </command>
+ <command id="2601" protocol="virtual">
+ <property name="address" value="GVconfig" />
+ <property name="command" value="status" />
+ <property name="name" value="GVconfig" />
+ <property name="urn:openremote:device-command:device-name" value="Config" />
+ <property name="urn:openremote:device-command:device-id" value="35481" />
+ </command>
+ <command id="2602" protocol="virtual">
+ <property name="address" value="pidkd" />
+ <property name="command" value="status" />
+ <property name="name" value="GV.PID.Kd" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2603" protocol="virtual">
+ <property name="address" value="pidkp" />
+ <property name="command" value="status" />
+ <property name="name" value="GV.PID.Kp" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2604" protocol="virtual">
+ <property name="address" value="pidki" />
+ <property name="command" value="status" />
+ <property name="name" value="GV.PID.Ki" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2605" protocol="virtual">
+ <property name="address" value="piddbinc" />
+ <property name="command" value="ON" />
+ <property name="name" value="PID.db.inc.ON" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2606" protocol="virtual">
+ <property name="address" value="pidkdinc" />
+ <property name="command" value="status" />
+ <property name="name" value="PID.kd.inc" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2607" protocol="virtual">
+ <property name="address" value="pidkiinc" />
+ <property name="command" value="ON" />
+ <property name="name" value="PID.ki.inc.ON" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2608" protocol="virtual">
+ <property name="address" value="kpdec" />
+ <property name="command" value="status" />
+ <property name="name" value="PID.kp.dec" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2609" protocol="virtual">
+ <property name="address" value="pidse" />
+ <property name="command" value="status" />
+ <property name="name" value="PID.Se" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2610" protocol="virtual">
+ <property name="address" value="pidsp" />
+ <property name="command" value="status" />
+ <property name="name" value="GV.PID.Sp" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2611" protocol="virtual">
+ <property name="address" value="pidkidec" />
+ <property name="command" value="ON" />
+ <property name="name" value="PID.ki.dec.ON" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2612" protocol="virtual">
+ <property name="address" value="pidkddec" />
+ <property name="command" value="status" />
+ <property name="name" value="PID.kd.dec" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2613" protocol="virtual">
+ <property name="address" value="piddbdec" />
+ <property name="command" value="status" />
+ <property name="name" value="PID.db.dec" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2614" protocol="virtual">
+ <property name="address" value="pidkddec" />
+ <property name="command" value="ON" />
+ <property name="name" value="PID.kd.dec.ON" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2615" protocol="virtual">
+ <property name="address" value="pidoutput" />
+ <property name="command" value="status" />
+ <property name="name" value="PID.Output" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2616" protocol="virtual">
+ <property name="address" value="pidkdinc" />
+ <property name="command" value="ON" />
+ <property name="name" value="PID.kd.inc.ON" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2617" protocol="virtual">
+ <property name="address" value="pidspdec" />
+ <property name="command" value="ON" />
+ <property name="name" value="PID.sp.dec.ON" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2618" protocol="virtual">
+ <property name="address" value="piddbdec" />
+ <property name="command" value="ON" />
+ <property name="name" value="PID.db.dec.ON" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2619" protocol="virtual">
+ <property name="address" value="pidspinc" />
+ <property name="command" value="ON" />
+ <property name="name" value="PID.sp.inc.ON" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2620" protocol="virtual">
+ <property name="address" value="pidkidec" />
+ <property name="command" value="status" />
+ <property name="name" value="PID.ki.dec" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2621" protocol="virtual">
+ <property name="address" value="kpinc" />
+ <property name="command" value="ON" />
+ <property name="name" value="PID.kp.inc.ON" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2622" protocol="virtual">
+ <property name="address" value="piddbinc" />
+ <property name="command" value="status" />
+ <property name="name" value="PID.db.inc" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2623" protocol="virtual">
+ <property name="address" value="pidkiinc" />
+ <property name="command" value="status" />
+ <property name="name" value="PID.ki.inc" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2624" protocol="virtual">
+ <property name="address" value="piddb" />
+ <property name="command" value="status" />
+ <property name="name" value="GV.PID.Db" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2625" protocol="virtual">
+ <property name="address" value="pidspdec" />
+ <property name="command" value="status" />
+ <property name="name" value="PID.sp.dec" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2626" protocol="virtual">
+ <property name="address" value="pidspinc" />
+ <property name="command" value="status" />
+ <property name="name" value="PID.sp.inc" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2627" protocol="virtual">
+ <property name="address" value="kpdec" />
+ <property name="command" value="ON" />
+ <property name="name" value="PID.kp.dec.ON" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2628" protocol="virtual">
+ <property name="address" value="kpinc" />
+ <property name="command" value="status" />
+ <property name="name" value="PID.kp.inc" />
+ <property name="urn:openremote:device-command:device-name" value="PID" />
+ <property name="urn:openremote:device-command:device-id" value="35487" />
+ </command>
+ <command id="2629" protocol="virtual">
+ <property name="address" value="fsoutsideinc" />
+ <property name="command" value="on" />
+ <property name="name" value="FS.Toutside.inc.ON" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2630" protocol="virtual">
+ <property name="address" value="fswindow" />
+ <property name="command" value="status" />
+ <property name="name" value="FS.Window" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2631" protocol="virtual">
+ <property name="address" value="fspir" />
+ <property name="command" value="status" />
+ <property name="name" value="FS.PIR" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2632" protocol="virtual">
+ <property name="address" value="fstinside" />
+ <property name="command" value="status" />
+ <property name="name" value="FS.Tinside" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2633" protocol="virtual">
+ <property name="address" value="fsoutsidedec" />
+ <property name="command" value="on" />
+ <property name="name" value="FS.Toutside.dec.ON" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2634" protocol="virtual">
+ <property name="address" value="fstinsidedec" />
+ <property name="command" value="on" />
+ <property name="name" value="FS.Tinside.dec.ON" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2635" protocol="virtual">
+ <property name="address" value="fsoutsideinc" />
+ <property name="command" value="status" />
+ <property name="name" value="FS.Toutside.inc" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2636" protocol="virtual">
+ <property name="address" value="fspir" />
+ <property name="command" value="on" />
+ <property name="name" value="FS.PIR.ON" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2637" protocol="virtual">
+ <property name="address" value="fswindow" />
+ <property name="command" value="on" />
+ <property name="name" value="FS.Window.(ON)" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2638" protocol="virtual">
+ <property name="address" value="fsoutside" />
+ <property name="command" value="status" />
+ <property name="name" value="FS.Toutside" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2639" protocol="virtual">
+ <property name="address" value="fswindow" />
+ <property name="command" value="off" />
+ <property name="name" value="FS.Window.(OFF)" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2640" protocol="virtual">
+ <property name="address" value="fsoutsidedec" />
+ <property name="command" value="status" />
+ <property name="name" value="FS.Toutside.dec" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2641" protocol="virtual">
+ <property name="address" value="fstinsidedec" />
+ <property name="command" value="status" />
+ <property name="name" value="FS.Tinside.dec" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2642" protocol="virtual">
+ <property name="address" value="fstinsideinc" />
+ <property name="command" value="status" />
+ <property name="name" value="FS.Tinside.inc" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2643" protocol="virtual">
+ <property name="address" value="fspir" />
+ <property name="command" value="off" />
+ <property name="name" value="FS.PIR.OFF" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2644" protocol="virtual">
+ <property name="address" value="fstinsideinc" />
+ <property name="command" value="on" />
+ <property name="name" value="FS.Tinside.inc.ON" />
+ <property name="urn:openremote:device-command:device-name" value="Fake sensors" />
+ <property name="urn:openremote:device-command:device-id" value="35488" />
+ </command>
+ <command id="2540" protocol="datetime">
+ <property name="timezone" value="Europe/Amsterdam" />
+ <property name="command" value="date" />
+ <property name="pollingInterval" value="1m" />
+ <property name="format" value="d" />
+ <property name="name" value="Timerd" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2553" protocol="datetime">
+ <property name="timezone" value="Europe/Amsterdam" />
+ <property name="command" value="date" />
+ <property name="pollingInterval" value="1m" />
+ <property name="format" value="EEEE" />
+ <property name="name" value="TimerEEEE" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2567" protocol="datetime">
+ <property name="timezone" value="Europe/Amsterdam" />
+ <property name="command" value="date" />
+ <property name="pollingInterval" value="1m" />
+ <property name="format" value="HH:mm:ss" />
+ <property name="name" value="TimerHH" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2569" protocol="datetime">
+ <property name="timezone" value="Europe/Amsterdam" />
+ <property name="command" value="date" />
+ <property name="pollingInterval" value="1m" />
+ <property name="format" value="MMM" />
+ <property name="name" value="TimerMMM" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ <command id="2570" protocol="datetime">
+ <property name="timezone" value="Europe/Amsterdam" />
+ <property name="command" value="date" />
+ <property name="pollingInterval" value="1m" />
+ <property name="format" value="EEE" />
+ <property name="name" value="TimerEEE" />
+ <property name="urn:openremote:device-command:device-name" value="Times" />
+ <property name="urn:openremote:device-command:device-id" value="35478" />
+ </command>
+ </commands>
+ <config>
+ <property name="multicast.address" value="224.0.1.100" />
+ <property name="zwave.pad.host" value="localhost" />
+ <property name="resource.upload.enable" value="true" />
+ <property name="protocol.velbus.classname" value="org.openremote.controller.protocol.velbus.VelbusCommandBuilder" />
+ <property name="copy.lircd.conf.on" value="true" />
+ <property name="lagarto_network.broadcast" value="tcp://127.0.0.1:5001" />
+ <property name="domintell.address" value="192.168.1.1" />
+ <property name="enocean.commLayer" value="RXTX" />
+ <property name="zwave.pad.port" value="7876" />
+ <property name="zwave.commLayer" value="RXTX" />
+ <property name="webapp.port" value="8688" />
+ <property name="protocol.zwave.classname" value="org.openremote.controller.protocol.zwave.ZWaveCommandBuilder" />
+ <property name="controller.groupname" value="floor20" />
+ <property name="lircd.conf.path" value="/etc/lircd.conf" />
+ <property name="multicast.port" value="3333" />
+ <property name="protocol.vera.classname" value="org.openremote.controller.protocol.vera.VeraCommandBuilder" />
+ <property name="velbus.server.ports" value="6000" />
+ <property name="Macro.IR.Execution.Delay" value="500" />
+ <property name="enocean.comPort" value="/dev/ttyUSB0" />
+ <property name="controller.roundrobin.tcpserver.port" value="20000" />
+ <property name="amx_ni.port" value="50000" />
+ <property name="zwave.comPort" value="/dev/ttyUSB0" />
+ <property name="lutron_homeworks.password" value="openremote" />
+ <property name="lutron_homeworks.address" value="192.168.1.1" />
+ <property name="irsend.path" value="/usr/local/bin/irsend" />
+ <property name="controller.applicationname" value="controller" />
+ <property name="protocol.samsungTV.classname" value="org.openremote.controller.protocol.samsungtv.SamsungTVRemoteCommandBuilder" />
+ <property name="enocean.serialProtocol" value="ESP3" />
+ <property name="samsungTV.address" value="" />
+ <property name="controller.roundrobin.multicast.port" value="10000" />
+ <property name="domintell.port" value="17481" />
+ <property name="amx_ni.address" value="192.168.1.1" />
+ <property name="velbus.server.hostnames" value="127.0.0.1" />
+ <property name="lutron_homeworks.username" value="openremote" />
+ <property name="controller.roundrobin.multicast.address" value="224.0.1.200" />
+ <property name="lutron_homeworks.port" value="23" />
+ <property name="controller.groupmember.autodetect.on" value="true" />
+ <property name="marantz_avr.address" value="192.168.1.1" />
+ <property name="vera.address" value="" />
+ <property name="protocol.alarm.classname" value="org.openremote.controller.protocol.alarm.AlarmCommandBuilder" />
+ </config>
+</openremote>
+
diff --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.csv
index 5d33b0a70..cc6d749b3 100644
--- a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/DTableTest.csv
+++ b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/DTableTest.csv
@@ -2,7 +2,7 @@
Ruleset, My CSV Rules Examples
Import, org.openremote.controller.event.Event
-Variables, org.openremote.controller.statuscache.RangeFacade ranges
+Variables, org.openremote.controller.event.facade.RangeFacade ranges
,RuleTable,Modify Range Values in Decision Table
@@ -10,6 +10,6 @@ Variables, org.openremote.controller.statuscache.RangeFacade ranges
,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",-77
+Fire Alarm,"TestSensor555",55
+Ice Age,"TestSensor666",6666
+Comfort,"TestSensor777",-77
diff --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.drl
index 1fe50ae29..43ebe86be 100644
--- a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/EventMod.drl
+++ b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/EventMod.drl
@@ -2,11 +2,11 @@ package org.openremote.test.rules;
import org.openremote.controller.event.*;
-global org.openremote.controller.statuscache.RangeFacade ranges;
+global org.openremote.controller.event.facade.RangeFacade ranges;
rule "Modify Level State Above Max"
when
- Event( sourceID == 123, $name : source )
+ Event( sourceID == 444, $name : source )
then
- ranges.name($name).value( 321 );
+ ranges.name($name).value( 12345 );
end
diff --git a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/controller.xml b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/controller.xml
new file mode 100755
index 000000000..2648f958d
--- /dev/null
+++ b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/controller.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<openremote xmlns="http://www.openremote.org"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.openremote.org http://www.openremote.org/schemas/controller.xsd">
+
+ <components>
+ </components>
+
+ <sensors>
+ <sensor id="444" type="range" name="TestSensor444">
+ <include type="command" ref="456"/>
+ <min value="0"/>
+ <max value="1000"/>
+ </sensor>
+ <sensor id="555" type="range" name="TestSensor555">
+ <include type="command" ref="456"/>
+ <min value="0"/>
+ <max value="1000"/>
+ </sensor>
+ </sensors>
+
+ <commands>
+ <command id="456" protocol="test">
+ <property name="name" value="TestCommand"/>
+ <property name="what-are-we-testing" value="a-test-range"/>
+ <property name="urn:openremote:device-command:device-name" value="TestDevice"/>
+ <property name="urn:openremote:device-command:device-id" value="111"/>
+ </command>
+ </commands>
+
+ <config>
+ </config>
+
+</openremote>
+
diff --git a/controller/src/test/resources/org/openremote/test/rules/simple/EventMod.drl b/controller/src/test/resources/org/openremote/test/rules/simple/EventMod.drl
index 44eb61dd0..9fb7f8073 100644
--- a/controller/src/test/resources/org/openremote/test/rules/simple/EventMod.drl
+++ b/controller/src/test/resources/org/openremote/test/rules/simple/EventMod.drl
@@ -2,7 +2,7 @@ package org.openremote.test.rules;
import org.openremote.controller.event.*;
-global org.openremote.controller.statuscache.SwitchFacade switches;
+global org.openremote.controller.event.facade.SwitchFacade switches;
rule "Modify Switch State"
when
diff --git a/controller/src/test/resources/org/openremote/test/rules/simple/controller.xml b/controller/src/test/resources/org/openremote/test/rules/simple/controller.xml
new file mode 100755
index 000000000..e9c4e73fc
--- /dev/null
+++ b/controller/src/test/resources/org/openremote/test/rules/simple/controller.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<openremote xmlns="http://www.openremote.org"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.openremote.org http://www.openremote.org/schemas/controller.xsd">
+
+ <components>
+ </components>
+
+ <sensors>
+ <sensor id="123" type="switch" name="TestSensor">
+ <include type="command" ref="456"/>
+ <state name="on"/>
+ <state name="off"/>
+ </sensor>
+ </sensors>
+
+ <commands>
+ <command id="456" protocol="test">
+ <property name="name" value="TestCommand"/>
+ <property name="what-are-we-testing" value="a-test-switch"/>
+ <property name="urn:openremote:device-command:device-name" value="TestDevice"/>
+ <property name="urn:openremote:device-command:device-id" value="111"/>
+ </command>
+ </commands>
+
+ <config>
+ </config>
+
+</openremote>
+
diff --git a/controller/src/test/resources/org/openremote/test/rules/vacation/Vacation.drl b/controller/src/test/resources/org/openremote/test/rules/vacation/Vacation.drl
index 023997334..7608d0cb8 100644
--- a/controller/src/test/resources/org/openremote/test/rules/vacation/Vacation.drl
+++ b/controller/src/test/resources/org/openremote/test/rules/vacation/Vacation.drl
@@ -1,6 +1,6 @@
package org.openremote.test.rules;
-global org.openremote.controller.event.CommandFacade execute;
+global org.openremote.controller.event.facade.CommandFacade execute;
import org.openremote.controller.command.*;
import org.openremote.controller.event.*;
diff --git a/controller/src/test/resources/org/openremote/test/rules/vacation/controller.xml b/controller/src/test/resources/org/openremote/test/rules/vacation/controller.xml
new file mode 100755
index 000000000..7e6e152a4
--- /dev/null
+++ b/controller/src/test/resources/org/openremote/test/rules/vacation/controller.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<openremote xmlns="http://www.openremote.org"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.openremote.org http://www.openremote.org/schemas/controller.xsd">
+
+ <components>
+ </components>
+
+ <sensors>
+ </sensors>
+
+ <commands>
+ <command id="456" protocol="test">
+ <property name="name" value="temp"/>
+ <property name="what-are-we-testing" value="an-executable-command"/>
+ <property name="urn:openremote:device-command:device-name" value="TestDevice"/>
+ <property name="urn:openremote:device-command:device-id" value="111"/>
+ </command>
+ </commands>
+
+ <config>
+ </config>
+
+</openremote>
+
diff --git a/gradle.properties b/gradle.properties
index cff48d50b..8bc6cc10e 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -36,3 +36,4 @@ geojsonJacksonVersion = 1.6
ahcVersion = 1.9.39
flexjsonVersion = 2.1
springVersion = 3.1.1.RELEASE
+sunriseSunsetCalculatorVersion = 1.2