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 MessageFilter functionality to protocols
Rich Turnerffb1b0c789b8
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.javaindex 99e57737b..fdc0f9136 100644--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java@@ -21,6 +21,7 @@ package org.openremote.agent.protocol;import org.apache.camel.ProducerTemplate;import org.apache.camel.builder.RouteBuilder;+import org.openremote.agent.protocol.filter.MessageFilter;import org.openremote.container.Container;import org.openremote.container.message.MessageBrokerContext;import org.openremote.container.message.MessageBrokerService;@@ -33,11 +34,15 @@ import org.openremote.model.asset.AssetMeta;import org.openremote.model.asset.agent.AgentLink;import org.openremote.model.asset.agent.ConnectionStatus;import org.openremote.model.asset.agent.ProtocolConfiguration;-import org.openremote.model.attribute.*;import org.openremote.model.asset.agent.ProtocolDescriptor;+import org.openremote.model.attribute.*;+import org.openremote.model.value.Value;+import org.openremote.model.value.ValueType;+import org.openremote.model.value.Values;import java.util.*;import java.util.function.Consumer;+import java.util.logging.Level;import java.util.logging.Logger;public abstract class AbstractProtocol implements Protocol {@@ -79,6 +84,7 @@ public abstract class AbstractProtocol implements Protocol {protected final Map<AttributeRef, AssetAttribute> linkedAttributes = new HashMap<>();protected final Map<AttributeRef, LinkedProtocolInfo> linkedProtocolConfigurations = new HashMap<>();+ protected final Map<AttributeRef, List<MessageFilter>> linkedAttributeFilters = new HashMap<>();protected MessageBrokerContext messageBrokerContext;protected ProducerTemplate producerTemplate;protected TimerService timerService;@@ -162,8 +168,25 @@ public abstract class AbstractProtocol implements Protocol {synchronized (linkedAttributes) {attributes.forEach(attribute -> {LOG.fine("Linking attribute to '" + getProtocolName() + "': " + attribute);- linkedAttributes.put(attribute.getReferenceOrThrow(), attribute);- doLinkAttribute(attribute, protocolConfiguration);+ AttributeRef attributeRef = attribute.getReferenceOrThrow();+ // Need to add to map before actual linking as protocols may want to update the value as part of+ // linking process and without entry in the map any update would be blocked+ linkedAttributes.put(attributeRef, attribute);+ Optional<List<MessageFilter>> messageFilters = Protocol.getLinkedAttributeMessageFilters(attribute);+ if (messageFilters.isPresent()) {+ synchronized (linkedAttributeFilters) {+ linkedAttributeFilters.put(attributeRef, messageFilters.get());+ }+ }+ try {+ doLinkAttribute(attribute, protocolConfiguration);+ } catch (Exception e) {+ LOG.log(Level.SEVERE, "Failed to link attribute to protocol: " + attribute, e);+ linkedAttributes.remove(attributeRef);+ synchronized (linkedAttributeFilters) {+ linkedAttributeFilters.remove(attributeRef);+ }+ }});}}@@ -173,8 +196,12 @@ public abstract class AbstractProtocol implements Protocol {synchronized (linkedAttributes) {attributes.forEach(attribute -> {LOG.fine("Unlinking attribute on '" + getProtocolName() + "': " + attribute);+ AttributeRef attributeRef = attribute.getReferenceOrThrow();+ linkedAttributes.remove(attributeRef);+ synchronized (linkedAttributeFilters) {+ linkedAttributeFilters.remove(attributeRef);+ }doUnlinkAttribute(attribute, protocolConfiguration);- linkedAttributes.remove(attribute.getReferenceOrThrow());});}}@@ -220,33 +247,98 @@ public abstract class AbstractProtocol implements Protocol {*/protected void sendAttributeEvent(AttributeEvent event) {// Don't allow updating linked attributes with this mechanism as it could cause an infinite loop+ boolean isForLinkedAttribute;+synchronized (linkedAttributes) {- boolean isForLinkedAttribute = linkedAttributes.values()- .stream()- .anyMatch(attribute -> attribute.getReferenceOrThrow()- .equals(event.getAttributeRef())- );-- if (isForLinkedAttribute) {- LOG.warning("Cannot update an attribute linked to the same protocol; use updateLinkedAttribute for that: " + event);- return;- }+ isForLinkedAttribute = linkedAttributes.containsKey(event.getAttributeRef());+ }++ if (isForLinkedAttribute) {+ LOG.warning("Cannot update an attribute linked to the same protocol; use updateLinkedAttribute for that: " + event);+ return;}assetService.sendAttributeEvent(event);}/**- * Update the value of a linked attribute. Call this to publish new sensor values.+ * Update the value of a linked attribute. Call this to publish new sensor values. This will apply any+ * {@link MessageFilter}s that have been set for the {@link Attribute} against the {@link AttributeState#value}+ * before sending on the sensor queue.*/protected void updateLinkedAttribute(AttributeState state, long timestamp) {+ AssetAttribute attribute;+ synchronized (linkedAttributes) {+ attribute = linkedAttributes.get(state.getAttributeRef());+ }++ if (attribute == null) {+ LOG.severe("Update linked attribute called for un-linked attribute: " + state);+ return;+ }++ if (state.getCurrentValue().isPresent()) {+ List<MessageFilter> filters;+ Value value = state.getCurrentValue().get();++ synchronized (linkedAttributeFilters) {+ filters = linkedAttributeFilters.get(state.getAttributeRef());+ }++ if (filters != null) {+ LOG.fine("Applying message filters to sensor value...");++ for (MessageFilter filter : filters) {+ if (filter.getMessageType() != value.getType().getModelType()) {+ LOG.fine("Message filter type '" + filter.getMessageType().getName()+ + "' is not compatible with actual message type '" + value.getType().getModelType().getName()+ + "': " + filter.getClass().getName());+ value = null;+ } else {+ try {+ LOG.finest("Applying message filter: " + filter.getClass().getName());+ //noinspection unchecked+ value = filter.process(value);+ } catch (Exception e) {+ LOG.log(+ Level.SEVERE,+ "Message filter threw and exception during processing of message: "+ + filter.getClass().getName(),+ e);+ value = null;+ }+ }++ if (value == null) {+ break;+ }+ }+ }++ // Do basic value conversion+ Optional<ValueType> attributeValueType = attribute.getType().map(AttributeType::getValueType);++ if (value != null && attributeValueType.isPresent()) {+ if (attributeValueType.get() != value.getType()) {+ LOG.fine("Converting value: " + value.getType() + " -> " + attributeValueType.get());+ Optional<Value> convertedValue = Values.convert(value, attributeValueType.get());+ if (!convertedValue.isPresent()) {+ LOG.warning("Failed to convert value: " + value.getType() + " -> " + attributeValueType.get());+ } else {+ value = convertedValue.get();+ }+ }+ }++ state = new AttributeState(state.getAttributeRef(), value);+ }AttributeEvent attributeEvent = new AttributeEvent(state, timestamp);LOG.fine("Sending on sensor queue: " + attributeEvent);producerTemplate.sendBodyAndHeader(SENSOR_QUEUE, attributeEvent, Protocol.SENSOR_QUEUE_SOURCE_PROTOCOL, getProtocolName());}/**- * Update the value of a linked attribute, with the current system time as event time. Call this to publish new- * sensor values.+ * Update the value of a linked attribute, with the current system time as event time see+ * {@link #updateLinkedAttribute(AttributeState, long)} for more details.*/protected void updateLinkedAttribute(AttributeState state) {updateLinkedAttribute(state, timerService.getCurrentTimeMillis());diff --git a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent/protocol/Protocol.javaindex a5572580b..e78b2555f 100644--- a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java@@ -19,22 +19,33 @@*/package org.openremote.agent.protocol;+import org.openremote.agent.protocol.filter.MessageFilter;+import org.openremote.container.Container;import org.openremote.container.ContainerService;+import org.openremote.model.AbstractValueHolder;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetAttribute;import org.openremote.model.asset.AssetMeta;import org.openremote.model.asset.AssetType;import org.openremote.model.asset.agent.ConnectionStatus;import org.openremote.model.asset.agent.ProtocolConfiguration;-import org.openremote.model.attribute.AttributeValidationResult;import org.openremote.model.asset.agent.ProtocolDescriptor;-import org.openremote.model.attribute.AttributeEvent;-import org.openremote.model.attribute.AttributeType;-import org.openremote.model.attribute.MetaItem;+import org.openremote.model.attribute.*;+import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.ObjectValue;import org.openremote.model.value.ValueType;+import sun.plugin2.message.Message;+import java.io.IOException;+import java.util.ArrayList;import java.util.Collection;+import java.util.List;+import java.util.Optional;import java.util.function.Consumer;+import java.util.logging.Level;+import java.util.logging.Logger;++import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;/*** A protocol is a thread-safe singleton {@link ContainerService} that connects devices and@@ -80,6 +91,10 @@ import java.util.function.Consumer;* {@link AttributeType} and therefore a base {@link ValueType}, the protocol implementation must* receive and send value change messages with values of that type.* <p>+ * Generic protocols should implement support for filtering state messages from devices (or services) before the+ * protocol updates the linked attribute, to implement this protocols should use the {@link #META_PROTOCOL_FILTERS}+ * {@link MetaItem}.+ * <p>* NOTE: That {@link #linkProtocolConfiguration} will always be called* before {@link #linkAttributes} and {@link #unlinkAttributes} will always be called before* {@link #unlinkProtocolConfiguration}.@@ -124,9 +139,19 @@ import java.util.function.Consumer;*/public interface Protocol extends ContainerService {+ Logger LOG = Logger.getLogger(Protocol.class.getName());String ACTUATOR_TOPIC_TARGET_PROTOCOL = "Protocol";String SENSOR_QUEUE_SOURCE_PROTOCOL = "Protocol";+ /**+ * {@link MetaItem} for defining {@link MessageFilter}s to apply to values before they are sent on the+ * {@link #SENSOR_QUEUE} (i.e. before it is used to update a protocol linked attribute); this is particularly+ * useful for generic protocols. The {@link MetaItem} should be an {@link ArrayValue} of {@link ObjectValue}s where+ * each {@link ObjectValue} represents a serialised {@link MessageFilter}. The message should pass through the+ * filters in array order.+ */+ String META_PROTOCOL_FILTERS = PROTOCOL_NAMESPACE + ":filters";+// TODO: Some of these options should be configurable depending on expected load etc.// Message topic for communicating from asset/thing to protocol layer (asset attribute changed, trigger actuator)@@ -169,9 +194,12 @@ public interface Protocol extends ContainerService {/*** Links the protocol configuration to the protocol; the protocol is responsible for calling the statusConsumer- * to indicate the runtime state of the protocol configuration.+ * to indicate the runtime state of the protocol configuration. If the {@link ConnectionStatus} is set to+ * {@link ConnectionStatus#ERROR} or {@link ConnectionStatus#ERROR_CONFIGURATION} or this method throws an exception+ * then attribute linking will be skipped for this {@link ProtocolConfiguration}.*/- void linkProtocolConfiguration(AssetAttribute protocolConfiguration, Consumer<ConnectionStatus> statusConsumer);+ void linkProtocolConfiguration(AssetAttribute protocolConfiguration, Consumer<ConnectionStatus> statusConsumer)+ throws Exception;/*** Un-links the protocol configuration from the protocol; called whenever a protocolConfiguration is modified@@ -196,4 +224,49 @@ public interface Protocol extends ContainerService {* protocol configuration is well formed but not necessarily that it connects to a working system).*/AttributeValidationResult validateProtocolConfiguration(AssetAttribute protocolConfiguration);++ /**+ * Extract the {@link MessageFilter}s from the specified {@link Attribute}+ */+ static Optional<List<MessageFilter>> getLinkedAttributeMessageFilters(Attribute attribute) {+ if (attribute == null) {+ return Optional.empty();+ }++ Optional<ArrayValue> arrayValueOptional = attribute.getMetaItem(META_PROTOCOL_FILTERS)+ .flatMap(AbstractValueHolder::getValueAsArray);++ if (!arrayValueOptional.isPresent()) {+ return Optional.empty();+ }++ try {+ ArrayValue arrayValue = arrayValueOptional.get();+ List<MessageFilter> messageFilters = new ArrayList<>(arrayValue.length());+ for (int i = 0; i < arrayValue.length(); i++) {+ ObjectValue objValue = arrayValue.getObject(i).orElseThrow(() ->+ new IllegalArgumentException("Attribute protocol filters meta item is invalid"));+ MessageFilter filter = deserialiseMessageFilter(objValue);+ messageFilters.add(filter);+ }+ return messageFilters.isEmpty() ? Optional.empty() : Optional.of(messageFilters);+ } catch (IllegalArgumentException e) {+ LOG.log(Level.WARNING, e.getMessage(), e);+ }++ return Optional.empty();+ }++ /**+ * Deserialise a {@link MessageFilter} from an {@link ObjectValue}+ */+ static MessageFilter deserialiseMessageFilter(ObjectValue objectValue) throws IllegalArgumentException {+ String json = objectValue.toJson();+ try {+ return Container.JSON.readValue(json, MessageFilter.class);+ } catch (IOException ioException) {+ LOG.log(Level.WARNING, "Failed to deserialise message filter", ioException);+ throw new IllegalArgumentException(ioException);+ }+ }}diff --git a/agent/src/main/java/org/openremote/agent/protocol/filter/MessageFilter.java b/agent/src/main/java/org/openremote/agent/protocol/filter/MessageFilter.javanew file mode 100644index 000000000..b4d814088--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/filter/MessageFilter.java@@ -0,0 +1,71 @@+/*+ * 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.agent.protocol.filter;++import com.fasterxml.jackson.annotation.JsonSubTypes;+import com.fasterxml.jackson.annotation.JsonTypeInfo;+import com.fasterxml.jackson.core.JsonProcessingException;+import org.openremote.agent.protocol.http.OAuthGrant;+import org.openremote.container.Container;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.ValueType;+import org.openremote.model.value.Values;++import java.util.Optional;++/**+ * Interface for a filter that can be applied to messages of type <T> the filter can return a different+ * {@link ValueType} to the supplied message (i.e. value conversion as well as filtering). Filters can be chained and+ * filters should be applied using the following logic:+ * <ul>+ * <li>If message is null then do not pass through filter</li>+ * <li>If message type doesn't match the filter's message type then treat as if filter returned null</li>+ * <li>If filter throws an exception then handle and treat as if filter returned null</li>+ * </ul>+ */+@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property = "type")+@JsonSubTypes({+ @JsonSubTypes.Type(name = RegexFilter.NAME, value = RegexFilter.class),+ @JsonSubTypes.Type(name = SubStringFilter.NAME, value = SubStringFilter.class)+})+public abstract class MessageFilter<T extends Value> {++ /**+ * Get the message type+ */+ public abstract Class<T> getMessageType();++ /**+ * Apply this filter to the supplied message+ */+ public abstract Value process(T message);++ /**+ * Convert this filter to an {@link ObjectValue}+ */+ public Optional<ObjectValue> toValue() {+ try {+ String json = Container.JSON.writeValueAsString(this);+ return Values.parse(json);+ } catch (JsonProcessingException ignore) {}+ return Optional.empty();+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/filter/RegexFilter.java b/agent/src/main/java/org/openremote/agent/protocol/filter/RegexFilter.javanew file mode 100644index 000000000..31517c379--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/filter/RegexFilter.java@@ -0,0 +1,97 @@+/*+ * 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.agent.protocol.filter;++import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonProperty;+import com.fasterxml.jackson.annotation.JsonTypeName;+import com.fasterxml.jackson.core.JsonProcessingException;+import org.openremote.container.Container;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.StringValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;++import java.util.Optional;+import java.util.regex.Matcher;+import java.util.regex.Pattern;+import java.util.regex.PatternSyntaxException;++import static org.openremote.agent.protocol.filter.RegexFilter.NAME;++@JsonTypeName(NAME)+public class RegexFilter extends MessageFilter<StringValue> {++ public static final String NAME = "regex";++ @JsonProperty+ protected Pattern pattern;+ @JsonProperty+ protected int matchGroup;+ @JsonProperty+ protected int matchIndex;++ @JsonCreator+ public RegexFilter(@JsonProperty("pattern") String regex,+ @JsonProperty("matchGroup") int matchGroup,+ @JsonProperty("matchIndex") int matchIndex) {+ try {+ pattern = Pattern.compile(regex);+ this.matchGroup = matchGroup;+ this.matchIndex = matchIndex;+ } catch (PatternSyntaxException ignore) {}+ }++ public RegexFilter(Pattern pattern, int matchGroup, int matchIndex) {+ this.pattern = pattern;+ this.matchGroup = matchGroup;+ this.matchIndex = matchIndex;+ }++ @Override+ public Class<StringValue> getMessageType() {+ return StringValue.class;+ }++ @Override+ public Value process(StringValue value) {+ if (value == null || pattern == null) {+ return null;+ }++ String filteredStr = null;+ Matcher matcher = pattern.matcher(value.getString());+ int matchIndex = 0;+ boolean matched = matcher.find();++ while(matched && matchIndex<this.matchIndex) {+ matched = matcher.find();+ matchIndex++;+ }++ if (matched) {+ if (matchGroup <= matcher.groupCount()) {+ filteredStr = matcher.group(matchGroup);+ }+ }++ return filteredStr == null ? null : Values.create(filteredStr);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/filter/SubStringFilter.java b/agent/src/main/java/org/openremote/agent/protocol/filter/SubStringFilter.javanew file mode 100644index 000000000..e599c30a0--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/filter/SubStringFilter.java@@ -0,0 +1,74 @@+/*+ * 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.agent.protocol.filter;++import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonProperty;+import com.fasterxml.jackson.annotation.JsonTypeName;+import org.openremote.model.value.StringValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;++import static org.openremote.agent.protocol.filter.SubStringFilter.NAME;++@JsonTypeName(NAME)+public class SubStringFilter extends MessageFilter<StringValue> {++ public static final String NAME = "substring";++ @JsonProperty+ protected int beginIndex;+ @JsonProperty+ protected Integer endIndex;++ @JsonCreator+ public SubStringFilter(@JsonProperty("beginIndex") int beginIndex, @JsonProperty("endIndex") Integer endIndex) {+ this.beginIndex = beginIndex;+ this.endIndex = endIndex;+ }++ public SubStringFilter(int beginIndex) {+ this.beginIndex = beginIndex;+ }++ @Override+ public Class<StringValue> getMessageType() {+ return StringValue.class;+ }++ @Override+ public Value process(StringValue value) {+ if (value == null) {+ return null;+ }++ String result = null;++ try {+ if (endIndex != null) {+ result = value.getString().substring(beginIndex, endIndex);+ } else {+ result = value.getString().substring(beginIndex);+ }+ } catch (IndexOutOfBoundsException ignored) {}++ return result == null ? null : Values.create(result);+ }+}diff --git a/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovyindex e78db80ff..a418dd1b6 100644--- a/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy@@ -20,6 +20,9 @@package org.openremote.test.protocolimport org.openremote.agent.protocol.AbstractProtocol+import org.openremote.agent.protocol.Protocol+import org.openremote.agent.protocol.filter.RegexFilter+import org.openremote.agent.protocol.filter.SubStringFilterimport org.openremote.model.asset.agent.AgentStatusEventimport org.openremote.model.asset.agent.ConnectionStatusimport org.openremote.manager.server.agent.AgentService@@ -61,7 +64,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,and: "a mock protocol"def mockProtocolName = "urn:myCustom:mockProtocol"Map<String, Integer> protocolExpectedLinkedAttributeCount = [:]- protocolExpectedLinkedAttributeCount['mockConfig1'] = 2+ protocolExpectedLinkedAttributeCount['mockConfig1'] = 5protocolExpectedLinkedAttributeCount['mockConfig2'] = 2protocolExpectedLinkedAttributeCount['mockConfig3'] = 2protocolExpectedLinkedAttributeCount['mockConfig4'] = 2@@ -74,11 +77,11 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,List<AttributeEvent> protocolWriteAttributeEvents = []List<String> protocolMethodCalls = []def mockProtocol = new AbstractProtocol() {- protected void responseReceived() {+ protected void updateReceived(AttributeState state) {// Assume we've pushed the update to the actual device and it responded with OK// so now we want to cause a sensor update that will go through the processing// chain.- updateLinkedAttribute(protocolWriteAttributeEvents.last().getAttributeState())+ updateLinkedAttribute(state)}protected void updateAttribute(AttributeState state) {@@ -119,6 +122,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,def deploymentStatus = getStatus(protocolConfiguration)if (deploymentStatus == ConnectionStatus.CONNECTED) {String attributeName = attribute.getName().orElse("")+if (attributeName.startsWith("lightToggle")) {// Set all lights to onupdateLinkedAttribute(new AttributeState(attribute.getReferenceOrThrow(), Values.create(true)))@@ -256,92 +260,130 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,when: "a mock thing asset is created that links to the mock protocol configurations"def mockThing = new ServerAsset("Mock Thing Asset", AssetType.THING, mockAgent)mockThing.setAttributes(- new AssetAttribute("lightToggle1", AttributeType.BOOLEAN)- .setMeta(- new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),- new MetaItem(- AssetMeta.AGENT_LINK,- new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()- )- ),- new AssetAttribute("tempTarget1", AttributeType.NUMBER)- .setMeta(- new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),- new MetaItem(- AssetMeta.AGENT_LINK,- new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()- )- ),- new AssetAttribute("invalidToggle1", AttributeType.BOOLEAN)+ new AssetAttribute("lightToggle1", AttributeType.BOOLEAN)+ .setMeta(+ new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),+ new MetaItem(+ AssetMeta.AGENT_LINK,+ new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()+ )+ ),+ new AssetAttribute("tempTarget1", AttributeType.NUMBER)+ .setMeta(+ new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),+ new MetaItem(+ AssetMeta.AGENT_LINK,+ new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()+ )+ ),+ new AssetAttribute("invalidToggle1", AttributeType.BOOLEAN)+ .setMeta(+ new MetaItem(+ AssetMeta.AGENT_LINK,+ new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()+ )+ ),+ new AssetAttribute("lightToggle2", AttributeType.BOOLEAN)+ .setMeta(+ new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),+ new MetaItem(+ AssetMeta.AGENT_LINK,+ new AttributeRef(mockAgent.getId(), "mockConfig2").toArrayValue()+ )+ ),+ new AssetAttribute("tempTarget2", AttributeType.NUMBER)+ .setMeta(+ new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),+ new MetaItem(+ AssetMeta.AGENT_LINK,+ new AttributeRef(mockAgent.getId(), "mockConfig2").toArrayValue()+ )+ ),+ new AssetAttribute("lightToggle3", AttributeType.BOOLEAN)+ .setMeta(+ new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),+ new MetaItem(+ AssetMeta.AGENT_LINK,+ new AttributeRef(mockAgent.getId(), "mockConfig3").toArrayValue()+ )+ ),+ new AssetAttribute("tempTarget3", AttributeType.NUMBER)+ .setMeta(+ new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),+ new MetaItem(+ AssetMeta.AGENT_LINK,+ new AttributeRef(mockAgent.getId(), "mockConfig3").toArrayValue()+ )+ ),+ new AssetAttribute("lightToggle4", AttributeType.BOOLEAN)+ .setMeta(+ new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),+ new MetaItem(+ AssetMeta.AGENT_LINK,+ new AttributeRef(mockAgent.getId(), "mockConfig4").toArrayValue()+ )+ ),+ new AssetAttribute("tempTarget4", AttributeType.NUMBER).setMeta(- new MetaItem(+ new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),+ new MetaItem(AssetMeta.AGENT_LINK,- new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()- )- ),- new AssetAttribute("lightToggle2", AttributeType.BOOLEAN)- .setMeta(- new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),- new MetaItem(- AssetMeta.AGENT_LINK,- new AttributeRef(mockAgent.getId(), "mockConfig2").toArrayValue()- )- ),- new AssetAttribute("tempTarget2", AttributeType.NUMBER)- .setMeta(- new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),- new MetaItem(- AssetMeta.AGENT_LINK,- new AttributeRef(mockAgent.getId(), "mockConfig2").toArrayValue()- )+ new AttributeRef(mockAgent.getId(), "mockConfig4").toArrayValue()+ )+ ),+ new AssetAttribute("invalidToggle5", AttributeType.BOOLEAN, Values.create(false))+ .setMeta(+ new MetaItem(+ AssetMeta.AGENT_LINK,+ new AttributeRef(mockAgent.getId(), "INVALID CONFIG").toArrayValue()+ )),- new AssetAttribute("lightToggle3", AttributeType.BOOLEAN)- .setMeta(- new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),- new MetaItem(- AssetMeta.AGENT_LINK,- new AttributeRef(mockAgent.getId(), "mockConfig3").toArrayValue()- )+ new AssetAttribute("plainAttribute", AttributeType.STRING, Values.create("demo"))+ .setMeta(+ new MetaItem(+ AssetMeta.DESCRIPTION,+ Values.create("A plain string attribute for storing information")),- new AssetAttribute("tempTarget3", AttributeType.NUMBER)- .setMeta(- new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),- new MetaItem(- AssetMeta.AGENT_LINK,- new AttributeRef(mockAgent.getId(), "mockConfig3").toArrayValue()- )+ new MetaItem(AssetMeta.READ_ONLY, Values.create(true))+ ),+ new AssetAttribute("filterRegex", AttributeType.NUMBER)+ .setMeta(+ new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),+ new MetaItem(+ AssetMeta.AGENT_LINK,+ new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()),- new AssetAttribute("lightToggle4", AttributeType.BOOLEAN)- .setMeta(- new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),- new MetaItem(- AssetMeta.AGENT_LINK,- new AttributeRef(mockAgent.getId(), "mockConfig4").toArrayValue()- )+ new MetaItem(+ Protocol.META_PROTOCOL_FILTERS,+ Values.createArray().add(new RegexFilter("\\w(\\d+)", 1, 2).toValue().get())+ )+ ),+ new AssetAttribute("filterSubstring", AttributeType.STRING)+ .setMeta(+ new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),+ new MetaItem(+ AssetMeta.AGENT_LINK,+ new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()),- new AssetAttribute("tempTarget4", AttributeType.NUMBER)- .setMeta(- new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),- new MetaItem(- AssetMeta.AGENT_LINK,- new AttributeRef(mockAgent.getId(), "mockConfig4").toArrayValue()- )+ new MetaItem(+ Protocol.META_PROTOCOL_FILTERS,+ Values.createArray().add(new SubStringFilter(10, 12).toValue().get())+ )+ ),+ new AssetAttribute("filterRegexSubstring", AttributeType.NUMBER)+ .setMeta(+ new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META", Values.create(true)),+ new MetaItem(+ AssetMeta.AGENT_LINK,+ new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()),- new AssetAttribute("invalidToggle5", AttributeType.BOOLEAN, Values.create(false))- .setMeta(- new MetaItem(- AssetMeta.AGENT_LINK,- new AttributeRef(mockAgent.getId(), "INVALID CONFIG").toArrayValue()- )- ),- new AssetAttribute("plainAttribute", AttributeType.STRING, Values.create("demo"))- .setMeta(- new MetaItem(- AssetMeta.DESCRIPTION,- Values.create("A plain string attribute for storing information")- ),- new MetaItem(AssetMeta.READ_ONLY, Values.create(true))+ new MetaItem(+ Protocol.META_PROTOCOL_FILTERS,+ Values.createArray()+ .add(new SubStringFilter(23).toValue().get())+ .add(new RegexFilter("[a-z|\\s]+(\\d+)%\"}", 1, 0).toValue().get()))+ ))mockThing = assetStorageService.merge(mockThing)@@ -354,7 +396,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,}and: "the deployment should have occurred in the correct order"- assert protocolMethodCalls.size() == 13+ assert protocolMethodCalls.size() == 16assert protocolMethodCalls[0] == "LINK_PROTOCOL"assert protocolMethodCalls[1] == "LINK_PROTOCOL"assert protocolMethodCalls[2] == "LINK_PROTOCOL"@@ -368,6 +410,9 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,assert protocolMethodCalls[10] == "LINK_ATTRIBUTE"assert protocolMethodCalls[11] == "LINK_ATTRIBUTE"assert protocolMethodCalls[12] == "LINK_ATTRIBUTE"+ assert protocolMethodCalls[13] == "LINK_ATTRIBUTE"+ assert protocolMethodCalls[14] == "LINK_ATTRIBUTE"+ assert protocolMethodCalls[15] == "LINK_ATTRIBUTE"expect: "the linked attributes values should have been updated by the protocol"conditions.eventually {@@ -432,7 +477,8 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,}when: "the protocol has finished processing the attribute write"- mockProtocol.responseReceived()+ def state = mockProtocol.protocolWriteAttributeEvents.last().getAttributeState()+ mockProtocol.updateReceived(state)then: "the target temp attributes value should be updated"conditions.eventually {@@ -440,6 +486,78 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,assert mockThing.getAttribute("tempTarget1").get().getValueAsNumber().orElse(0d) == 30d}+ when: "a sensor value is received that links to an attribute using a regex filter"+ state = new AttributeState(mockThing.id, "filterRegex", Values.create("s100 d56 g1212"))+ mockProtocol.updateReceived(state)++ then: "the linked attributes value should be updated with the filtered result"+ conditions.eventually {+ mockThing = assetStorageService.find(mockThing.getId(), true)+ assert mockThing.getAttribute("filterRegex").get().getValueAsNumber().orElse(0d) == 1212d+ }++ when: "the same attribute receives a sensor value that doesn't match the regex filter (match index invalid)"+ state = new AttributeState(mockThing.id, "filterRegex", Values.create("s100"))+ mockProtocol.updateReceived(state)++ then: "the linked attributes value should be updated to null"+ conditions.eventually {+ mockThing = assetStorageService.find(mockThing.getId(), true)+ assert !mockThing.getAttribute("filterRegex").get().getValueAsNumber().isPresent()+ }++ when: "the same attribute receives a sensor value that doesn't match the regex filter (no match)"+ def lastUpdate = mockThing.getAttribute("filterRegex").get().valueTimestamp.get()+ state = new AttributeState(mockThing.id, "filterRegex", Values.create("no match to be found!"))+ mockProtocol.updateReceived(state)++ then: "the linked attributes value should be updated to null"+ conditions.eventually {+ mockThing = assetStorageService.find(mockThing.getId(), true)+ assert mockThing.getAttribute("filterRegex").get().valueTimestamp.get() > lastUpdate+ assert !mockThing.getAttribute("filterRegex").get().getValueAsNumber().isPresent()+ }++ when: "a sensor value is received that links to an attribute using a substring filter"+ state = new AttributeState(mockThing.id, "filterSubstring", Values.create("Substring test value"))+ mockProtocol.updateReceived(state)++ then: "the linked attributes value should be updated with the filtered result"+ conditions.eventually {+ mockThing = assetStorageService.find(mockThing.getId(), true)+ assert mockThing.getAttribute("filterSubstring").get().getValueAsString().orElse(null) == "te"+ }++ when: "the same attribute receives a sensor value that doesn't match the substring filter"+ state = new AttributeState(mockThing.id, "filterSubstring", Values.create("Substring"))+ mockProtocol.updateReceived(state)++ then: "the linked attributes value should be updated to null"+ conditions.eventually {+ mockThing = assetStorageService.find(mockThing.getId(), true)+ assert !mockThing.getAttribute("filterSubstring").get().getValueAsString().isPresent()+ }++ when: "a sensor value is received that links to an attribute using a regex and substring filter"+ state = new AttributeState(mockThing.id, "filterRegexSubstring", Values.create('{"prop1":true,"prop2":"volume is at 90%"}'))+ mockProtocol.updateReceived(state)++ then: "the linked attributes value should be updated with the filtered result"+ conditions.eventually {+ mockThing = assetStorageService.find(mockThing.getId(), true)+ assert mockThing.getAttribute("filterRegexSubstring").get().getValueAsNumber().orElse(0d) == 90d+ }++ when: "the same attribute receives a sensor value that doesn't match the substring filter"+ state = new AttributeState(mockThing.id, "filterRegexSubstring", Values.create('"volume is at 90%"}'))+ mockProtocol.updateReceived(state)++ then: "the linked attributes value should be updated to null"+ conditions.eventually {+ mockThing = assetStorageService.find(mockThing.getId(), true)+ assert !mockThing.getAttribute("filterRegexSubstring").get().getValueAsNumber().isPresent()+ }+cleanup: "the client should be stopped"if (clientEventService != null) clientEventService.close()