Skip to content

armgit / core

Public Imported from GitHub
0

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

Protocol updates and testing

Rich Turnera8d2b8836ed5
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
index cc3439a97..ee0c509f0 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
@@ -19,7 +19,6 @@
*/
package org.openremote.agent3.protocol;
-import org.apache.camel.Predicate;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.openremote.container.Container;
@@ -27,11 +26,16 @@ import org.openremote.container.message.MessageBrokerContext;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.timer.TimerService;
+import org.openremote.model.AbstractValueHolder;
import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetMeta;
+import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.AttributeState;
-import org.openremote.model.util.Pair;
+import org.openremote.model.attribute.MetaItem;
+import org.openremote.model.util.Triplet;
+import org.openremote.model.value.Values;
import java.util.Collection;
import java.util.HashMap;
@@ -42,18 +46,8 @@ import java.util.logging.Logger;
public abstract class AbstractProtocol implements Protocol {
private static final Logger LOG = Logger.getLogger(AbstractProtocol.class.getName());
-
- static Predicate isAttributeStateForAny(Collection<AttributeRef> attributeRefs) {
- return exchange -> {
- if (!(exchange.getIn().getBody() instanceof AttributeEvent))
- return false;
- AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
- return attributeRefs.contains(event.getAttributeRef());
- };
- }
-
- final protected Map<AttributeRef, AssetAttribute> linkedAttributes = new HashMap<>();
- final protected Map<AttributeRef, Pair<AssetAttribute, Consumer<DeploymentStatus>>> linkedProtocolConfigurations = new HashMap<>();
+ protected final Map<AttributeRef, AssetAttribute> linkedAttributes = new HashMap<>();
+ protected final Map<AttributeRef, Triplet<AssetAttribute, Consumer<DeploymentStatus>, DeploymentStatus>> linkedProtocolConfigurations = new HashMap<>();
protected MessageBrokerContext messageBrokerContext;
protected ProducerTemplate producerTemplate;
protected TimerService timerService;
@@ -90,7 +84,31 @@ public abstract class AbstractProtocol implements Protocol {
if (attribute == null) {
LOG.warning("Attribute doesn't exist on this protocol: " + event.getAttributeRef());
} else {
- processLinkedAttributeWrite(event, attribute);
+ AssetAttribute protocolConfiguration = getLinkedProtocolConfiguration(attribute);
+
+ // If attribute is linked to protocol's enabled status handle here
+ boolean isLinkedToEnabledStatus = attribute
+ .getMetaItem(AssetMeta.PROTOCOL_PROPERTY)
+ .flatMap(AbstractValueHolder::getValueAsString)
+ .map(property -> property.equals("ENABLED"))
+ .orElse(false);
+
+ if (isLinkedToEnabledStatus) {
+ LOG.fine("Attribute is linked to protocol's enabled property so handling write here");
+
+ // check event value is a boolean
+ boolean enabled = Values.getBoolean(event.getValue()
+ .orElse(null))
+ .orElseThrow(() -> new IllegalStateException("Writing to protocol configuration ENABLED property requires a boolean value"));
+
+ if (enabled == protocolConfiguration.isEnabled()) {
+ LOG.finer("Protocol configuration enabled status is already: " + enabled);
+ } else {
+ updateLinkedProtocolConfiguration(protocolConfiguration, new MetaItem(AssetMeta.ENABLED, Values.create(enabled)));
+ }
+ } else {
+ processLinkedAttributeWrite(event, protocolConfiguration);
+ }
}
}
}
@@ -115,7 +133,7 @@ public abstract class AbstractProtocol implements Protocol {
LOG.finer("Linking protocol configuration to protocol '" + getProtocolName() + "': " + protocolConfiguration);
linkedProtocolConfigurations.put(
protocolConfiguration.getReferenceOrThrow(),
- new Pair<>(protocolConfiguration, deploymentStatusConsumer)
+ new Triplet<>(protocolConfiguration, deploymentStatusConsumer, DeploymentStatus.LINKING)
);
doLinkProtocolConfiguration(protocolConfiguration);
}
@@ -135,8 +153,23 @@ 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);
+
+ // If attribute is linked to protocol configuration enabled status handle here
+ boolean isLinkedToEnabledStatus = attribute
+ .getMetaItem(AssetMeta.PROTOCOL_PROPERTY)
+ .flatMap(AbstractValueHolder::getValueAsString)
+ .map(property -> property.equals("ENABLED"))
+ .orElse(false);
+
+ AttributeRef attributeRef = attribute.getReferenceOrThrow();
+ linkedAttributes.put(attributeRef, attribute);
+
+ if (isLinkedToEnabledStatus) {
+ LOG.fine("Attribute is linked to protocol's enabled property so handling here");
+ updateLinkedAttribute(new AttributeState(attributeRef, Values.create(protocolConfiguration.isEnabled())));
+ } else {
+ doLinkAttribute(attribute, protocolConfiguration);
+ }
});
}
}
@@ -146,7 +179,18 @@ public abstract class AbstractProtocol implements Protocol {
synchronized (linkedAttributes) {
attributes.forEach(attribute -> {
LOG.fine("Unlinking attribute on '" + getProtocolName() + "': " + attribute);
- doUnlinkAttribute(attribute, protocolConfiguration);
+
+ // If attribute is linked to protocol's enabled status handle here
+ boolean isLinkedToEnabledStatus = attribute
+ .getMetaItem(AssetMeta.PROTOCOL_PROPERTY)
+ .flatMap(AbstractValueHolder::getValueAsString)
+ .map(property -> property.equals("ENABLED"))
+ .orElse(false);
+
+ if (!isLinkedToEnabledStatus) {
+ // Only pass to the protocol if it is not linked to enabled status
+ doUnlinkAttribute(attribute, protocolConfiguration);
+ }
linkedAttributes.remove(attribute.getReferenceOrThrow());
});
}
@@ -162,20 +206,19 @@ public abstract class AbstractProtocol implements Protocol {
}
/**
- * Get the deployment status consumer for a given protocol configuration
+ * Get the protocol configuration that this attribute links to.
*/
- protected Consumer<DeploymentStatus> getDeploymentStatusConsumer(AssetAttribute protocolConfiguration) {
- return getDeploymentStatusConsumer(protocolConfiguration.getReferenceOrThrow());
+ protected AssetAttribute getLinkedProtocolConfiguration(AssetAttribute attribute) {
+ AttributeRef protocolConfigRef = AgentLink.getAgentLink(attribute).orElseThrow(() -> new IllegalStateException("Attribute is not linked to a protocol"));
+ return getLinkedProtocolConfiguration(protocolConfigRef);
}
- /**
- * Get the deployment status consumer for a given protocol configurations attribute ref
- */
- protected Consumer<DeploymentStatus> getDeploymentStatusConsumer(AttributeRef protocolRef) {
+ protected AssetAttribute getLinkedProtocolConfiguration(AttributeRef protocolConfigurationRef) {
synchronized (linkedProtocolConfigurations) {
- return linkedProtocolConfigurations.containsKey(protocolRef)
- ? linkedProtocolConfigurations.get(protocolRef).value
- : null;
+ Triplet<AssetAttribute, Consumer<DeploymentStatus>, DeploymentStatus> assetAttributeConsumerInfo = linkedProtocolConfigurations.get(protocolConfigurationRef);
+ // Don't bother with null check if someone calls here with an attribute not linked to this protocol
+ // then they're doing something wrong so fail hard and fast
+ return assetAttributeConsumerInfo.getValue1();
}
}
@@ -184,16 +227,14 @@ public abstract class AbstractProtocol implements Protocol {
* using the current system time as the timestamp.
*/
protected void sendAttributeEvent(AttributeState state) {
- AttributeEvent event = new AttributeEvent(state, timerService.getCurrentTimeMillis());
- LOG.info("Sending attribute event from protocol '" + getProtocolName() + "': " + event);
- assetService.sendAttributeEvent(event);
+ sendAttributeEvent(new AttributeEvent(state, timerService.getCurrentTimeMillis()));
}
/**
* Send an arbitrary {@link AttributeEvent} through the processing chain.
*/
protected void sendAttributeEvent(AttributeEvent attributeEvent) {
- LOG.info("Sending attribute event: " + attributeEvent);
+ LOG.info("Sending attribute event from protocol '" + getProtocolName() + "': " + attributeEvent);
assetService.sendAttributeEvent(attributeEvent);
}
@@ -213,6 +254,17 @@ public abstract class AbstractProtocol implements Protocol {
updateLinkedAttribute(state, timerService.getCurrentTimeMillis());
}
+ /**
+ * Update a linked protocol configuration; allows protocols to reconfigure their
+ * own protocol configurations to persist changing data e.g. authorization tokens.
+ */
+ protected void updateLinkedProtocolConfiguration(AssetAttribute protocolConfiguration, MetaItem newMetaItem) {
+ // Clone the protocol configuration rather than modify this one
+ AssetAttribute modifiedProtocolConfiguration = protocolConfiguration.deepCopy();
+ MetaItem.replaceMetaByName(modifiedProtocolConfiguration.getMeta(), AssetMeta.ENABLED, newMetaItem);
+ assetService.updateProtocolConfiguration(modifiedProtocolConfiguration);
+ }
+
/**
* Update the deployment status of a protocol configuration by its attribute ref
*/
@@ -220,13 +272,24 @@ public abstract class AbstractProtocol implements Protocol {
synchronized (linkedProtocolConfigurations) {
linkedProtocolConfigurations.computeIfPresent(protocolRef,
(ref, pair) -> {
- pair.value.accept(deploymentStatus);
+ pair.getValue2().accept(deploymentStatus);
+ pair.value3 = deploymentStatus;
return pair;
}
);
}
}
+ /**
+ * Gets the current deployment status of a protocol configuration.
+ */
+ protected DeploymentStatus getDeploymentStatus(AssetAttribute protocolConfiguration) {
+ synchronized (linkedProtocolConfigurations) {
+ Triplet<AssetAttribute, Consumer<DeploymentStatus>, DeploymentStatus> assetAttributeConsumerInfo = linkedProtocolConfigurations.get(protocolConfiguration.getReferenceOrThrow());
+ return assetAttributeConsumerInfo.getValue3();
+ }
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/AbstractTriggerHandler.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/AbstractTriggerHandler.java
index ace15024f..4ae227232 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/trigger/AbstractTriggerHandler.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/AbstractTriggerHandler.java
@@ -37,8 +37,6 @@ public abstract class AbstractTriggerHandler {
protected abstract void registerTrigger(AttributeRef triggerRef, Value value, boolean isEnabled);
- protected abstract void updateTrigger(AttributeRef triggerRef, Value value, boolean isEnabled);
-
protected abstract void unregisterTrigger(AttributeRef triggerRef);
/**
@@ -52,8 +50,6 @@ public abstract class AbstractTriggerHandler {
*/
protected abstract void registerAttribute(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName);
- protected abstract void updateAttribute(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName);
-
protected abstract void unregisterAttribute(AttributeRef attributeRef, AttributeRef triggerRef);
/**
@@ -62,15 +58,11 @@ public abstract class AbstractTriggerHandler {
* The {@link AbstractTriggerHandler} implementation should override this method
* to handle the request based on the propertyName and the {@link AttributeEvent}.
*
- * {@link TriggerProtocol#TRIGGER_PROPERTY_ENABLED} writes are handled here and are
- * applicable for all trigger types (implementations can override but should still
- * call this super method).
- *
* If the handler wishes to alter the trigger's value as a result of the request
* (e.g. request was to adjust the time of a TimeTrigger) then the handler
* should call {@link #updateTriggerValue(AttributeState)} with the new desired value.
*/
- protected abstract void processAttributeWrite(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName, AttributeEvent event);
+ protected abstract void processAttributeWrite(AssetAttribute attribute, AssetAttribute protocolConfiguration, String propertyName, AttributeEvent event);
/**
* Called by the protocol init
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerConfiguration.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerConfiguration.java
index 8047cce2b..23dddc054 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerConfiguration.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerConfiguration.java
@@ -21,6 +21,7 @@ package org.openremote.agent3.protocol.trigger;
import org.openremote.model.AbstractValueHolder;
import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetMeta;
import org.openremote.model.attribute.AttributeState;
import org.openremote.model.value.Value;
import org.openremote.model.value.Values;
@@ -164,7 +165,7 @@ final public class TriggerConfiguration {
public static Optional<String> getTriggerProperty(AssetAttribute attribute) {
return attribute == null ? Optional.empty() : attribute
- .getMetaItem(META_TRIGGER_PROPERTY)
+ .getMetaItem(AssetMeta.PROTOCOL_PROPERTY)
.flatMap(AbstractValueHolder::getValueAsString);
}
}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerProtocol.java
index 2cd77a9e9..46d27bef7 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerProtocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerProtocol.java
@@ -25,8 +25,8 @@ import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.AttributeState;
+import org.openremote.model.attribute.MetaItem;
import org.openremote.model.value.Value;
-import org.openremote.model.value.Values;
import java.util.HashMap;
import java.util.Map;
@@ -36,8 +36,6 @@ import java.util.logging.Logger;
import static org.openremote.agent3.protocol.trigger.TriggerConfiguration.*;
import static org.openremote.model.Constants.ASSET_META_NAMESPACE;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
-import static org.openremote.model.asset.AssetMeta.ENABLED;
-import static org.openremote.model.asset.agent.AgentLink.getAgentLink;
/**
* This protocol can be used to trigger {@link AttributeEvent} using a trigger type:
@@ -52,10 +50,11 @@ import static org.openremote.model.asset.agent.AgentLink.getAgentLink;
* {@link AssetAttribute}s can link to time triggers to read/write the trigger time and/or enable/disable
* the trigger.
* <p>
- * The {@link #META_TRIGGER_PROPERTY} meta should be used on linked attributes to indicate what property
- * of the trigger the attribute should read/write. The content of the meta should be a string that is
- * specific to the trigger type handler. The only globally recognised value is {@link #TRIGGER_PROPERTY_ENABLED}
- * which reads/writes the trigger's {@link org.openremote.model.asset.AssetMeta#ENABLED} meta item.
+ * The {@link org.openremote.model.asset.AssetMeta#PROTOCOL_PROPERTY} meta should be used on linked attributes to
+ * indicate what property of the trigger the attribute should read/write. The content of the meta should be a string
+ * that is specific to the trigger type handler. The only globally recognised value is "ENABLED"
+ * which reads/writes the trigger's {@link org.openremote.model.asset.AssetMeta#ENABLED} meta item and is handled by
+ * the {@link AbstractProtocol} super class.
*/
public class TriggerProtocol extends AbstractProtocol {
@@ -63,8 +62,6 @@ public class TriggerProtocol extends AbstractProtocol {
public static final String META_TRIGGER_VALUE = ASSET_META_NAMESPACE + ":triggerValue";
public static final String META_TRIGGER_TYPE = ASSET_META_NAMESPACE + ":triggerType";
public static final String META_TRIGGER_ACTION = ASSET_META_NAMESPACE + ":triggerAction";
- public static final String META_TRIGGER_PROPERTY = ASSET_META_NAMESPACE + ":triggerProperty";
- public static final String TRIGGER_PROPERTY_ENABLED = "ENABLED";
private static final Logger LOG = Logger.getLogger(TriggerProtocol.class.getName());
protected final Map<AttributeRef, AssetAttribute> protocolConfigMap = new HashMap<>();
protected final Map<AttributeRef, AbstractTriggerHandler> attributeTriggerHandlerMap = new HashMap<>();
@@ -152,28 +149,14 @@ public class TriggerProtocol extends AbstractProtocol {
// if the attributes' META_TRIGGER_PROPERTY value is TRIGGER_PROPERTY_ENABLED
// then handle the request here, otherwise delegate to the trigger handler
AssetAttribute attribute = getLinkedAttribute(event.getAttributeRef());
- AttributeRef triggerRef = getAgentLink(attribute)
- .orElseThrow(() -> new IllegalStateException("Trigger configuration link cannot be found on attribute: " + event.getAttributeRef()));
TriggerConfiguration.getTriggerProperty(attribute)
.ifPresent(propertyName -> {
- if (TRIGGER_PROPERTY_ENABLED.equals(propertyName)) {
- // Check that event contains a boolean
- event.getValue()
- .flatMap(Values::getBoolean)
- .ifPresent(enabled -> {
- // We update the trigger configuration and wait for it to come back through the processing
- // chain as an update to the protocol configuration in the agent service
- updateTriggerMeta(new AttributeState(triggerRef, Values.create(enabled)), ENABLED.getUrn());
- }
- );
- } else {
- synchronized (attributeTriggerHandlerMap) {
- AbstractTriggerHandler handler = attributeTriggerHandlerMap.get(event.getAttributeRef());
- if (handler != null) {
- LOG.info("Passing attribute write request to trigger handler '" + handler.getName() + "'");
- handler.processAttributeWrite(event.getAttributeRef(), triggerRef, propertyName, event);
- }
+ synchronized (attributeTriggerHandlerMap) {
+ AbstractTriggerHandler handler = attributeTriggerHandlerMap.get(event.getAttributeRef());
+ if (handler != null) {
+ LOG.info("Passing attribute write request to trigger handler '" + handler.getName() + "'");
+ handler.processAttributeWrite(attribute, protocolConfiguration, propertyName, event);
}
}
});
@@ -206,41 +189,11 @@ public class TriggerProtocol extends AbstractProtocol {
TriggerConfiguration.getTriggerProperty(attribute)
.ifPresent(propertyName -> {
AttributeRef attributeRef = attribute.getReferenceOrThrow();
-
- if (TRIGGER_PROPERTY_ENABLED.equals(propertyName)) {
- AttributeState state = new AttributeState(attributeRef, Values.create(triggerConfiguration.isEnabled()));
- // Push current value of enabled status into the attribute
- LOG.info("Updating attribute value with trigger enabled status: " + state);
- updateLinkedAttribute(state);
- } else {
- LOG.info("Registering attribute '" + attributeRef + "' on trigger handler '" + handler.getName() + "'");
- synchronized (attributeTriggerHandlerMap) {
- attributeTriggerHandlerMap.put(attribute.getReferenceOrThrow(), handler);
- }
- handler.registerAttribute(attributeRef, triggerConfiguration.getReferenceOrThrow(), propertyName);
- }
- });
- }
-
- protected void updateAttributeWithTriggerHandler(AssetAttribute attribute, AssetAttribute triggerConfiguration, AbstractTriggerHandler handler) {
- LOG.fine("Request to update attribute with trigger handler");
-
- TriggerConfiguration.getTriggerProperty(attribute)
- .ifPresent(propertyName -> {
- AttributeRef attributeRef = attribute.getReferenceOrThrow();
-
- if (TRIGGER_PROPERTY_ENABLED.equals(propertyName)) {
- // META_TRIGGER_PROPERTY has changed must not have been using TRIGGER_ENABLED value before
- unRegisterAttributeWithTriggerHandler(attributeRef, triggerConfiguration.getReferenceOrThrow(), handler);
-
- LOG.info("Registering attribute for trigger enabled status: " + attributeRef);
-
- // Push current value of enabled status into the attribute
- updateLinkedAttribute(new AttributeState(attributeRef, Values.create(triggerConfiguration.isEnabled())));
- } else {
- LOG.info("Updating attribute '" + attributeRef + "' on trigger handler '" + handler.getName() + "'");
- handler.updateAttribute(attributeRef, triggerConfiguration.getReferenceOrThrow(), propertyName);
+ LOG.info("Registering attribute '" + attributeRef + "' on trigger handler '" + handler.getName() + "'");
+ synchronized (attributeTriggerHandlerMap) {
+ attributeTriggerHandlerMap.put(attribute.getReferenceOrThrow(), handler);
}
+ handler.registerAttribute(attributeRef, triggerConfiguration.getReferenceOrThrow(), propertyName);
});
}
@@ -282,26 +235,11 @@ public class TriggerProtocol extends AbstractProtocol {
* Update the trigger's {@link #META_TRIGGER_VALUE}
*/
void updateTriggerValue(AttributeState state) {
- updateTriggerMeta(state, META_TRIGGER_VALUE);
- }
-
- /**
- * Updates the trigger configuration on the owning agent
- */
- // TODO: Implement trigger meta update
- protected void updateTriggerMeta(AttributeState state, String metaName) {
- LOG.info("Updating trigger meta '" + metaName + "': " + state.getAttributeRef());
+ LOG.fine("Updating the trigger value: " + state);
- synchronized (protocolConfigMap) {
- Optional.ofNullable(protocolConfigMap.get(state.getAttributeRef()))
- .ifPresent(triggerConfiguration ->
- LOG.info("Updating trigger configuration")
- // Set the trigger Configuration meta and update the agent
- //replaceMetaByName(triggerConfiguration, metaName, state.getValue());
- //Asset agent = assetStorageService.get(triggerConfiguration.getAssetId(), true);
- //agent.replaceAttribute(triggerConfiguration);
- //assetStorageService.merge(agent);
- );
- }
+ updateLinkedProtocolConfiguration(
+ getLinkedProtocolConfiguration(state.getAttributeRef()),
+ new MetaItem(META_TRIGGER_VALUE, state.getCurrentValue().orElse(null))
+ );
}
}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/attribute/AttributeTriggerHandler.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/attribute/AttributeTriggerHandler.java
index de03a7a98..83e3fcf3f 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/trigger/attribute/AttributeTriggerHandler.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/attribute/AttributeTriggerHandler.java
@@ -20,6 +20,7 @@
package org.openremote.agent3.protocol.trigger.attribute;
import org.openremote.agent3.protocol.trigger.AbstractTriggerHandler;
+import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.value.Value;
@@ -43,11 +44,6 @@ public class AttributeTriggerHandler extends AbstractTriggerHandler {
}
- @Override
- protected void updateTrigger(AttributeRef triggerRef, Value value, boolean isEnabled) {
-
- }
-
@Override
protected void unregisterTrigger(AttributeRef triggerRef) {
@@ -58,10 +54,6 @@ public class AttributeTriggerHandler extends AbstractTriggerHandler {
}
- @Override
- protected void updateAttribute(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName) {
-
- }
@Override
protected void unregisterAttribute(AttributeRef attributeRef, AttributeRef triggerRef) {
@@ -69,7 +61,7 @@ public class AttributeTriggerHandler extends AbstractTriggerHandler {
}
@Override
- protected void processAttributeWrite(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName, AttributeEvent event) {
- // This trigger handler doesn't support updates for now
+ protected void processAttributeWrite(AssetAttribute attribute, AssetAttribute protocolConfiguration, String propertyName, AttributeEvent event) {
+
}
}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerHandler.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerHandler.java
index 7153086ba..d85ac374c 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerHandler.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerHandler.java
@@ -20,6 +20,7 @@
package org.openremote.agent3.protocol.trigger.time;
import org.openremote.agent3.protocol.trigger.AbstractTriggerHandler;
+import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.AttributeState;
@@ -83,12 +84,6 @@ public class TimeTriggerHandler extends AbstractTriggerHandler {
}
}
- @Override
- protected void updateTrigger(AttributeRef triggerRef, Value value, boolean isEnabled) {
- unregisterTrigger(triggerRef);
- registerTrigger(triggerRef, value, isEnabled);
- }
-
@Override
protected void unregisterTrigger(AttributeRef triggerRef) {
getCronScheduler().removeJob(getTriggerId(triggerRef));
@@ -120,21 +115,16 @@ public class TimeTriggerHandler extends AbstractTriggerHandler {
}
}
- @Override
- protected void updateAttribute(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName) {
- registerAttribute(attributeRef, triggerRef, propertyName);
- }
-
@Override
protected void unregisterAttribute(AttributeRef attributeRef, AttributeRef triggerRef) {
}
@Override
- protected void processAttributeWrite(AttributeRef attributeRef, AttributeRef triggerRef, String propertyName, AttributeEvent event) {
+ protected void processAttributeWrite(AssetAttribute attribute, AssetAttribute protocolConfiguration, String propertyName, AttributeEvent event) {
TimeTriggerProperty triggerProperty = TimeTriggerProperty.fromString(propertyName);
if (triggerProperty == null) {
- LOG.warning("Attribute is using an invalid trigger property name '" + propertyName + "': " + attributeRef);
+ LOG.warning("Attribute is using an invalid trigger property name '" + propertyName + "': " + attribute.getReferenceOrThrow());
return;
}
@@ -153,10 +143,10 @@ public class TimeTriggerHandler extends AbstractTriggerHandler {
case CRON_EXPRESSION:
// Allow writing invalid cron expressions; mean that the trigger will stop working
// but that is handled gracefully
- updateTriggerValue(new AttributeState(triggerRef, Values.create(value)));
+ updateTriggerValue(new AttributeState(protocolConfiguration.getReferenceOrThrow(), Values.create(value)));
break;
case TIME:
- CronExpressionParser parser = getCronExpressionParser(triggerRef);
+ CronExpressionParser parser = getCronExpressionParser(protocolConfiguration.getReferenceOrThrow());
if (parser == null) {
LOG.info("Ignoring trigger update because current cron expression is invalid");
return;
@@ -176,7 +166,7 @@ public class TimeTriggerHandler extends AbstractTriggerHandler {
}
parser.setTime(hours, minutes, seconds);
- updateTriggerValue(new AttributeState(triggerRef, Values.create(parser.buildCronExpression())));
+ updateTriggerValue(new AttributeState(protocolConfiguration.getReferenceOrThrow(), Values.create(parser.buildCronExpression())));
break;
default:
throw new NotSupportedException("Unsupported trigger property");
diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
index 2af715745..6ec363676 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
@@ -453,12 +453,12 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
Protocol protocol = getProtocol(protocolConfiguration);
if (protocol == null) {
- LOG.severe("Cannot link protocol attributes as protocol is null");
+ LOG.severe("Cannot unlink protocol attributes as protocol is null");
return;
}
try {
- LOG.finest("Unlinking protocol attributes form: " + protocol.getProtocolName());
+ LOG.finest("Unlinking protocol attributes from: " + protocol.getProtocolName());
protocol.unlinkAttributes(attributes, protocolConfiguration);
} catch (Exception ex) {
LOG.log(Level.SEVERE, "Ignoring error on unlinking attributes from protocol: " + protocol.getProtocolName(), ex);
diff --git a/manager/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy b/manager/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
index 3c5ce7d13..eb1e305b0 100644
--- a/manager/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
@@ -22,6 +22,7 @@ package org.openremote.test.protocol
import org.openremote.agent3.protocol.AbstractProtocol
import org.openremote.agent3.protocol.Protocol
import org.openremote.manager.server.agent.AgentService
+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
@@ -29,10 +30,7 @@ import org.openremote.model.asset.AssetAttribute
import org.openremote.model.asset.AssetMeta
import org.openremote.model.asset.AssetType
import org.openremote.model.asset.agent.ProtocolConfiguration
-import org.openremote.model.attribute.AttributeEvent
-import org.openremote.model.attribute.AttributeRef
-import org.openremote.model.attribute.AttributeType
-import org.openremote.model.attribute.MetaItem
+import org.openremote.model.attribute.*
import org.openremote.model.value.Values
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
@@ -63,14 +61,18 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
protocolLinkedAttributes['mockConfig2'] = []
protocolLinkedAttributes['mockConfig3'] = []
protocolLinkedAttributes['mockConfig4'] = []
- List<AttributeEvent> protocolWriteAttributes = []
+ List<AttributeEvent> protocolWriteAttributeEvents = []
List<String> protocolMethodCalls = []
def mockProtocol = new AbstractProtocol() {
protected void responseReceived() {
// 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(protocolWriteAttributes.last().getAttributeState())
+ updateLinkedAttribute(protocolWriteAttributeEvents.last().getAttributeState())
+ }
+
+ protected void updateAttribute(AttributeState state) {
+ sendAttributeEvent(state)
}
@Override
@@ -103,6 +105,18 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
throw new IllegalStateException("Attribute is not valid");
}
protocolLinkedAttributes[protocolConfiguration.getName().orElse("")] << attribute
+
+ def deploymentStatus = getDeploymentStatus(protocolConfiguration);
+ if (deploymentStatus == Protocol.DeploymentStatus.LINKED_ENABLED) {
+ String attributeName = attribute.getName().orElse("");
+ if (attributeName.startsWith("lightToggle")) {
+ // Set all lights to on
+ updateLinkedAttribute(new AttributeState(attribute.getReferenceOrThrow(), Values.create(true)))
+ } else if (attributeName.startsWith("tempTarget")) {
+ // Set target temps to 25.5
+ updateLinkedAttribute(new AttributeState(attribute.getReferenceOrThrow(), Values.create(25.5)))
+ }
+ }
}
@Override
@@ -119,7 +133,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
.any {it.getReferenceOrThrow().equals(event.attributeRef)}) {
throw new IllegalStateException("Attribute is not linked")
}
- protocolWriteAttributes.add(event)
+ protocolWriteAttributeEvents.add(event)
}
@Override
@@ -133,6 +147,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
def container = startContainerMinimal(defaultConfig(serverPort), defaultServices(mockProtocol))
def assetStorageService = container.getService(AssetStorageService.class)
def agentService = container.getService(AgentService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
when: "a mock agent that uses the mock protocol is created with a valid protocol configuration"
def mockAgent = new ServerAsset()
@@ -177,7 +192,7 @@ 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("light1Toggle", AttributeType.BOOLEAN, Values.create(false))
+ new AssetAttribute("lightToggle1", AttributeType.BOOLEAN)
.setMeta(
new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META"),
new MetaItem(
@@ -185,7 +200,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()
)
),
- new AssetAttribute("temp1Target", AttributeType.BOOLEAN)
+ new AssetAttribute("tempTarget1", AttributeType.DECIMAL)
.setMeta(
new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META"),
new MetaItem(
@@ -193,14 +208,14 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()
)
),
- new AssetAttribute("invalid1Toggle", AttributeType.BOOLEAN, Values.create(false))
+ new AssetAttribute("invalidToggle1", AttributeType.BOOLEAN)
.setMeta(
new MetaItem(
AssetMeta.AGENT_LINK,
new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()
)
),
- new AssetAttribute("light2Toggle", AttributeType.BOOLEAN, Values.create(false))
+ new AssetAttribute("lightToggle2", AttributeType.BOOLEAN)
.setMeta(
new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META"),
new MetaItem(
@@ -208,7 +223,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
new AttributeRef(mockAgent.getId(), "mockConfig2").toArrayValue()
)
),
- new AssetAttribute("temp2Target", AttributeType.BOOLEAN)
+ new AssetAttribute("tempTarget2", AttributeType.DECIMAL)
.setMeta(
new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META"),
new MetaItem(
@@ -216,7 +231,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
new AttributeRef(mockAgent.getId(), "mockConfig2").toArrayValue()
)
),
- new AssetAttribute("light3Toggle", AttributeType.BOOLEAN, Values.create(false))
+ new AssetAttribute("lightToggle3", AttributeType.BOOLEAN)
.setMeta(
new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META"),
new MetaItem(
@@ -224,7 +239,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
new AttributeRef(mockAgent.getId(), "mockConfig3").toArrayValue()
)
),
- new AssetAttribute("temp3Target", AttributeType.BOOLEAN)
+ new AssetAttribute("tempTarget3", AttributeType.DECIMAL)
.setMeta(
new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META"),
new MetaItem(
@@ -232,7 +247,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
new AttributeRef(mockAgent.getId(), "mockConfig3").toArrayValue()
)
),
- new AssetAttribute("light4Toggle", AttributeType.BOOLEAN, Values.create(false))
+ new AssetAttribute("lightToggle4", AttributeType.BOOLEAN)
.setMeta(
new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META"),
new MetaItem(
@@ -240,7 +255,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
new AttributeRef(mockAgent.getId(), "mockConfig4").toArrayValue()
)
),
- new AssetAttribute("temp4Target", AttributeType.BOOLEAN)
+ new AssetAttribute("tempTarget4", AttributeType.DECIMAL)
.setMeta(
new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META"),
new MetaItem(
@@ -248,7 +263,18 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
new AttributeRef(mockAgent.getId(), "mockConfig4").toArrayValue()
)
),
- new AssetAttribute("invalid5Toggle", AttributeType.BOOLEAN, Values.create(false))
+ // The below attribute is handled by abstract protocol and won't reach the mock
+ // protocol link/unlink attribute method
+ new AssetAttribute("protocolEnabled", AttributeType.BOOLEAN)
+ .setMeta(
+ new MetaItem("MOCK_ATTRIBUTE_REQUIRED_META"),
+ new MetaItem(AssetMeta.PROTOCOL_PROPERTY, Values.create("ENABLED")),
+ new MetaItem(
+ AssetMeta.AGENT_LINK,
+ new AttributeRef(mockAgent.getId(), "mockConfig4").toArrayValue()
+ )
+ ),
+ new AssetAttribute("invalidToggle5", AttributeType.BOOLEAN, Values.create(false))
.setMeta(
new MetaItem(
AssetMeta.AGENT_LINK,
@@ -289,9 +315,25 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
assert protocolMethodCalls[11] == "LINK_ATTRIBUTE"
assert protocolMethodCalls[12] == "LINK_ATTRIBUTE"
+ when: "the mock thing is retrieved from the DB"
+ mockThing = assetStorageService.find(mockThing.getId(), true)
+
+ then: "the linked attributes values should have been updated by the protocol"
+ // Check all valid linked attributes have the new values
+ assert mockThing.getAttribute("lightToggle1").get().getValueAsBoolean().orElse(false)
+ assert mockThing.getAttribute("tempTarget1").get().getValueAsNumber().orElse(0d) == 25.5d
+ // Check disabled linked attributes don't have the new values
+ assert !mockThing.getAttribute("lightToggle4").get().getValue().isPresent()
+ assert !mockThing.getAttribute("tempTarget4").get().getValue().isPresent()
+ // Check invalid attributes don't have the new values
+ assert !mockThing.getAttribute("lightToggle2").get().getValue().isPresent()
+ assert !mockThing.getAttribute("tempTarget2").get().getValue().isPresent()
+ assert !mockThing.getAttribute("lightToggle3").get().getValue().isPresent()
+ assert !mockThing.getAttribute("tempTarget3").get().getValue().isPresent()
+
when: "a linked attribute is removed"
protocolMethodCalls.clear()
- mockThing.removeAttribute("temp3Target")
+ mockThing.removeAttribute("tempTarget3")
mockThing = assetStorageService.merge(mockThing)
then: "the protocol should not be unlinked"
@@ -303,18 +345,72 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
when: "a protocol configuration is removed"
protocolMethodCalls.clear()
- mockAgent.removeAttribute("mockConfig4")
+ mockAgent.removeAttribute("mockConfig3")
mockAgent = assetStorageService.merge(mockAgent)
then: "the attributes should be unlinked then the protocol configuration"
conditions.eventually {
- assert protocolLinkedAttributes["mockConfig4"].size() == 0
- assert protocolMethodCalls.size() == 3
+ assert protocolLinkedAttributes["mockConfig3"].size() == 0
+ assert protocolMethodCalls.size() == 2
+ assert protocolMethodCalls[0] == "UNLINK_ATTRIBUTE"
+ assert protocolMethodCalls[1] == "UNLINK_PROTOCOL"
+ }
+
+ when: "a disabled protocol configuration is enabled"
+ protocolMethodCalls.clear()
+ assetProcessingService.sendAttributeEvent(new AttributeEvent(mockThing.getId(),"protocolEnabled", Values.create(true)))
+
+ then: "the protocol configuration should be relinked"
+ conditions.eventually {
+ assert protocolLinkedAttributes['mockConfig4'].size() == 2
+ assert protocolMethodCalls.size() == 6
assert protocolMethodCalls[0] == "UNLINK_ATTRIBUTE"
assert protocolMethodCalls[1] == "UNLINK_ATTRIBUTE"
assert protocolMethodCalls[2] == "UNLINK_PROTOCOL"
+ assert protocolMethodCalls[3] == "LINK_PROTOCOL"
+ assert protocolMethodCalls[4] == "LINK_ATTRIBUTE"
+ assert protocolMethodCalls[5] == "LINK_ATTRIBUTE"
+ }
+
+ and: "the deployment status of the relinked protocol configuration should now be LINKED_ENABLED"
+ def config4 = protocolLinkedConfigurations.find { it.getName().orElse("").equals("mockConfig4") }
+ assert config4 != null
+ assert agentService.getProtocolDeploymentStatus(config4.getReferenceOrThrow()) == Protocol.DeploymentStatus.LINKED_ENABLED
+
+ when: "the mock thing is retrieved from the DB"
+ mockThing = assetStorageService.find(mockThing.getId(), true)
+
+ then: "the linked attribute values should have been updated by the protocol"
+ assert mockThing.getAttribute("lightToggle4").get().getValueAsBoolean().orElse(false)
+ assert mockThing.getAttribute("tempTarget4").get().getValueAsNumber().orElse(0d) == 25.5d
+
+ when: "the mock protocol tries to update the plain attribute"
+ mockProtocol.updateAttribute(new AttributeState(mockThing.getId(),"plainAttribute", Values.create("UPDATE")))
+
+ then: "the plain attributes value should be updated"
+ conditions.eventually {
+ mockThing = assetStorageService.find(mockThing.getId(), true)
+ assert mockThing.getAttribute("plainAttribute").get().getValueAsString().orElse("") == "UPDATE"
+ }
+
+ when: "a target temp linked attribute value is updated it should reach the protocol"
+ assetProcessingService.sendAttributeEvent(new AttributeEvent(mockThing.getId(), "tempTarget1", Values.create(30d)))
+
+ then: "the update should reach the protocol as an attribute write request"
+ conditions.eventually {
+ protocolWriteAttributeEvents.size() == 1
+ protocolWriteAttributeEvents[0].attributeName == "tempTarget1"
+ protocolWriteAttributeEvents[0].attributeRef.entityId == mockThing.getId()
+ Values.getNumber(protocolWriteAttributeEvents[0].value.orElse(null)).orElse(0d) == 30d
}
- // TODO: Extend this test
+ when: "the protocol has finished processing the attribute write"
+ mockProtocol.responseReceived()
+
+ then: "the target temp attributes value should be updated"
+ conditions.eventually {
+ mockThing = assetStorageService.find(mockThing.getId(), true)
+ assert mockThing.getAttribute("tempTarget1").get().getValueAsNumber().orElse(0d) == 30d
+ }
}
}
\ No newline at end of file
diff --git a/manager/test/src/test/groovy/org/openremote/test/protocol/MacroProtocolTest.groovy b/manager/test/src/test/groovy/org/openremote/test/protocol/MacroProtocolTest.groovy
index adc7088f7..e6da2e1b4 100644
--- a/manager/test/src/test/groovy/org/openremote/test/protocol/MacroProtocolTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/protocol/MacroProtocolTest.groovy
@@ -14,7 +14,7 @@ class MacroProtocolTest extends Specification implements ManagerContainerTrait {
def "Check macro agent and device asset deployment"() {
given: "expected conditions"
- def conditions = new PollingConditions(timeout: 10, initialDelay: 0)
+ def conditions = new PollingConditions(timeout: 15, initialDelay: 0)
when: "the container starts"
def serverPort = findEphemeralPort()
diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
index aa10fb5cf..32658ff08 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
@@ -151,7 +151,14 @@ public enum AssetMeta implements HasMetaName {
/**
* Marks an attribute as being executable so it then supports values of type {@link AttributeExecuteStatus}.
*/
- EXECUTABLE(ASSET_META_NAMESPACE + ":executable", new Access(true, false, true), ValueType.BOOLEAN);
+ EXECUTABLE(ASSET_META_NAMESPACE + ":executable", new Access(true, false, true), ValueType.BOOLEAN),
+
+ /**
+ * Marks an agent linked attribute as being linked to a property of the linked protocol (e.g. an attribute
+ * linked to the {@link #ENABLED} status of a protocol configuration) should use this meta with a value of
+ * "ENABLED"; other supported values are protocol dependent.
+ */
+ PROTOCOL_PROPERTY(ASSET_META_NAMESPACE + ":protocolProperty", new Access(true, false, true), ValueType.STRING);
final protected String urn;
final protected Access access;
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeState.java b/model/src/main/java/org/openremote/model/attribute/AttributeState.java
index d9dbcd86d..b7023827f 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeState.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeState.java
@@ -27,6 +27,8 @@ import org.openremote.model.value.Values;
import java.util.Objects;
import java.util.Optional;
+import static org.openremote.model.util.TextUtil.requireNonNullAndNonEmpty;
+
/**
* The desired or current or past state of an {@link AttributeRef}.
*/
@@ -38,6 +40,12 @@ public class AttributeState {
protected AttributeState() {
}
+ public AttributeState(String entityId, String attributeName, Value value) {
+ this(new AttributeRef(entityId, attributeName), value);
+ requireNonNullAndNonEmpty(entityId);
+ requireNonNullAndNonEmpty(attributeName);
+ }
+
/**
* @param value can be <code>null</code> if the attribute has no value.
*/