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
Updated Protocol interface and AbstractProtocol
Rich Turnere2cbafa3d45b
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.javaindex 42253d904..5a76d5085 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java@@ -27,14 +27,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.asset.AssetAttribute;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.attribute.AttributeState;-import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.util.Pair;import java.util.Collection;import java.util.HashMap;import java.util.Map;+import java.util.function.Consumer;import java.util.logging.Logger;public abstract class AbstractProtocol implements Protocol {@@ -51,16 +53,19 @@ public abstract class AbstractProtocol implements Protocol {}final protected Map<AttributeRef, AssetAttribute> linkedAttributes = new HashMap<>();+ final protected Map<AttributeRef, Pair<AssetAttribute, Consumer<DeploymentStatus>>> linkedProtocolConfigurations = new HashMap<>();protected MessageBrokerContext messageBrokerContext;protected ProducerTemplate producerTemplate;protected TimerService timerService;protected ProtocolExecutorService executorService;+ protected ProtocolAssetService assetService;@Overridepublic void init(Container container) throws Exception {LOG.info("Initializing protocol: " + getProtocolName());timerService = container.getService(TimerService.class);executorService = container.getService(ProtocolExecutorService.class);+ assetService = container.getService(ProtocolAssetService.class);}@Override@@ -76,11 +81,17 @@ public abstract class AbstractProtocol implements Protocol {from(ACTUATOR_TOPIC).routeId("Actuator-" + getProtocolName()).process(exchange -> {- // TODO Use read/write lock for link/unlink attributes synchronization and additional optional exclusive lock for single-threaded implementors- synchronized (linkedAttributes) {- // TODO This could be optimized, we must avoid inspecting all messages (maybe tag with protocol name in header?)- if (isAttributeStateForAny(linkedAttributes.keySet()).matches(exchange)) {- sendToActuator(exchange.getIn().getBody(AttributeEvent.class));+ String protocolName = exchange.getIn().getHeader("Protocol", String.class);+ if (getProtocolName().equals(protocolName)) {+ // TODO Use read/write lock for link/unlink attributes synchronization and additional optional exclusive lock for single-threaded implementors+ synchronized (linkedAttributes) {+ AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);+ AssetAttribute attribute = linkedAttributes.get(event.getAttributeRef());+ if (attribute == null) {+ LOG.warning("Attribute doesn't exist on this protocol: " + event.getAttributeRef());+ } else {+ processLinkedAttributeWrite(event, attribute);+ }}}});@@ -99,18 +110,33 @@ public abstract class AbstractProtocol implements Protocol {}@Override- public void linkAttributes(Collection<AssetAttribute> attributes, AssetAttribute protocolConfiguration) throws Exception {+ public void linkProtocolConfiguration(AssetAttribute protocolConfiguration, Consumer<DeploymentStatus> deploymentStatusConsumer) {+ synchronized (linkedProtocolConfigurations) {+ LOG.finer("Linking protocol configuration to protocol '" + getProtocolName() + "': " + protocolConfiguration);+ linkedProtocolConfigurations.put(+ protocolConfiguration.getReferenceOrThrow(),+ new Pair<>(protocolConfiguration, deploymentStatusConsumer)+ );+ doLinkProtocolConfiguration(protocolConfiguration);+ }+ }++ @Override+ public void unlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ synchronized (linkedProtocolConfigurations) {+ LOG.finer("Unlinking protocol configuration from protocol '" + getProtocolName() + "': " + protocolConfiguration);+ doUnlinkProtocolConfiguration(protocolConfiguration);+ linkedProtocolConfigurations.remove(protocolConfiguration.getReferenceOrThrow());+ }+ }++ @Override+ public void linkAttributes(Collection<AssetAttribute> attributes, AssetAttribute protocolConfiguration) {synchronized (linkedAttributes) {attributes.forEach(attribute -> {- if (linkedAttributes.containsKey(attribute.getReferenceOrThrow())) {- LOG.fine("Attribute updated on '" + getProtocolName() + "': " + attribute);- onAttributeUpdated(attribute, protocolConfiguration);- linkedAttributes.put(attribute.getReferenceOrThrow(), attribute);- } else {- LOG.fine("Attribute added on '" + getProtocolName() + "': " + attribute);- onAttributeAdded(attribute, protocolConfiguration);- linkedAttributes.put(attribute.getReferenceOrThrow(), attribute);- }+ LOG.fine("Linking attribute to '" + getProtocolName() + "': " + attribute);+ linkedAttributes.put(attribute.getReferenceOrThrow(), attribute);+ doLinkAttribute(attribute, protocolConfiguration);});}}@@ -118,45 +144,87 @@ public abstract class AbstractProtocol implements Protocol {@Overridepublic void unlinkAttributes(Collection<AssetAttribute> attributes, AssetAttribute protocolConfiguration) throws Exception {synchronized (linkedAttributes) {- attributes- .stream()- .filter(attribute -> linkedAttributes.values()- .stream()- .anyMatch(linkedAttribute ->- linkedAttribute- .getReferenceOrThrow()- .equals(attribute.getReferenceOrThrow()))- )- .forEach(attributeToRemove -> {- AttributeRef agentLinkedAttributeRef = attributeToRemove.getReferenceOrThrow();-- linkedAttributes.remove(agentLinkedAttributeRef);- LOG.fine("Attribute removed on '" + getProtocolName() + "': " + attributeToRemove);- onAttributeRemoved(attributeToRemove, protocolConfiguration);- });+ attributes.forEach(attribute -> {+ LOG.fine("Unlinking attribute on '" + getProtocolName() + "': " + attribute);+ doUnlinkAttribute(attribute, protocolConfiguration);+ linkedAttributes.remove(attribute.getReferenceOrThrow());+ });}}+ /**+ * Gets a linked attribute by its attribute ref+ */protected AssetAttribute getLinkedAttribute(AttributeRef attributeRef) {synchronized (linkedAttributes) {return linkedAttributes.get(attributeRef);}}+ /**+ * Get the deployment status consumer for a given protocol configuration+ */+ protected Consumer<DeploymentStatus> getDeploymentStatusConsumer(AssetAttribute protocolConfiguration) {+ return getDeploymentStatusConsumer(protocolConfiguration.getReferenceOrThrow());+ }++ /**+ * Get the deployment status consumer for a given protocol configurations attribute ref+ */+ protected Consumer<DeploymentStatus> getDeploymentStatusConsumer(AttributeRef protocolRef) {+ synchronized (linkedProtocolConfigurations) {+ return linkedProtocolConfigurations.containsKey(protocolRef)+ ? linkedProtocolConfigurations.get(protocolRef).value+ : null;+ }+ }++ /**+ * Send an arbitrary {@link AttributeState} through the processing chain+ * using the current system time as the timestamp.+ */protected void sendAttributeEvent(AttributeState state) {AttributeEvent event = new AttributeEvent(state, timerService.getCurrentTimeMillis());- LOG.info("Sending on sensor queue: " + event);- producerTemplate.sendBodyAndHeader(SENSOR_QUEUE, event, "isSensorUpdate", false);+ LOG.info("Sending attribute event from protocol '" + getProtocolName() + "': " + event);+ assetService.sendAttributeEvent(event);+ }++ /**+ * Send an arbitrary {@link AttributeEvent} through the processing chain.+ */+ protected void sendAttributeEvent(AttributeEvent attributeEvent) {+ LOG.info("Sending attribute event: " + attributeEvent);+ assetService.sendAttributeEvent(attributeEvent);}- protected void onSensorUpdate(AttributeState state, long timestamp) {+ /**+ * Update the value of a linked attribute.+ */+ protected void updateLinkedAttribute(AttributeState state, long timestamp) {AttributeEvent event = new AttributeEvent(state, timestamp);LOG.fine("Sending on sensor queue: " + event);producerTemplate.sendBody(SENSOR_QUEUE, event);}- protected void onSensorUpdate(AttributeState state) {- onSensorUpdate(state, timerService.getCurrentTimeMillis());+ /**+ * Update the value of a linked attribute.+ */+ protected void updateLinkedAttribute(AttributeState state) {+ updateLinkedAttribute(state, timerService.getCurrentTimeMillis());+ }++ /**+ * Update the deployment status of a protocol configuration by its attribute ref+ */+ protected void updateDeploymentStatus(AttributeRef protocolRef, DeploymentStatus deploymentStatus) {+ synchronized (linkedProtocolConfigurations) {+ linkedProtocolConfigurations.computeIfPresent(protocolRef,+ (ref, pair) -> {+ pair.value.accept(deploymentStatus);+ return pair;+ }+ );+ }}@Override@@ -165,11 +233,29 @@ public abstract class AbstractProtocol implements Protocol {'}';}- abstract protected void sendToActuator(AttributeEvent event);+ /**+ * Link the protocol configuration.+ */+ abstract protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration);++ /**+ * Unlink the protocol configuration.+ */+ abstract protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration);- abstract protected void onAttributeAdded(AssetAttribute attribute, AssetAttribute protocolConfiguration);+ /**+ * Link an attribute to its linked protocol configuration.+ */+ abstract protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration);- abstract protected void onAttributeUpdated(AssetAttribute attribute, AssetAttribute protocolConfiguration);+ /**+ * Unlink an attribute from its linked protocol configuration.+ */+ abstract protected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration);- abstract protected void onAttributeRemoved(AssetAttribute attribute, AssetAttribute protocolConfiguration);+ /**+ * Attribute event (write) has been requested for an attribute linked to the specified+ * protocol configuration.+ */+ abstract protected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration);}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.javaindex c220d09ad..e811b48da 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java@@ -20,42 +20,149 @@package org.openremote.agent3.protocol;import org.openremote.container.ContainerService;-import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.Constants;+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.ProtocolConfiguration;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.MetaItem;import java.util.Collection;+import java.util.function.Consumer;/**- * A Protocol implementation must have a unique name in a VM. TODO This is not enforced.+ * A Protocol implementation must have a unique name in a VM.+ * <p>+ * All protocol names must be in the {@link Constants#PROTOCOL_NAMESPACE}.+ * <p>+ * Protocols are singletons and 'instances' are defined by an attribute on an+ * {@link Asset} that has a type of {@link AssetType#AGENT}; the attribute must+ * conform to {@link ProtocolConfiguration}.+ * <p>+ * When a {@link ProtocolConfiguration} {@link AssetAttribute} is loaded/created for a protocol+ * then the {@link #linkProtocolConfiguration(AssetAttribute, Consumer)} method will be called.+ * <p>+ * When a protocolConfiguration is linked the protocol is responsible for calling the consumer+ * whenever the status of the protocolConfiguration changes (e.g. if the protocolConfiguration+ * is not valid then the protocol should call the consumer with a value of {@link DeploymentStatus#ERROR}+ * and it should provide sensible logging to allow fault finding.* <p>- * OpenRemote protocols are in {@link Constants#PROTOCOL_NAMESPACE}, third-party protocols- * should use their own URN namespace identifier.+ * The protocol should check the {@link AssetAttribute#isEnabled()} status of the protocolConfiguration+ * to determine whether or not it should be running or stopped.* <p>- * The protocol implementation can receive {@link AttributeEvent} messages on the- * {@link #ACTUATOR_TOPIC}. It can produce {@link AttributeEvent} messages on the- * {@link #SENSOR_QUEUE}.+ * {@link AssetAttribute}s of other {@link Asset}s can be linked to a protocolConfiguration by creating+ * an {@link AssetMeta#AGENT_LINK} {@link MetaItem} on the attribute, other MetaItems+ * may then be required that are specific to the linked protocolConfiguration so that it can determine+ * what data to read/write from/to the attribute. Attributes linked to a protocolConfiguration will get passed+ * to the protocol via a call to {@link #linkAttributes(Collection, AssetAttribute)}.* <p>- * The linked attributes of a protocol provide the model for the protocol to perform these operations. How- * attributes and value changes map to actual device and service calls is up to the implementation. The method- * {@link #linkAttributes} is first called during startup of the protocol, after- * {@link #init} and before {@link #start}.+ * NOTE: That {@link #linkProtocolConfiguration(AssetAttribute, Consumer)} will always be called before+ * {@link #linkAttributes(Collection, AssetAttribute)} and {@link #unlinkAttributes(Collection, AssetAttribute)}+ * will always be called before {@link #unlinkProtocolConfiguration(AssetAttribute)}+ * <p>+ * Write operations on attributes linked to a protocolConfiguration can be consumed by the protocol+ * on the {@link #ACTUATOR_TOPIC} where the message body will be an {@link AttributeEvent}.+ * If a protocol wants to update a linked attributes' value then it can produce {@link AttributeEvent} messages+ * on the {@link #SENSOR_QUEUE}.* <p>* The linked protocol handles south-bound read and write of the attribute value: If the user writes- * a new value into the Thing attribute, the protocol translates this value change into a+ * a new value into a linked attribute, the protocol translates this value change into a* device (or service) action. If the actual state of the device (or service) changes, the linked* protocol writes the new state into the attribute value and the asset system user is notified of the change.* <p>* Data type conversion is also delegated to the Protocol implementation: If an attribute has a particular* AttributeType and therefore a certain JsonValue, the Protocol must receive and send value change messages* with values of that type.- * TODO: Some kind of converter system can be introduced later, although I find JsonValue#asXXX() is already a good utility for protocol implementators.* <p>- * Protocol-specific meta items required for the link can be added to Thing attributes, such as the- * Hue light identifier or the ZWave node and command.+ * The following summarises the method calls protocols should expect:+ * <p>+ * Protocol Configuration is created/loaded:+ * <ol>+ * <li>{@link #linkProtocolConfiguration(AssetAttribute, Consumer)}</li>+ * <li>{@link #linkAttributes(Collection, AssetAttribute)}</li>+ * </ol>+ * <p>+ * Protocol Configuration is modified:+ * <ol>+ * <li>{@link #unlinkAttributes(Collection, AssetAttribute)}</li>+ * <li>{@link #unlinkProtocolConfiguration(AssetAttribute)}</li>+ * <li>{@link #linkProtocolConfiguration(AssetAttribute, Consumer)}</li>+ * <li>{@link #linkAttributes(Collection, AssetAttribute)}</li>+ * </ol>+ * <p>+ * Protocol Configuration is removed:+ * <ol>+ * <li>{@link #unlinkAttributes(Collection, AssetAttribute)}</li>+ * <li>{@link #unlinkProtocolConfiguration(AssetAttribute)}</li>+ * </ol>+ * <p>+ * Linked Attribute is created/loaded:+ * <ol>+ * <li>{@link #linkAttributes(Collection, AssetAttribute)}</li>+ * </ol>+ * <p>+ * Linked Attribute is modified:+ * <ol>+ * <li>{@link #unlinkAttributes(Collection, AssetAttribute)}</li>+ * <li>{@link #linkAttributes(Collection, AssetAttribute)}</li>+ * </ol>+ * <p>+ * Linked Attribute is removed:+ * <ol>+ * <li>{@link #unlinkAttributes(Collection, AssetAttribute)}</li>+ * </ol>*/public interface Protocol extends ContainerService {+ /**+ * Indicates the deployment status of a protocol configuration (i.e. protocol instance).+ */+ enum DeploymentStatus {++ /**+ * Protocol configuration has not yet been linked (i.e. {@link #linkProtocolConfiguration(AssetAttribute, Consumer)}+ * hasn't yet been called for the configuration.+ */+ UNLINKED,++ /**+ * Protocol configuration is being linked to the protocol.+ */+ LINKING,++ /**+ * Protocol configuration is being unlinked from the protocol.+ */+ UNLINKING,++ /**+ * Protocol configuration has been linked, is valid and it is enabled.+ */+ LINKED_ENABLED,++ /**+ * Protocol configuration has been linked, it is valid but it is not enabled (i.e. it has a+ * {@link org.openremote.model.asset.AssetMeta#ENABLED} {@link MetaItem}+ * with a value of false).+ */+ LINKED_DISABLED,++ /**+ * Protocol configuration is not valid or some internal protocol error occurred that prevents+ * this configuration from running (the protocol should provide sensible logging to allow fault+ * finding).+ */+ ERROR,++ /**+ * Protocol is performing an operation that means the status cannot be exactly determined at this+ * time (e.g. the protocol is trying to re-establish a connection to a remote server).+ */+ UPDATING+ }+// 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)@@ -66,8 +173,32 @@ public interface Protocol extends ContainerService {String getProtocolName();- void linkAttributes(Collection<AssetAttribute> attributes, AssetAttribute protocolConfiguration) throws Exception;+ /**+ * Links attributes to their protocolConfiguration; the protocolConfiguration would have+ * been linked before this call. If an attribute is not valid for this protocol or the protocol+ * Configuration then it is up to the protocol whether to put the entire protocolConfiguration+ * into an {@link DeploymentStatus#ERROR} state or to continue running (appropriate logging should+ * always be used).+ * <p>+ * Attributes are linked to a protocol configuration via an {@link AssetMeta#AGENT_LINK} meta item.+ */+ void linkAttributes(Collection<AssetAttribute> attributes, AssetAttribute protocolConfiguration);+ /**+ * Un-links attributes from their protocolConfiguration; called whenever an attribute is modified or removed+ * or when the linked protocolConfiguration is modified or removed.+ */void unlinkAttributes(Collection<AssetAttribute> attributes, AssetAttribute protocolConfiguration) throws Exception;+ /**+ * Links the protocol configuration to the protocol; the protocol is responsible for calling the deploymentStatusConsumer+ * to indicate the state of the protocol configuration.+ */+ void linkProtocolConfiguration(AssetAttribute protocolConfiguration, Consumer<DeploymentStatus> deploymentStatusConsumer);++ /**+ * Un-links the protocol configuration from the protocol; called whenever a protocolConfiguration is modified+ * or removed.+ */+ void unlinkProtocolConfiguration(AssetAttribute protocolConfiguration);}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/ProtocolAssetService.java b/agent/src/main/java/org/openremote/agent3/protocol/ProtocolAssetService.javanew file mode 100644index 000000000..e889a885a--- /dev/null+++ b/agent/src/main/java/org/openremote/agent3/protocol/ProtocolAssetService.java@@ -0,0 +1,40 @@+/*+ * 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.agent3.protocol;++import org.openremote.container.ContainerService;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.attribute.AttributeEvent;++/**+ * Interface for protocols to perform limited asset+ * related operations.+ * <p>+ * <ul>+ * <li>Send attribute events into the processing chain</li>+ * <li>Update their own protocol configurations</li>+ * </ul>+ */+public interface ProtocolAssetService extends ContainerService {+ void sendAttributeEvent(AttributeEvent attributeEvent);++ // TODO: Find a way of limiting protocols to only modifying their own protocol configurations+ void updateProtocolConfiguration(AssetAttribute protocolConfiguration);+}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroConfiguration.java b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroConfiguration.javaindex 3f743fddf..420adec84 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroConfiguration.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroConfiguration.java@@ -102,14 +102,10 @@ final public class MacroConfiguration {attribute.getMeta().addAll(actions- .map(action -> action.toMetaItem())+ .map(MacroAction::toMetaItem).collect(Collectors.toList()));return attribute;}-- public static UnaryOperator<AssetAttribute> setMacroActions(Stream<MacroAction> actions) {- return attribute -> setMacroActions(attribute, actions);- }}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.javaindex 7f0627e08..78215baca 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java@@ -25,6 +25,7 @@ import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeExecuteStatus;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.attribute.AttributeState;+import org.openremote.model.util.Pair;import org.openremote.model.value.Value;import org.openremote.model.value.Values;@@ -40,7 +41,7 @@ import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;* This protocol is responsible for executing macros.* <p>* It expects a {@link AttributeExecuteStatus} as the attribute event value on the- * sendToActuator. The protocol will then try to perform the requested status on the+ * processLinkedAttributeWrite. The protocol will then try to perform the requested status on the* linked macro.*/public class MacroProtocol extends AbstractProtocol {@@ -67,7 +68,7 @@ public class MacroProtocol extends AbstractProtocol {}// Update the command Status of this attribute- onSensorUpdate(new AttributeState(attributeRef, AttributeExecuteStatus.RUNNING.asValue()));+ updateLinkedAttribute(new AttributeState(attributeRef, AttributeExecuteStatus.RUNNING.asValue()));run();}@@ -80,7 +81,7 @@ public class MacroProtocol extends AbstractProtocol {}// Update the command Status of this attribute- onSensorUpdate(new AttributeState(attributeRef, AttributeExecuteStatus.CANCELLED.asValue()));+ updateLinkedAttribute(new AttributeState(attributeRef, AttributeExecuteStatus.CANCELLED.asValue()));}private void run() {@@ -112,7 +113,7 @@ public class MacroProtocol extends AbstractProtocol {}// Update the command Status of this attribute- onSensorUpdate(new AttributeState(attributeRef, AttributeExecuteStatus.COMPLETED.asValue()));+ updateLinkedAttribute(new AttributeState(attributeRef, AttributeExecuteStatus.COMPLETED.asValue()));return;}@@ -125,7 +126,7 @@ public class MacroProtocol extends AbstractProtocol {}private static final Logger LOG = Logger.getLogger(MacroProtocol.class.getName());- protected final Map<AttributeRef, List<MacroAction>> macroMap = new HashMap<>();+ protected final Map<AttributeRef, Pair<Boolean, List<MacroAction>>> macroMap = new HashMap<>();protected final Map<AttributeRef, AttributeRef> macroAttributeMap = new HashMap<>();protected final Map<AttributeRef, MacroExecutionTask> executions = new HashMap<>();@@ -135,9 +136,38 @@ public class MacroProtocol extends AbstractProtocol {}@Override- protected void sendToActuator(AttributeEvent event) {+ protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ // Protocol configuration is actually a Macro Configuration+ AttributeRef macroRef = protocolConfiguration.getReferenceOrThrow();+ boolean isEnabled = protocolConfiguration.isEnabled();++ synchronized (macroMap) {+ // Check macro configuration is valid+ if (!isValidMacroConfiguration(protocolConfiguration)) {+ LOG.fine("Macro configuration is not valid: " + protocolConfiguration);+ updateDeploymentStatus(macroRef, DeploymentStatus.ERROR);+ // Put an empty list of actions against this macro+ macroMap.put(macroRef, new Pair<>(isEnabled, Collections.emptyList()));+ } else {+ // Store the macro actions for later execution requests+ macroMap.put(macroRef, new Pair<>(isEnabled, getMacroActions(protocolConfiguration)));+ updateDeploymentStatus(macroRef, isEnabled ? DeploymentStatus.LINKED_ENABLED : DeploymentStatus.LINKED_DISABLED);+ }+ }+ }++ @Override+ protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ AttributeRef macroRef = protocolConfiguration.getReferenceOrThrow();+ synchronized (macroMap) {+ macroMap.remove(macroRef);+ }+ }++ @Override+ protected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration) {+// Asset processing service has already done sanity checks- // Can be valid to pass null toOptional<Value> value = event.getValue();AttributeExecuteStatus status = event.getValue().flatMap(Values::getString)@@ -160,8 +190,14 @@ public class MacroProtocol extends AbstractProtocol {return;}+ // If protocol configuration is disabled then nothing to do here+ if (!protocolConfiguration.isEnabled()) {+ LOG.fine("Protocol configuration is disabled so cannot be executed: " + protocolConfiguration.getReferenceOrThrow());+ return;+ }+AttributeRef macroRef;- List<MacroAction> actions;+ Pair<Boolean, List<MacroAction>> actionsEnabledPair;synchronized (macroAttributeMap) {macroRef = macroAttributeMap.get(attributeRef);@@ -173,56 +209,49 @@ public class MacroProtocol extends AbstractProtocol {}synchronized (macroMap) {- actions = macroMap.get(macroRef);+ actionsEnabledPair = macroMap.get(macroRef);}- if (actions == null || actions.size() == 0) {+ if (actionsEnabledPair == null || actionsEnabledPair.value.size() == 0) {LOG.fine("No macro actions found for attribute event: " + event);return;}- executeMacro(attributeRef, actions, status == AttributeExecuteStatus.REQUEST_REPEATING);+ if (!actionsEnabledPair.key) {+ LOG.fine("Macro configuration is disabled so cannot execute");+ return;+ }++ executeMacro(attributeRef, actionsEnabledPair.value, status == AttributeExecuteStatus.REQUEST_REPEATING);}@Override- protected void onAttributeAdded(AssetAttribute attribute, AssetAttribute macroConfiguration) {- // Protocol configuration is actually a Macro Configuration- AttributeRef macroRef = macroConfiguration.getReferenceOrThrow();-- // Only process the macro configuration the first time it is encountered- synchronized (macroMap) {- if (!macroMap.containsKey(macroRef)) {- // Check macro configuration is valid- if (!isValidMacroConfiguration(macroConfiguration)) {- LOG.fine("Macro configuration is not valid: " + macroConfiguration);-- // Put an empty list of actions against this macro- macroMap.put(macroRef, Collections.emptyList());- } else {- // Store the macro actions for later execution requests- macroMap.put(macroRef, getMacroActions(macroConfiguration));- }- }- }+ protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {+ AttributeRef macroRef = protocolConfiguration.getReferenceOrThrow();// Store link between attribute and configurationsynchronized (macroAttributeMap) {macroAttributeMap.put(attribute.getReferenceOrThrow(), macroRef);}- }- @Override- protected void onAttributeUpdated(AssetAttribute attribute, AssetAttribute protocolConfiguration) {- onAttributeAdded(attribute, protocolConfiguration);+ // Update the command Status of this attribute+ updateLinkedAttribute(+ new AttributeState(+ attribute.getReferenceOrThrow(),+ protocolConfiguration.isEnabled()+ ? AttributeExecuteStatus.READY.asValue()+ : AttributeExecuteStatus.DISABLED.asValue()+ )+ );}@Override- protected void onAttributeRemoved(AssetAttribute attribute, AssetAttribute protocolConfiguration) {+ protected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {// Store the macro actions for later execution requestsAttributeRef reference = attribute.getReferenceOrThrow();synchronized (macroAttributeMap) {- macroAttributeMap.remove(attribute.getReference());+ macroAttributeMap.remove(reference);}}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.javaindex be26ba1e5..4641001e4 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java@@ -38,7 +38,6 @@ import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;import static org.openremote.model.asset.AssetMeta.RANGE_MAX;import static org.openremote.model.asset.AssetMeta.RANGE_MIN;-// TODO: Should putState be allowed or should users be forced to go through the AssetProcessingService processing chainpublic class SimulatorProtocol extends AbstractProtocol {/**@@ -61,8 +60,10 @@ public class SimulatorProtocol extends AbstractProtocol {public static class Instance {protected Mode mode;protected int delayMilliseconds;+ protected boolean enabled;- public Instance(Mode mode, int delayMilliseconds) {+ public Instance(Mode mode, int delayMilliseconds, boolean enabled) {+ this.enabled = enabled;this.mode = mode;this.delayMilliseconds = delayMilliseconds;}@@ -74,6 +75,10 @@ public class SimulatorProtocol extends AbstractProtocol {public int getDelayMilliseconds() {return delayMilliseconds;}++ public boolean isEnabled() {+ return enabled;+ }}protected static final Map<AttributeRef, SimulatorElement> elements = new HashMap<>();@@ -110,24 +115,13 @@ public class SimulatorProtocol extends AbstractProtocol {}@Override- protected void onAttributeAdded(AssetAttribute attribute, AssetAttribute protocolConfiguration) {-- // Get element type from the attribute meta- String elementType = getElementType(attribute)- .orElseThrow(- () -> new IllegalArgumentException(- "Can't configure simulator, missing " + SIMULATOR_ELEMENT + " meta item on: " + attribute- )- );-- // Look for existing instance for this protocol configuration or create if needed- AttributeRef configRef = protocolConfiguration.getReferenceOrThrow();- AttributeRef attributeRef = attribute.getReferenceOrThrow();+ protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();synchronized (instances) {instances.computeIfAbsent(- configRef,+ protocolRef,ref -> {Mode mode = protocolConfiguration.getMetaItem(CONFIG_MODE)@@ -149,10 +143,35 @@ public class SimulatorProtocol extends AbstractProtocol {.flatMap(AbstractValueHolder::getValueAsInteger).orElse(DEFAULT_WRITE_DELAY);- return new Instance(mode, writeDelay);+ updateDeploymentStatus(protocolRef, protocolConfiguration.isEnabled() ? DeploymentStatus.LINKED_ENABLED : DeploymentStatus.LINKED_DISABLED);+ return new Instance(mode, writeDelay, protocolConfiguration.isEnabled());});}+ }++ @Override+ protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ AttributeRef configRef = protocolConfiguration.getReferenceOrThrow();++ synchronized (instances) {+ instances.remove(configRef);+ }+ }++ @Override+ protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {++ // Get element type from the attribute meta+ String elementType = getElementType(attribute)+ .orElseThrow(+ () -> new IllegalArgumentException(+ "Can't configure simulator, missing " + SIMULATOR_ELEMENT + " meta item on: " + attribute+ )+ );++ AttributeRef configRef = protocolConfiguration.getReferenceOrThrow();+ AttributeRef attributeRef = attribute.getReferenceOrThrow();SimulatorElement element = createElement(elementType, attribute);if (attribute.getValue().isPresent()) {@@ -175,12 +194,7 @@ public class SimulatorProtocol extends AbstractProtocol {}@Override- protected void onAttributeUpdated(AssetAttribute attribute, AssetAttribute protocolConfiguration) {- onAttributeAdded(attribute, protocolConfiguration);- }-- @Override- protected void onAttributeRemoved(AssetAttribute attribute, AssetAttribute protocolConfiguration) {+ protected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {AttributeRef attributeRef = attribute.getReferenceOrThrow();synchronized (elements) {@@ -193,7 +207,7 @@ public class SimulatorProtocol extends AbstractProtocol {}@Override- protected void sendToActuator(AttributeEvent event) {+ protected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration) {putState(event.getAttributeState());}@@ -224,39 +238,59 @@ public class SimulatorProtocol extends AbstractProtocol {public void updateSensor(AttributeRef attributeRef, int updateSensorDelayMilliseconds) {Value value = getState(attributeRef);final AttributeState state = new AttributeState(attributeRef, value);+ AttributeRef instanceRef = attributeInstanceMap.get(attributeRef);++ if (instanceRef == null) {+ throw new IllegalArgumentException("Attribute is not referenced by an instance:" + attributeRef);+ }++ Instance instance;++ synchronized (instances) {+ instance = instances.get(instanceRef);+ }++ if (instance == null) {+ throw new IllegalArgumentException("No instance found by name '" + instanceRef + "'");+ }++ if (!instance.isEnabled()) {+ LOG.fine("Simulator protocol configuration is disabled so cannot process request");+ return;+ }if (updateSensorDelayMilliseconds <= 0) {- onSensorUpdate(state);+ updateLinkedAttribute(state);} else {- executorService.schedule(() -> onSensorUpdate(state), updateSensorDelayMilliseconds);+ executorService.schedule(() -> updateLinkedAttribute(state), updateSensorDelayMilliseconds);}}/*** Call this to simulate a send to actuator.*/- public void putState(String entityId, String attributeName, Value value) {+ protected void putState(String entityId, String attributeName, Value value) {putState(new AttributeState(new AttributeRef(entityId, attributeName), value));}/*** Call this to simulate a send to actuator.*/- public void putState(AttributeRef attributeRef, Value value) {+ protected void putState(AttributeRef attributeRef, Value value) {putState(new AttributeState(attributeRef, value));}/*** Call this to simulate a send to actuator.*/- public void putState(AttributeEvent event) {+ protected void putState(AttributeEvent event) {putState(event.getAttributeState());}/*** Call this to simulate a send to actuator.*/- public void putState(AttributeState attributeState) {+ protected void putState(AttributeState attributeState) {AttributeRef attributeRef = attributeState.getAttributeRef();AttributeRef instanceRef = attributeInstanceMap.get(attributeRef);@@ -274,6 +308,11 @@ public class SimulatorProtocol extends AbstractProtocol {throw new IllegalArgumentException("No instance found by name '" + instanceRef + "'");}+ if (!instance.isEnabled()) {+ LOG.fine("Simulator protocol configuration is disabled so cannot process request");+ return;+ }+synchronized (elements) {LOG.info("Put simulator state: " + attributeState);SimulatorElement element = elements.get(attributeRef);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.javaindex abf6bcb52..ace15024f 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@@ -21,6 +21,7 @@ package org.openremote.agent3.protocol.trigger;import org.openremote.agent3.protocol.AbstractProtocol;import org.openremote.container.Container;+import org.openremote.model.asset.AssetAttribute;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.attribute.AttributeState;@@ -56,7 +57,7 @@ public abstract class AbstractTriggerHandler {protected abstract void unregisterAttribute(AttributeRef attributeRef, AttributeRef triggerRef);/**- * A {@link AbstractProtocol#sendToActuator(AttributeEvent)} has occurred on the protocol.+ * A {@link AbstractProtocol#processLinkedAttributeWrite(AttributeEvent, AssetAttribute)} has occurred on the protocol.** The {@link AbstractTriggerHandler} implementation should override this method* to handle the request based on the propertyName and the {@link AttributeEvent}.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.javaindex f20f07a98..2cd77a9e9 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@@ -100,8 +100,6 @@ public class TriggerProtocol extends AbstractProtocol {public void init(Container container) throws Exception {super.init(container);- // TODO: Wire up AssetStorageService so we can push trigger configuration updates- //container.getService(AssetStorageService.class);// Push static protocol reference so trigger handlers can call doTriggerActionAbstractTriggerHandler.protocol = this;@@ -113,7 +111,41 @@ public class TriggerProtocol extends AbstractProtocol {}@Override- protected void sendToActuator(AttributeEvent event) {+ protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ // The protocol configuration is actually a Trigger Configuration+ AssetAttribute initialisedProtocolConfiguration;++ synchronized (protocolConfigMap) {+ initialisedProtocolConfiguration = protocolConfigMap.computeIfAbsent(protocolConfiguration.getReferenceOrThrow(), protocolConfigRef ->+ {+ // Verify that this is a valid Trigger Configuration+ if (!isValidTriggerConfiguration(protocolConfiguration)) {+ LOG.warning("Trigger Configuration is not valid so it will be ignored: " + protocolConfigRef);+ updateDeploymentStatus(protocolConfigRef, DeploymentStatus.ERROR);+ return null;+ }++ // Register the trigger with its handler+ TriggerType type = getTriggerType(protocolConfiguration).get();+ AbstractTriggerHandler handler = getTriggerTypeHandler(protocolConfiguration).get();+ Value value = getTriggerValue(protocolConfiguration).get();+ handler.registerTrigger(protocolConfigRef, value, protocolConfiguration.isEnabled());+ updateDeploymentStatus(protocolConfigRef, protocolConfiguration.isEnabled() ? DeploymentStatus.LINKED_ENABLED : DeploymentStatus.LINKED_DISABLED);++ return protocolConfiguration;+ });+ }+ }++ @Override+ protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ synchronized (protocolConfigMap) {+ protocolConfigMap.remove(protocolConfiguration.getReferenceOrThrow());+ }+ }++ @Override+ protected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration) {LOG.fine("Request to send to actuator");// Send to actuator means that the trigger wants to be updated@@ -147,78 +179,15 @@ public class TriggerProtocol extends AbstractProtocol {});}- @SuppressWarnings("ConstantConditions")@Override- protected void onAttributeAdded(AssetAttribute attribute, AssetAttribute protocolConfiguration) {-- // The protocol configuration is actually a Trigger Configuration- // TODO: Initialise triggers even if they don't have linked attributes- AssetAttribute initialisedProtocolConfiguration;-- synchronized (protocolConfigMap) {- initialisedProtocolConfiguration = protocolConfigMap.computeIfAbsent(protocolConfiguration.getReferenceOrThrow(), protocolConfigRef ->- {- // Verify that this is a valid Trigger Configuration- if (!isValidTriggerConfiguration(protocolConfiguration)) {- LOG.warning("Trigger Configuration is not valid so it will be ignored: " + protocolConfigRef);- return null;- }-- // Register the trigger with its handler- TriggerType type = getTriggerType(protocolConfiguration).get();- AbstractTriggerHandler handler = getTriggerTypeHandler(protocolConfiguration).get();- Value value = getTriggerValue(protocolConfiguration).get();- handler.registerTrigger(protocolConfigRef, value, protocolConfiguration.isEnabled());-- return protocolConfiguration;- });- }-- // Do nothing if protocol configuration is not valid- if (initialisedProtocolConfiguration == null) {- LOG.warning("The Trigger Configuration linked to by the attribute is invalid so cannot use it");- return;- }-+ protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {// Wire up the attributeTriggerConfiguration.getTriggerTypeHandler(protocolConfiguration).ifPresent(handler -> registerAttributeWithTriggerHandler(attribute, protocolConfiguration, handler));}@Override- protected void onAttributeUpdated(AssetAttribute attribute, AssetAttribute protocolConfiguration) {- // Check if this attribute is already linked to a handler and that it is the same- AbstractTriggerHandler oldHandler;- AbstractTriggerHandler newHandler;- AttributeRef attributeRef = attribute.getReferenceOrThrow();-- synchronized (attributeTriggerHandlerMap) {- oldHandler = attributeTriggerHandlerMap.get(attributeRef);- }-- newHandler = getTriggerTypeHandler(protocolConfiguration).orElse(null);-- if (oldHandler == null && newHandler == null) {- LOG.finer("Both old and new handlers are null so nothing to do here");- return;- }-- if (newHandler == oldHandler) {- updateAttributeWithTriggerHandler(attribute, protocolConfiguration, oldHandler);- return;- }-- if (oldHandler != null) {- unRegisterAttributeWithTriggerHandler(attributeRef, protocolConfiguration.getReferenceOrThrow(), oldHandler);- }-- if (newHandler != null) {- registerAttributeWithTriggerHandler(attribute, protocolConfiguration, newHandler);- }- }-- @Override- protected void onAttributeRemoved(AssetAttribute attribute, AssetAttribute protocolConfiguration) {+ protected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {AbstractTriggerHandler oldHandler;AttributeRef attributeRef = attribute.getReferenceOrThrow();@@ -242,7 +211,7 @@ public class TriggerProtocol extends AbstractProtocol {AttributeState state = new AttributeState(attributeRef, Values.create(triggerConfiguration.isEnabled()));// Push current value of enabled status into the attributeLOG.info("Updating attribute value with trigger enabled status: " + state);- onSensorUpdate(state);+ updateLinkedAttribute(state);} else {LOG.info("Registering attribute '" + attributeRef + "' on trigger handler '" + handler.getName() + "'");synchronized (attributeTriggerHandlerMap) {@@ -267,7 +236,7 @@ public class TriggerProtocol extends AbstractProtocol {LOG.info("Registering attribute for trigger enabled status: " + attributeRef);// Push current value of enabled status into the attribute- onSensorUpdate(new AttributeState(attributeRef, Values.create(triggerConfiguration.isEnabled())));+ 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);@@ -291,7 +260,7 @@ public class TriggerProtocol extends AbstractProtocol {* Updates the value of an attribute linked to a trigger handler*/void updateAttribute(AttributeState state) {- onSensorUpdate(state);+ updateLinkedAttribute(state);}/**diff --git a/agent/src/main/resources/META-INF/services/org.openremote.agent3.protocol.Protocol b/agent/src/main/resources/META-INF/services/org.openremote.agent3.protocol.Protocolindex 1f446e296..f981c554a 100644--- a/agent/src/main/resources/META-INF/services/org.openremote.agent3.protocol.Protocol+++ b/agent/src/main/resources/META-INF/services/org.openremote.agent3.protocol.Protocol@@ -1,2 +1,3 @@org.openremote.agent3.protocol.simulator.SimulatorProtocol-org.openremote.agent3.protocol.macro.MacroProtocol\ No newline at end of file+org.openremote.agent3.protocol.macro.MacroProtocol+org.openremote.agent3.protocol.trigger.TriggerProtocol\ No newline at end of filediff --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.javaindex a511d0b09..0a71967c6 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@@ -29,7 +29,7 @@ import org.openremote.container.persistence.PersistenceEvent;import org.openremote.manager.server.asset.AssetStorageService;import org.openremote.manager.server.asset.ServerAsset;import org.openremote.manager.server.datapoint.AssetDatapointService;-import org.openremote.model.AbstractValueTimestampHolder;+import org.openremote.model.*;import org.openremote.model.asset.*;import org.openremote.model.asset.agent.AgentLink;import org.openremote.model.asset.agent.ProtocolConfiguration;@@ -47,12 +47,14 @@ import java.util.stream.Collectors;import java.util.stream.Stream;import static org.openremote.agent3.protocol.Protocol.ACTUATOR_TOPIC;+import static org.openremote.agent3.protocol.Protocol.DeploymentStatus.*;import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForAssetType;import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;import static org.openremote.model.asset.AssetAttribute.attributesFromJson;import static org.openremote.model.asset.AssetType.AGENT;import static org.openremote.model.asset.agent.AgentLink.getAgentLink;+import static org.openremote.model.util.TextUtil.isNullOrEmpty;/*** Finds all {@link AssetType#AGENT} and {@link AssetType#THING} assets and starts the protocols for them.@@ -64,7 +66,8 @@ public class AgentService extends RouteBuilder implements ContainerService, Consprotected AssetStorageService assetStorageService;protected AssetDatapointService assetDatapointService;protected MessageBrokerService messageBrokerService;- protected static final Map<AttributeRef, AssetAttribute> protocolConfigurations = new HashMap<>();+ protected final Map<AttributeRef, Pair<AssetAttribute, Protocol.DeploymentStatus>> protocolConfigurations = new HashMap<>();+ protected final Map<String, Protocol> protocols = new HashMap<>();@Overridepublic void init(Container container) throws Exception {@@ -78,6 +81,22 @@ public class AgentService extends RouteBuilder implements ContainerService, Conspublic void start(Container container) throws Exception {container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);+ // Load all protocol instances and fail hard and fast when a duplicate is found+ Collection<Protocol> discoveredProtocols = container.getServices(Protocol.class);++ discoveredProtocols+ .forEach(+ discoveredProtocol -> {+ if (isNullOrEmpty(discoveredProtocol.getProtocolName()) || !discoveredProtocol.getProtocolName().startsWith(Constants.PROTOCOL_NAMESPACE))+ throw new IllegalStateException("Protocol name is invalid it must start with '" + Constants.PROTOCOL_NAMESPACE + "': " + discoveredProtocol.getClass());++ if (protocols.containsKey(discoveredProtocol.getProtocolName()))+ throw new IllegalStateException("A protocol with the name '" + discoveredProtocol.getProtocolName() + "' has already been loaded: " + discoveredProtocol.getClass());++ protocols.put(discoveredProtocol.getProtocolName(), discoveredProtocol);+ }+ );+List<ServerAsset> agents = assetStorageService.findAll(new AssetQuery().select(new AssetQuery.Select(true, false)).type(AssetType.AGENT));@@ -88,7 +107,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Consfor (Asset agent : agents) {agent.getAttributesStream().filter(ProtocolConfiguration::isProtocolConfiguration)- .forEach(this::linkProtocol);+ .forEach(this::linkProtocolConfiguration);}}@@ -96,7 +115,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Conspublic void stop(Container container) throws Exception {synchronized (protocolConfigurations) {new ArrayList<>(protocolConfigurations.values())- .forEach(this::unlinkProtocol);+ .forEach(protocolConfigAndConsumer -> unlinkProtocolConfiguration(protocolConfigAndConsumer.key));}}@@ -127,7 +146,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Consagent.getAttributesStream().filter(ProtocolConfiguration::isProtocolConfiguration)- .forEach(this::linkProtocol);+ .forEach(this::linkProtocolConfiguration);break;case UPDATE:@@ -166,7 +185,7 @@ public class AgentService extends RouteBuilder implements ContainerService, ConsoldProtocolAttribute.getObjectValue().equals(newProtocolAttribute.getObjectValue())))- .forEach(this::unlinkProtocol);+ .forEach(this::unlinkProtocolConfiguration);// Link protocols that are in newConfigs but not in oldConfigsnewProtocolConfigurations@@ -176,7 +195,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons.noneMatch(oldProtocolAttribute ->oldProtocolAttribute.getObjectValue().equals(newProtocolAttribute.getObjectValue()))- ).forEach(this::linkProtocol);+ ).forEach(this::linkProtocolConfiguration);break;case DELETE:@@ -184,7 +203,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons// Unlink any attributes that have an agent link to this agentagent.getAttributesStream().filter(ProtocolConfiguration::isProtocolConfiguration)- .forEach(this::unlinkProtocol);+ .forEach(this::unlinkProtocolConfiguration);break;}}@@ -282,14 +301,40 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons}}- protected void linkProtocol(AssetAttribute protocolConfiguration) {+ protected void linkProtocolConfiguration(AssetAttribute protocolConfiguration) {LOG.finest("Linking all attributes that use protocol attribute: " + protocolConfiguration);-AttributeRef protocolAttributeRef = protocolConfiguration.getReferenceOrThrow();+ Protocol protocol = getProtocol(protocolConfiguration);++ if (protocol == null) {+ LOG.warning("Cannot find protocol that attribute is linked to: " + protocolAttributeRef);+ return;+ }synchronized (protocolConfigurations) {- // Store this protocol configuration for easy access later- protocolConfigurations.put(protocolAttributeRef, protocolConfiguration);+ // Create a consumer callback for deployment status updates+ Consumer<Protocol.DeploymentStatus> deploymentStatusConsumer = status ->+ publishProtocolDeploymentStatus(protocolAttributeRef, status);++ // Store the info+ protocolConfigurations.put(+ protocolAttributeRef,+ new Pair<>(protocolConfiguration, LINKING)+ );++ // Set status to linking+ publishProtocolDeploymentStatus(protocolAttributeRef, LINKING);++ // Link the protocol configuration to the protocol+ try {+ protocol.linkProtocolConfiguration(protocolConfiguration, deploymentStatusConsumer);+ } catch (Exception e) {+ LOG.log(Level.SEVERE, "Protocol threw an exception during protocol configuration linking", e);+ // Set status to error+ publishProtocolDeploymentStatus(protocolAttributeRef, ERROR);+ // Cannot continue to link attributes;+ return;+ }}// Get all assets that have attributes that use this protocol configuration@@ -316,7 +361,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons);}- protected void unlinkProtocol(AssetAttribute protocolConfiguration) {+ protected void unlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {AttributeRef protocolAttributeRef = protocolConfiguration.getReferenceOrThrow();// Get all assets that have attributes that use this protocol configuration@@ -343,21 +388,34 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons);synchronized (protocolConfigurations) {+ Protocol protocol = getProtocol(protocolConfiguration);++ // Unlink the protocol configuration from the protocol+ try {+ protocol.unlinkProtocolConfiguration(protocolConfiguration);+ } catch (Exception e) {+ LOG.log(Level.SEVERE, "Protocol threw an exception during protocol configuration unlinking", e);+ }++ // Set status to error+ publishProtocolDeploymentStatus(protocolAttributeRef, UNLINKED);protocolConfigurations.remove(protocolAttributeRef);}}+ // TODO: Implement mechanism for publishing/subscribing to protocolconfiguration deployment status+ protected void publishProtocolDeploymentStatus(AttributeRef protocolRef, Protocol.DeploymentStatus status) {+ LOG.fine("Protocol status updated to '" + status + "': " + protocolRef);+ synchronized (protocolConfigurations) {+ Pair<AssetAttribute, Protocol.DeploymentStatus> protocolDeploymentInfo = protocolConfigurations.get(protocolRef);+ if (protocolDeploymentInfo != null) {+ protocolDeploymentInfo.value = status;+ }+ }+ }+protected Protocol getProtocol(AssetAttribute protocolConfiguration) {- Collection<Protocol> protocols = container.getServices(Protocol.class);- return protocols- .stream()- .filter(protocol -> {- if (protocol.getProtocolName() == null || protocol.getProtocolName().length() == 0)- throw new IllegalStateException("Protocol can't have empty name: " + protocol.getClass());- return protocol.getProtocolName().equals(protocolConfiguration.getValueAsString().orElse(null));- })- .findFirst()- .orElse(null);+ return protocols.get(protocolConfiguration.getValueAsString().orElse(null));}protected void linkAttributes(AssetAttribute protocolConfiguration, Collection<AssetAttribute> attributes) {@@ -372,8 +430,9 @@ public class AgentService extends RouteBuilder implements ContainerService, ConsLOG.finest("Linking protocol attributes to: " + protocol.getProtocolName());protocol.linkAttributes(attributes, protocolConfiguration);} catch (Exception ex) {- // TODO: Better error handling?- LOG.log(Level.WARNING, "Ignoring error on linking attributes to protocol: " + protocol.getProtocolName(), ex);+ LOG.log(Level.SEVERE, "Ignoring error on linking attributes to protocol: " + protocol.getProtocolName(), ex);+ // Update the status of this protocol configuration to error+ publishProtocolDeploymentStatus(protocolConfiguration.getReferenceOrThrow(), ERROR);}}@@ -389,8 +448,9 @@ public class AgentService extends RouteBuilder implements ContainerService, ConsLOG.finest("Unlinking protocol attributes form: " + protocol.getProtocolName());protocol.unlinkAttributes(attributes, protocolConfiguration);} catch (Exception ex) {- // TODO: Better error handling?- LOG.log(Level.WARNING, "Ignoring error on unlinking attributes from protocol: " + protocol.getProtocolName(), ex);+ LOG.log(Level.SEVERE, "Ignoring error on unlinking attributes from protocol: " + protocol.getProtocolName(), ex);+ // Update the status of this protocol configuration to error+ publishProtocolDeploymentStatus(protocolConfiguration.getReferenceOrThrow(), ERROR);}}@@ -429,9 +489,11 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons.getStateEvent();if (event.isPresent()) {- messageBrokerService.getProducerTemplate().sendBody(+ messageBrokerService.getProducerTemplate().sendBodyAndHeader(ACTUATOR_TOPIC,- event.get()+ event.get(),+ "Protocol",+ protocolConfiguration.getValueAsString().orElse(""));} else {LOG.warning("Attribute doesn't have a valid attribute event: " + assetState);@@ -472,9 +534,10 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons'}';}- public static Optional<AssetAttribute> getProtocolConfiguration(AttributeRef protocolRef) {+ public Optional<AssetAttribute> getProtocolConfiguration(AttributeRef protocolRef) {synchronized (protocolConfigurations) {- return Optional.ofNullable(protocolConfigurations.get(protocolRef));+ Pair<AssetAttribute, Protocol.DeploymentStatus> deploymentStatusPair = protocolConfigurations.get(protocolRef);+ return deploymentStatusPair == null ? Optional.empty() : Optional.of(deploymentStatusPair.key);}}}\ No newline at end of filediff --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 0b1427869..50c9ca757 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@@ -20,6 +20,7 @@package org.openremote.manager.server.asset;import org.apache.camel.builder.RouteBuilder;+import org.openremote.agent3.protocol.ProtocolAssetService;import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.container.message.MessageBrokerService;@@ -32,9 +33,10 @@ import org.openremote.manager.server.event.EventService;import org.openremote.manager.server.rules.RulesService;import org.openremote.manager.server.security.ManagerIdentityService;import org.openremote.manager.shared.security.ClientRole;+import org.openremote.model.asset.*;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeExecuteStatus;-import org.openremote.model.asset.*;+import org.openremote.model.attribute.AttributeRef;import org.openremote.model.value.Values;import java.util.ArrayList;@@ -55,7 +57,7 @@ import static org.openremote.model.asset.agent.AgentLink.getAgentLink;* <p>* {@link AttributeEvent}s can come from various sources:* <ul>- * <li>Protocol ({@link org.openremote.agent3.protocol.AbstractProtocol#onSensorUpdate})</li>+ * <li>Protocol ({@link org.openremote.agent3.protocol.AbstractProtocol#updateLinkedAttribute})</li>* <li>User/Client initiated ({@link #updateAttributeValue})</li>* <li>Rules ({@link org.openremote.model.rules.Assets#dispatch})</li>* </ul>@@ -86,7 +88,7 @@ import static org.openremote.model.asset.agent.AgentLink.getAgentLink;* <h2>Agent service processing logic</h2>* <p>* When the attribute event came from a Protocol (i.e. generated by a call from- * {@link org.openremote.agent3.protocol.AbstractProtocol#onSensorUpdate} then+ * {@link org.openremote.agent3.protocol.AbstractProtocol#updateLinkedAttribute} then* the agent service will ignore the message and just pass it onto the next consumer.* <p>* When the attribute event came from any other source then the agent service will check if it relates@@ -97,7 +99,7 @@ import static org.openremote.model.asset.agent.AgentLink.getAgentLink;* <p>* If the message is for a valid linked agent then an {@link AttributeEvent} is sent on the* {@link org.openremote.agent3.protocol.AbstractProtocol#ACTUATOR_TOPIC} which the protocol will receive in- * {@link org.openremote.agent3.protocol.AbstractProtocol#sendToActuator} for execution on an actual device or+ * {@link org.openremote.agent3.protocol.AbstractProtocol#processLinkedAttributeWrite} for execution on an actual device or* service 'things'.* <p>* This means that a protocol implementation is responsible for producing a new {@link AttributeEvent} to@@ -116,7 +118,7 @@ import static org.openremote.model.asset.agent.AgentLink.getAgentLink;* and if it does then the {@link AttributeEvent} is stored in a time series DB. Then allows the message to continue* if the commit was successful. TODO Should the datapoint service only store northbound updates?*/-public class AssetProcessingService extends RouteBuilder implements ContainerService {+public class AssetProcessingService extends RouteBuilder implements ContainerService, ProtocolAssetService {private static final Logger LOG = Logger.getLogger(AssetProcessingService.class.getName());@@ -209,13 +211,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer.process(exchange -> {AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);LOG.fine("Received on sensor queue: " + event);- // Can either come from onUpdateSensor or sendAttributeUpdate- boolean isSensorUpdate = (boolean) exchange.getIn().getHeader("isSensorUpdate", true);- if (isSensorUpdate) {- processSensorUpdate(event);- } else {- updateAttributeValue(event, true);- }+ processSensorUpdate(event);});// Process attribute events from clients@@ -280,6 +276,40 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSermessageBrokerService.getProducerTemplate().sendBody(ASSET_QUEUE, attributeEvent);}+ /**+ * This should only be called by protocol implementations to request an update to+ * one of their own protocol configuration attributes. The {@link ProtocolAssetService}+ * interface was implemented here because the sendAttributeEvent already exists here+ * and there are already protocol related things here anyway.+ */+ // TODO: Need a way of restricting protocols to their own protocolConfigurations+ @Override+ public void updateProtocolConfiguration(AssetAttribute protocolConfiguration) {+ if (protocolConfiguration == null || !protocolConfiguration.getReference().isPresent()) {+ LOG.warning("Cannot update protocol configuration as it is not valid: " + protocolConfiguration);+ return;+ }++ AttributeRef protocolRef = protocolConfiguration.getReference().get();+ ServerAsset agent = assetStorageService.find(protocolRef.getEntityId(), true);+ if (agent == null || agent.getWellKnownType() != AssetType.AGENT || !agent.hasAttribute(protocolRef.getAttributeName())) {+ LOG.warning("Protocol configuration doesn't belong to a valid agent");+ return;+ }++ // Check protocol configuration has changed+ @SuppressWarnings("ConstantConditions")+ AssetAttribute oldProtocolConfiguration = agent.getAttribute(protocolRef.getAttributeName()).get();+ if (oldProtocolConfiguration.getObjectValue().equals(protocolConfiguration.getObjectValue())) {+ LOG.fine("Protocol configuration hasn't changed so nothing to do here");+ return;+ }++ agent.replaceAttribute(protocolConfiguration);+ LOG.fine("Updating agent protocol configuration: " + protocolRef);+ assetStorageService.merge(agent);+ }+/*** This is the entry point for any attribute value change event in the entire system.* <p>@@ -375,7 +405,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerOptional<AssetAttribute> protocolConfiguration =getAgentLink(attribute)- .flatMap(AgentService::getProtocolConfiguration);+ .flatMap(agentService::getProtocolConfiguration);if (!protocolConfiguration.isPresent()) {LOG.warning("Processing sensor update failed, linked agent protocol configuration not found: " + attributeEvent);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 bad0c5203..9f6fceb78 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@@ -45,29 +45,34 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait// 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.- onSensorUpdate(sendToActuatorEvents.last().getAttributeState())+ updateLinkedAttribute(sendToActuatorEvents.last().getAttributeState())}@Override- protected void sendToActuator(AttributeEvent event) {- LOG.info("Mock Protocol: sendToActuator")- sendToActuatorEvents.add(event)+ protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ LOG.info("Mock Protocol: linkProtocol")}@Override- protected void onAttributeAdded(AssetAttribute attribute, AssetAttribute protocolConfiguration) {+ protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ LOG.info("Mock Protocol: unlinkProtocol")+ }++ @Override+ protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {protocolDeployed = true- LOG.info("Mock Protocol: onAttributeAdded")+ LOG.info("Mock Protocol: linkAttribute")}@Override- protected void onAttributeUpdated(AssetAttribute attribute, AssetAttribute protocolConfiguration) {- LOG.info("Mock Protocol: onAttributeUpdated")+ protected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {+ LOG.info("Mock Protocol: unlinkAttribute")}@Override- protected void onAttributeRemoved(AssetAttribute attribute, AssetAttribute protocolConfiguration) {- LOG.info("Mock Protocol: onAttributeRemoved")+ protected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration) {+ LOG.info("Mock Protocol: processLinkedAttributeWrite")+ sendToActuatorEvents.add(event)}@Override@@ -162,7 +167,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitassert sendToActuatorEvents.size() == 1assert sendToActuatorEvents[0].entityId == mockThing.idassert sendToActuatorEvents[0].attributeName == "light1Toggle"- assert Values.getBoolean(sendToActuatorEvents[0].attributeState.currentValue.orElse(null)).orElse(null) == true+ assert Values.getBoolean(sendToActuatorEvents[0].attributeState.currentValue.orElse(null)).orElse(null)assert updatesPassedStartOfProcessingChain[0].processingStatus == AssetState.ProcessingStatus.COMPLETED}@@ -177,8 +182,8 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitassert updatesReachedEndOfProcessingChain.size() == 1assert updatesReachedEndOfProcessingChain[0].name == "Mock Thing Asset"assert updatesReachedEndOfProcessingChain[0].attributeName == "light1Toggle"- assert Values.getBoolean(updatesReachedEndOfProcessingChain[0].oldValue).orElse(null) == false- assert Values.getBoolean(updatesReachedEndOfProcessingChain[0].value).orElse(null) == true+ assert !Values.getBoolean(updatesReachedEndOfProcessingChain[0].oldValue).orElse(null)+ assert Values.getBoolean(updatesReachedEndOfProcessingChain[0].value).orElse(null)assert updatesReachedEndOfProcessingChain[0].processingStatus == AssetState.ProcessingStatus.COMPLETED}//endregiondiff --git a/model/src/main/java/org/openremote/model/attribute/AttributeExecuteStatus.java b/model/src/main/java/org/openremote/model/attribute/AttributeExecuteStatus.javaindex 05004f1ef..28d5a5ff6 100644--- a/model/src/main/java/org/openremote/model/attribute/AttributeExecuteStatus.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeExecuteStatus.java@@ -41,6 +41,11 @@ public enum AttributeExecuteStatus {*/REQUEST_CANCEL(true),+ /**+ * Ready to be executed+ */+ READY(false),+/*** Execution completed*/@@ -59,7 +64,12 @@ public enum AttributeExecuteStatus {/*** Command produced an error*/- ERROR(false);+ ERROR(false),++ /**+ * Execution has been disabled+ */+ DISABLED(false);private boolean write;// Prevents cloning of values each time fromString is called