100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Added AssetAttributeLinkingService
Rich Turner485b445281ff
diff --git a/manager/server/src/main/java/org/openremote/manager/server/Main.java b/manager/server/src/main/java/org/openremote/manager/server/Main.javaindex b142db31d..5b57f22a7 100644--- a/manager/server/src/main/java/org/openremote/manager/server/Main.java+++ b/manager/server/src/main/java/org/openremote/manager/server/Main.java@@ -28,6 +28,7 @@ import org.openremote.container.persistence.PersistenceService;import org.openremote.container.timer.TimerService;import org.openremote.manager.server.agent.AgentService;import org.openremote.manager.server.apps.ConsoleAppService;+import org.openremote.manager.server.asset.AssetAttributeLinkingService;import org.openremote.manager.server.asset.AssetProcessingService;import org.openremote.manager.server.asset.AssetStorageService;import org.openremote.manager.server.datapoint.AssetDatapointService;@@ -65,6 +66,7 @@ public class Main {new RulesService(),new AssetStorageService(),new AssetDatapointService(),+ new AssetAttributeLinkingService(),new AssetProcessingService()));ServiceLoader.load(Protocol.class).forEach(this::add);diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetAttributeLinkingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetAttributeLinkingService.javanew file mode 100644index 000000000..1130be50a--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetAttributeLinkingService.java@@ -0,0 +1,292 @@+/*+ * Copyright 2017, 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.manager.server.asset;++import org.openremote.container.Container;+import org.openremote.container.ContainerService;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetMeta;+import org.openremote.model.asset.AssetQuery;+import org.openremote.model.asset.AssetState;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.util.Pair;+import org.openremote.model.value.*;++import java.util.NoSuchElementException;+import java.util.Optional;+import java.util.function.Consumer;+import java.util.logging.Logger;++import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;++/**+ * This service listens for attribute events on attributes that have one or more {@link AssetMeta#ATTRIBUTE_LINK} meta+ * items.+ * <p>+ * If such an event occurs then the event is 'forwarded' to the linked attribute; an attribute can contain multiple+ * {@link AssetMeta#ATTRIBUTE_LINK} meta items; optionally the value forwarded to the linked attribute can be modified+ * by configuring the converter property in the meta item's value:+ * <p>+ * By default the exact value of the attribute is forwarded unless a key exists in the converter JSON Object that+ * matches the value as a string (note matches are case sensitive so booleans should be lower case i.e. true or false);+ * in that case the value of the key is forwarded instead. There are several special conversions available by using+ * the value of a {@link Converter} as the value. This allows for example a button press to toggle a boolean+ * attribute or for a particular value to be ignored.+ * <p>+ * To convert null values the converter key of "NULL" can be used.+ * <p>+ * <b>+ * NOTE: State converters (e.g. {@link Converter#TOGGLE}, {@link Converter#INCREMENT}, {@link Converter#DECREMENT}) are+ * not synchronised so if the initiating attribute (the one with the {@link AssetMeta#ATTRIBUTE_LINK} meta items)+ * generates multiple attribute events in a short period of time then the value pushed to the linked attribute may not+ * be correct.+ * </b>+ * <p>+ * Example {@link AssetMeta#ATTRIBUTE_LINK} meta items:+ * <blockquote><pre>{@code+ * [+ * "name": "urn:openremote:asset:meta:attributeLink",+ * "value": {+ * "attributeRef": ["0oI7Gf_kTh6WyRJFUTr8Lg", "light1"],+ * "converter": {+ * "PRESSED": "@TOGGLE",+ * "LONG_PRESSED": "@IGNORE",+ * "RELEASED": "@IGNORE"+ * }+ * }+ * ],+ * [+ * "name": "urn:openremote:asset:meta:attributeLink",+ * "value": {+ * "attributeRef": ["0oI7Gf_kTh6WyRJFUTr8Lg", "light2"],+ * "converter": {+ * "0": true,+ * "1": false+ * "NULL": "@IGNORE"+ * }+ * }+ * ]+ * }</pre></blockquote>+ */+// TODO: Improve AssetAttributeLinkingService so that outbound events are synchronsied with inbound+public class AssetAttributeLinkingService implements ContainerService, Consumer<AssetState> {++ public enum Converter {++ /**+ * Ignore this value (do not send to the linked attribute)+ */+ IGNORE("@IGNORE"),++ /**+ * Send a null vale to the linked attribute+ */+ NULL("@NULL"),++ /**+ * Toggle the value of the linked attribute; the linked attribute's type must be+ * {@link org.openremote.model.attribute.AttributeType#BOOLEAN}+ */+ TOGGLE("@TOGGLE"),++ /**+ * Increment the value of the linked attribute; the linked attribute's type must be+ * {@link org.openremote.model.attribute.AttributeType#NUMBER}+ */+ INCREMENT("@INCREMENT"),++ /**+ * Decrement the value of the linked attribute; the linked attribute's type must be+ * {@link org.openremote.model.attribute.AttributeType#NUMBER}+ */+ DECREMENT("@DECREMENT");++ private String value;+ // Prevents cloning of values each time fromString is called+ private static final Converter[] copyOfValues = values();++ Converter(String value) {+ this.value = value;+ }++ public String getValue() {+ return value;+ }++ public static Optional<Converter> fromString(String value) {+ for (Converter converter : copyOfValues) {+ if (converter.getValue().equalsIgnoreCase(value))+ return Optional.of(converter);+ }+ return Optional.empty();+ }+ }++ private static final Logger LOG = Logger.getLogger(AssetAttributeLinkingService.class.getName());+ protected AssetProcessingService assetProcessingService;+ protected AssetStorageService assetStorageService;++ @Override+ public void init(Container container) throws Exception {+ assetProcessingService = container.getService(AssetProcessingService.class);+ assetStorageService = container.getService(AssetStorageService.class);+ }++ @Override+ public void start(Container container) throws Exception {+ }++ @Override+ public void stop(Container container) throws Exception {+ }++ @Override+ public void accept(AssetState assetState) {+ assetState+ .getAttribute()+ .getMetaStream()+ .filter(isMetaNameEqualTo(AssetMeta.ATTRIBUTE_LINK))+ .forEach(metaItem -> processLinkedAttributeUpdate(metaItem, assetState));+ }++ protected void sendAttributeEvent(AttributeEvent attributeEvent) {+ LOG.fine("Sending attribute event for linked attribute: " + attributeEvent);+ assetProcessingService.sendAttributeEvent(attributeEvent);+ }++ protected void processLinkedAttributeUpdate(MetaItem attributeLink, AssetState assetState) {+ LOG.fine("Processing attribute event for linked attribute");+ Optional<Pair<AttributeRef, Optional<ObjectValue>>> linkAndConverter = getAttributeLinkAndConverter(attributeLink);++ if (!linkAndConverter.isPresent()) {+ LOG.info("Invalid attribute link on: " + assetState.getAttributeRef());+ return;+ }++ // Convert the value as required+ Pair<Boolean, Value> sendConvertedValue = convertValueForLinkedAttribute(+ assetState.getValue(),+ linkAndConverter.get().key,+ linkAndConverter.get().value,+ assetStorageService+ );++ if (!sendConvertedValue.key) {+ // Do not forward the event (either marked as ignored or there was a problem with the value conversion)+ return;+ }++ sendAttributeEvent(new AttributeEvent(linkAndConverter.get().key, sendConvertedValue.value));+ }++ protected static Optional<Pair<AttributeRef, Optional<ObjectValue>>> getAttributeLinkAndConverter(MetaItem metaItem) {+ return metaItem+ .getValueAsObject()+ .map(obj -> {+ Optional<AttributeRef> ref = AttributeRef.fromValue(obj.get("attributeRef").orElse(null));+ Optional<ObjectValue> converter = obj.getObject("converter");++ return ref+ .map(attributeRef -> new Pair<>(attributeRef, converter))+ .orElse(null);+ });+ }++ protected static Pair<Boolean, Value> convertValueForLinkedAttribute(Value originalValue, AttributeRef linkedAttributeRef, Optional<ObjectValue> converter, AssetStorageService assetStorageService) {+ return converter+ .map(+ conv -> {+ String converterKey = originalValue == null ? "NULL": originalValue.toString();+ Optional<Value> converterValue = conv.get(converterKey);+ // Convert the value+ return converterValue+ .map(value ->+ getSpecialConverter(value)+ .map(c -> doSpecialConversion(c, linkedAttributeRef, assetStorageService))+ .orElse(new Pair<>(true, value))) // use the converter value as the new value+ .orElseGet(() -> new Pair<>(true, originalValue)); // use the original value+ })+ .orElse(new Pair<>(true, originalValue)); // use the original value+ }++ protected static Optional<Converter> getSpecialConverter(Value value) {+ if (value.getType() == ValueType.STRING) {+ return Converter.fromString(value.toString());+ }+ return Optional.empty();+ }++ protected static Pair<Boolean, Value> doSpecialConversion(Converter converter, AttributeRef linkedAttributeRef, AssetStorageService assetStorageService) {+ switch (converter) {+ case IGNORE:+ LOG.fine("Converter set to ignore value so not forwarding to linked attribute");+ return new Pair<>(false, null);+ case NULL:+ return new Pair<>(true, null);+ case TOGGLE:+ // Look up current value of the linked attribute+ try {+ Value currentValue = getCurrentValue(linkedAttributeRef, assetStorageService);+ if (currentValue == null || currentValue.getType() != ValueType.BOOLEAN) {+ LOG.fine("Cannot toggle attribute value as attribute is not of type BOOLEAN: " + linkedAttributeRef);+ return new Pair<>(false, null);+ }+ return new Pair<>(true, Values.create(!((BooleanValue)currentValue).getBoolean()));+ } catch (NoSuchElementException e) {+ LOG.fine("The attribute doesn't exist so ignoring toggle value request: " + linkedAttributeRef);+ return new Pair<>(false, null);+ }+ case INCREMENT:+ case DECREMENT:+ // Look up current value of the linked attribute+ try {+ Value currentValue = getCurrentValue(linkedAttributeRef, assetStorageService);+ if (currentValue == null || currentValue.getType() != ValueType.NUMBER) {+ LOG.fine("Cannot increment/decrement attribute value as attribute is not of type NUMBER: " + linkedAttributeRef);+ return new Pair<>(false, null);+ }+ int change = converter == Converter.INCREMENT ? +1 : -1;+ return new Pair<>(true, Values.create(((NumberValue)currentValue).getNumber() + change));+ } catch (NoSuchElementException e) {+ LOG.fine("The attribute doesn't exist so ignoring increment/decrement value request: " + linkedAttributeRef);+ return new Pair<>(false, null);+ }+ default:+ throw new UnsupportedOperationException("Converter is not supported: " + converter);+ }+ }++ protected static Value getCurrentValue(AttributeRef attributeRef, AssetStorageService assetStorageService) throws NoSuchElementException {+ ServerAsset asset = assetStorageService.find(+ new AssetQuery()+ .id(attributeRef.getEntityId())+ .select(new AssetQuery.Select(attributeRef.getAttributeName()).loadComplete(true))+ );++ Optional<AssetAttribute> attribute = Optional.empty();+ if (asset == null || !(attribute = asset.getAttribute(attributeRef.getAttributeName())).isPresent()) {+ throw new NoSuchElementException("Attribute or asset could not be found: " + attributeRef);+ }++ return attribute.get().getValue().orElse(null);+ }+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.javaindex 759eba678..8e527e0e0 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java@@ -138,6 +138,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerprotected AgentService agentService;protected AssetStorageService assetStorageService;protected AssetDatapointService assetDatapointService;+ protected AssetAttributeLinkingService assetAttributeLinkingService;protected MessageBrokerService messageBrokerService;protected ClientEventService clientEventService;// Used in testing to detect if initial/startup processing has completed@@ -153,6 +154,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSeragentService = container.getService(AgentService.class);assetStorageService = container.getService(AssetStorageService.class);assetDatapointService = container.getService(AssetDatapointService.class);+ assetAttributeLinkingService = container.getService(AssetAttributeLinkingService.class);messageBrokerService = container.getService(MessageBrokerService.class);clientEventService = container.getService(ClientEventService.class);@@ -196,6 +198,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerprocessors.add(rulesService);processors.add(assetStorageService);processors.add(assetDatapointService);+ processors.add(assetAttributeLinkingService);container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);}diff --git a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovyindex 66e76dff4..fd67d9aa7 100644--- a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy+++ b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy@@ -14,6 +14,7 @@ import org.openremote.manager.server.agent.AgentServiceimport org.openremote.manager.server.apps.ConsoleAppServiceimport org.openremote.manager.server.asset.AssetProcessingServiceimport org.openremote.manager.server.asset.AssetStorageService+import org.openremote.manager.server.asset.AssetAttributeLinkingServiceimport org.openremote.manager.server.concurrent.ManagerExecutorServiceimport org.openremote.manager.server.datapoint.AssetDatapointServiceimport org.openremote.manager.server.event.ClientEventService@@ -62,6 +63,7 @@ trait ManagerContainerTrait extends ContainerTrait {new RulesService(),new AssetStorageService(),new AssetDatapointService(),+ new AssetAttributeLinkingService(),new AssetProcessingService(),*Lists.newArrayList(ServiceLoader.load(Protocol.class)),new AgentService(),diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetAttributeLinkingTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetAttributeLinkingTest.groovynew file mode 100644index 000000000..05938d1e5--- /dev/null+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetAttributeLinkingTest.groovy@@ -0,0 +1,161 @@+package org.openremote.test.assets++import org.openremote.manager.server.asset.AssetProcessingService+import org.openremote.manager.server.asset.AssetStorageService+import org.openremote.manager.server.asset.ServerAsset+import org.openremote.model.Constants+import org.openremote.model.asset.AssetAttribute+import org.openremote.model.asset.AssetMeta+import org.openremote.model.asset.AssetType+import org.openremote.model.attribute.*+import org.openremote.model.value.Values+import org.openremote.test.ManagerContainerTrait+import spock.lang.Specification+import spock.util.concurrent.PollingConditions++import java.util.logging.Logger++class AssetAttributeLinkingTest extends Specification implements ManagerContainerTrait {+ Logger LOG = Logger.getLogger(AssetAttributeLinkingTest.class.getName())++ def "Check processing of asset attributes that are linked to other attributes"() {++ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 10, delay: 1)++ when: "the container is started"+ def serverPort = findEphemeralPort()+ def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)++ then: "the container should be running and initialised"+ conditions.eventually {+ assertNothingProcessedFor(assetProcessingService, 500)+ }++ when: "assets are created"+ def asset1 = new ServerAsset("Asset 1", AssetType.THING, null, Constants.MASTER_REALM)+ asset1.setAttributes(+ new AssetAttribute("button", AttributeType.STRING, Values.create("RELEASED"))+ )+ asset1 = assetStorageService.merge(asset1)+ def asset2 = new ServerAsset("Asset 2", AssetType.THING, null, Constants.MASTER_REALM)+ asset2.setAttributes(+ new AssetAttribute("lightOnOff", AttributeType.BOOLEAN, Values.create(false)),+ new AssetAttribute("counter", AttributeType.NUMBER, Values.create(0))+ )+ asset2 = assetStorageService.merge(asset2)++ then: "the assets should be saved to the DB"+ assert asset1.id != null+ assert asset2.id != null++ when: "an attribute from one asset is linked to an attribute on the other"+ def converterOnOff = Values.createObject()+ converterOnOff.put("PRESSED", "@TOGGLE")+ converterOnOff.put("RELEASED", "@IGNORE")+ converterOnOff.put("LONG_PRESSED", "@IGNORE")+ def attributeLinkOnOff = Values.createObject()+ attributeLinkOnOff.put("attributeRef", new AttributeRef(asset2.id, "lightOnOff").toArrayValue())+ attributeLinkOnOff.put("converter", converterOnOff)++ def converterCounter = Values.createObject()+ converterCounter.put("PRESSED", "@INCREMENT")+ converterCounter.put("RELEASED", "@DECREMENT")+ converterCounter.put("LONG_PRESSED", "@IGNORE")+ def attributeLinkCounter = Values.createObject()+ attributeLinkCounter.put("attributeRef", new AttributeRef(asset2.id, "counter").toArrayValue())+ attributeLinkCounter.put("converter", converterCounter)++ asset1.getAttribute("button").get().addMeta(new MetaItem(AssetMeta.ATTRIBUTE_LINK, attributeLinkOnOff))+ asset1.getAttribute("button").get().addMeta(new MetaItem(AssetMeta.ATTRIBUTE_LINK, attributeLinkCounter))+ asset1 = assetStorageService.merge(asset1)++ and: "the button is pressed for a short period"+ def buttonPressed = new AttributeEvent(+ new AttributeState(new AttributeRef(asset1.id, "button"), Values.create("PRESSED"))+ )+ assetProcessingService.sendAttributeEvent(buttonPressed)+ Thread.sleep(10)+ def buttonReleased = new AttributeEvent(+ new AttributeState(new AttributeRef(asset1.id, "button"), Values.create("RELEASED"))+ )+ assetProcessingService.sendAttributeEvent(buttonReleased)++ then: "the linked attribute value should be toggled on"+ conditions.eventually {+ asset2 = assetStorageService.find(asset2.id, true)+ assert asset2.getAttribute("lightOnOff").get().getValueAsBoolean().get()+ }++ when: "the button is pressed again for a short period"+ buttonPressed = new AttributeEvent(+ new AttributeState(new AttributeRef(asset1.id, "button"), Values.create("PRESSED"))+ )+ assetProcessingService.sendAttributeEvent(buttonPressed)+ Thread.sleep(10)+ buttonReleased = new AttributeEvent(+ new AttributeState(new AttributeRef(asset1.id, "button"), Values.create("RELEASED"))+ )+ assetProcessingService.sendAttributeEvent(buttonReleased)++ then: "the linked attribute value should be toggled off"+ conditions.eventually {+ asset2 = assetStorageService.find(asset2.id, true)+ assert !asset2.getAttribute("lightOnOff").get().getValueAsBoolean().get()+ }+ when: "a long button press occurs"+ def buttonLongPressed = new AttributeEvent(+ new AttributeState(new AttributeRef(asset1.id, "button"), Values.create("LONG_PRESSED"))+ )+ assetProcessingService.sendAttributeEvent(buttonLongPressed)+ Thread.sleep(10)+ buttonReleased = new AttributeEvent(+ new AttributeState(new AttributeRef(asset1.id, "button"), Values.create("RELEASED"))+ )+ assetProcessingService.sendAttributeEvent(buttonReleased)++ then: "the linked attribute value should not have changed and the system has settled down"+ conditions.eventually {+ asset2 = assetStorageService.find(asset2.id, true)+ assert !asset2.getAttribute("lightOnOff").get().getValueAsBoolean().get()+ assertNothingProcessedFor(assetProcessingService, 1000)+ }++ // Need to reset counter due to synchronisation issues (ideally counter would still be at 0 as+ // each press event had a corresponding release event)+ when: "the counter is reset"+ def attr = asset2.getAttribute("counter").get()+ attr.setValue(0.0)+ asset2.replaceAttribute(attr)+ asset2 = assetStorageService.merge(asset2)++ and: "A button press event occurs without a release event"+ buttonPressed = new AttributeEvent(+ new AttributeState(new AttributeRef(asset1.id, "button"), Values.create("PRESSED"))+ )+ assetProcessingService.sendAttributeEvent(buttonPressed)++ then: "the counter should increment"+ conditions.eventually {+ asset2 = assetStorageService.find(asset2.id, true)+ assert asset2.getAttribute("counter").get().getValueAsNumber().get() == 1.0+ }++ when: "A button release event occur"+ buttonReleased = new AttributeEvent(+ new AttributeState(new AttributeRef(asset1.id, "button"), Values.create("RELEASED"))+ )+ assetProcessingService.sendAttributeEvent(buttonReleased)++ then: "the counter should decrement"+ conditions.eventually {+ asset2 = assetStorageService.find(asset2.id, true)+ assert asset2.getAttribute("counter").get().getValueAsNumber().get() == 0.0+ }++ cleanup: "the server should be stopped"+ stopContainer(container)+ }+}diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovyindex 916838a8e..b6c3a116a 100644--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy@@ -268,5 +268,8 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitassert updatesPassedDatapointService[0].error == nullassert updatesPassedDatapointService[0].processingStatus == AssetState.ProcessingStatus.COMPLETED}++ cleanup: "the server should be stopped"+ stopContainer(container)}}diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.javaindex 76a4b63dc..580fffef1 100644--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java@@ -56,6 +56,12 @@ public enum AssetMeta implements HasUniqueResourceName {*/AGENT_LINK(ASSET_META_NAMESPACE + ":agentLink", new Access(false, false, true), ValueType.ARRAY),+ /**+ * Links the attribute to another attribute, so an attribute event on the attribute triggers the same attribute+ * event on the linked attribute.+ */+ ATTRIBUTE_LINK(ASSET_META_NAMESPACE + ":attributeLink", new Access(false, false, true), ValueType.OBJECT),+/*** A human-friendly string that can be displayed in UI instead of the raw attribute name.*/