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
Opened up protocol naming to 3rd party namespaces, fixed wrong Main service startup order (protocols must start before agent service)
Christian Bauer000873d94d53
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.javaindex 5a76d5085..cc3439a97 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java@@ -81,7 +81,7 @@ public abstract class AbstractProtocol implements Protocol {from(ACTUATOR_TOPIC).routeId("Actuator-" + getProtocolName()).process(exchange -> {- String protocolName = exchange.getIn().getHeader("Protocol", String.class);+ String protocolName = exchange.getIn().getHeader(Protocol.ACTUATOR_TOPIC_TARGET_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 implementorssynchronized (linkedAttributes) {diff --git a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.javaindex e811b48da..572e490c2 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java@@ -20,98 +20,103 @@package org.openremote.agent3.protocol;import org.openremote.container.ContainerService;-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.AttributeType;import org.openremote.model.attribute.MetaItem;+import org.openremote.model.value.ValueType;import java.util.Collection;import java.util.function.Consumer;/**- * 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>- * The protocol should check the {@link AssetAttribute#isEnabled()} status of the protocolConfiguration- * to determine whether or not it should be running or stopped.- * <p>- * {@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>- * 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 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.+ * A protocol is a thread-safe singleton {@link ContainerService} that connects devices and+ * services to the context broker. Each protocol implementation must have a unique+ * resource name (RfC 2141 URN) in a VM.+ * <h3>Configuring protocol instances</h3>+ * A protocol implementation must support multiple protocol configurations and therefore+ * support multiple logical instances. A protocol 'instance' can be 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 protocol configuration is loaded/created for a protocol then the+ * {@link #linkProtocolConfiguration(AssetAttribute, Consumer)} method will be called.+ * The protocol should check the {@link AssetAttribute#isEnabled()} status of the protocol+ * configuration to determine whether or not the logical instance should be running or stopped.+ * <p>+ * The protocol is responsible for calling the provided consumer whenever the status of the+ * logical instance changes (e.g. if the configuration 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).+ * <h3>Connecting attributes to actuators and sensors</h3>+ * {@link AssetAttribute}s of {@link Asset}s can be linked to a protocol configuration+ * instance by creating an {@link AssetMeta#AGENT_LINK} {@link MetaItem} on an attribute.+ * Besides the {@link AssetMeta#AGENT_LINK}, other protocol-specific meta items may also be+ * required when an asset attribute is linked to a protocol configuration instance.+ * Attributes linked to a protocol configuration instance will get passed to the protocol via+ * a call to {@link #linkAttributes(Collection, AssetAttribute)}.+ * <p>+ * The protocol handles read and write of linked attributes:+ * <p>+ * If the actual state of the device (or service) changes, the linked protocol writes the new+ * state into the attribute value and notifies the context broker of the change. A protocol updates+ * a linked attributes' value by sending an {@link AttributeEvent} messages on the+ * {@link #SENSOR_QUEUE}.+ * <p>+ * If the user writes a new value into the linked attribute, the protocol translates this value+ * change into a device (or service) action. Write operations on attributes linked to a protocol+ * configuration can be consumed by the protocol on the {@link #ACTUATOR_TOPIC} where the message+ * body will be an {@link AttributeEvent}. Each message also contains the target protocol name in+ * header {@link #ACTUATOR_TOPIC_TARGET_PROTOCOL}.+ * <p>+ * Data type conversion is also delegated to the protocol implementation: If an attribute has a particular+ * {@link AttributeType} and therefore a base {@link ValueType}, the protocol implementation must+ * receive and send value change messages with values of that type.+ * <p>+ * NOTE: That {@link #linkProtocolConfiguration} will always be called+ * before {@link #linkAttributes} and {@link #unlinkAttributes} will always be called before+ * {@link #unlinkProtocolConfiguration}.* <p>* The following summarises the method calls protocols should expect:* <p>- * Protocol Configuration is created/loaded:+ * Protocol configuration (logical instance) is created/loaded:* <ol>- * <li>{@link #linkProtocolConfiguration(AssetAttribute, Consumer)}</li>- * <li>{@link #linkAttributes(Collection, AssetAttribute)}</li>+ * <li>{@link #linkProtocolConfiguration(AssetAttribute, Consumer)}</li>+ * <li>{@link #linkAttributes(Collection, AssetAttribute)}</li>* </ol>* <p>- * Protocol Configuration is modified:+ * Protocol configuration (logical instance) 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>+ * <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:+ * Protocol configuration (logical instance) is removed:* <ol>- * <li>{@link #unlinkAttributes(Collection, AssetAttribute)}</li>- * <li>{@link #unlinkProtocolConfiguration(AssetAttribute)}</li>+ * <li>{@link #unlinkAttributes(Collection, AssetAttribute)}</li>+ * <li>{@link #unlinkProtocolConfiguration(AssetAttribute)}</li>* </ol>* <p>- * Linked Attribute is created/loaded:+ * Attribute linked to protocol configuration is created/loaded:* <ol>- * <li>{@link #linkAttributes(Collection, AssetAttribute)}</li>+ * <li>{@link #linkAttributes(Collection, AssetAttribute)}</li>* </ol>* <p>- * Linked Attribute is modified:+ * Attribute linked to protocol configuration is modified:* <ol>- * <li>{@link #unlinkAttributes(Collection, AssetAttribute)}</li>- * <li>{@link #linkAttributes(Collection, AssetAttribute)}</li>+ * <li>{@link #unlinkAttributes(Collection, AssetAttribute)}</li>+ * <li>{@link #linkAttributes(Collection, AssetAttribute)}</li>* </ol>* <p>- * Linked Attribute is removed:+ * Attribute link to protocol configuration is removed:* <ol>- * <li>{@link #unlinkAttributes(Collection, AssetAttribute)}</li>+ * <li>{@link #unlinkAttributes(Collection, AssetAttribute)}</li>* </ol>*/public interface Protocol extends ContainerService {@@ -122,8 +127,8 @@ public interface Protocol extends ContainerService {enum DeploymentStatus {/**- * Protocol configuration has not yet been linked (i.e. {@link #linkProtocolConfiguration(AssetAttribute, Consumer)}- * hasn't yet been called for the configuration.+ * Protocol configuration has not yet been linked (i.e. {@link #linkProtocolConfiguration}+ * hasn't yet been called for the configuration).*/UNLINKED,@@ -145,7 +150,7 @@ public interface Protocol extends ContainerService {/*** 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).+ * with a value of <code>false</code>).*/LINKED_DISABLED,@@ -163,6 +168,8 @@ public interface Protocol extends ContainerService {UPDATING}+ String ACTUATOR_TOPIC_TARGET_PROTOCOL = "Protocol";+// 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)diff --git a/manager/server/src/main/java/org/openremote/manager/server/Main.java b/manager/server/src/main/java/org/openremote/manager/server/Main.javaindex 9a9a19934..753736ac8 100644--- a/manager/server/src/main/java/org/openremote/manager/server/Main.java+++ b/manager/server/src/main/java/org/openremote/manager/server/Main.java@@ -65,11 +65,11 @@ public class Main {new RulesService(),new AssetStorageService(),new AssetDatapointService(),- new AssetProcessingService(),- new AgentService()+ new AssetProcessingService()));ServiceLoader.load(Protocol.class).forEach(this::add);addAll(Arrays.asList(+ new AgentService(),new MapService(),new NotificationService(),new MessageBrokerService(),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.javaindex 647ce80c9..2af715745 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.*;+import org.openremote.model.AbstractValueTimestampHolder;import org.openremote.model.asset.*;import org.openremote.model.asset.agent.AgentLink;import org.openremote.model.asset.agent.ProtocolConfiguration;@@ -55,6 +55,7 @@ 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;+import static org.openremote.model.util.TextUtil.isValidURN;/*** Finds all {@link AssetType#AGENT} and {@link AssetType#THING} assets and starts the protocols for them.@@ -87,12 +88,16 @@ public class AgentService extends RouteBuilder implements ContainerService, ConsdiscoveredProtocols.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 (isNullOrEmpty(discoveredProtocol.getProtocolName())+ || !isValidURN(discoveredProtocol.getProtocolName()))+ throw new IllegalStateException(+ "Protocol name is not a valid URN: " + discoveredProtocol.getClass()+ );if (protocols.containsKey(discoveredProtocol.getProtocolName()))- throw new IllegalStateException("A protocol with the name '" + discoveredProtocol.getProtocolName() + "' has already been loaded: " + discoveredProtocol.getClass());-+ throw new IllegalStateException(+ "A protocol with the name '" + discoveredProtocol.getProtocolName()+ + "' has already been loaded: " + discoveredProtocol.getClass()+ );protocols.put(discoveredProtocol.getProtocolName(), discoveredProtocol);});@@ -500,7 +505,7 @@ public class AgentService extends RouteBuilder implements ContainerService, ConsmessageBrokerService.getProducerTemplate().sendBodyAndHeader(ACTUATOR_TOPIC,event.get(),- "Protocol",+ Protocol.ACTUATOR_TOPIC_TARGET_PROTOCOL,protocolConfiguration.getValueAsString().orElse(""));} else {diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.javaindex 1264b250e..4753589e8 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java@@ -140,7 +140,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {agent.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));agent.setAttributes(initProtocolConfiguration(new AssetAttribute(agentProtocolConfigName), SimulatorProtocol.PROTOCOL_NAME)- .setMeta(+ .addMeta(new MetaItem(SimulatorProtocol.CONFIG_MODE,Values.create(SimulatorProtocol.Mode.WRITE_THROUGH_DELAYED.toString())@@ -564,25 +564,25 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment1Scenes.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment1Scenes.setAttributes(initProtocolConfiguration(new AssetAttribute("homeScene"), MacroProtocol.PROTOCOL_NAME)- .setMeta(+ .addMeta(new MacroAction(new AttributeState(new AttributeRef(apartment1Id, "alarmEnabled"), Values.create(false))).toMetaItem(),new MacroAction(new AttributeState(new AttributeRef(apartment1Id, "lastExecutedScene"), Values.create("HOME"))).toMetaItem(),new MacroAction(new AttributeState(new AttributeRef(apartment1LivingroomThermostatId, "targetTemperature"), Values.create(21d))).toMetaItem()),initProtocolConfiguration(new AssetAttribute("awayScene"), MacroProtocol.PROTOCOL_NAME)- .setMeta(+ .addMeta(new MacroAction(new AttributeState(new AttributeRef(apartment1Id, "alarmEnabled"), Values.create(true))).toMetaItem(),new MacroAction(new AttributeState(new AttributeRef(apartment1Id, "lastExecutedScene"), Values.create("AWAY"))).toMetaItem(),new MacroAction(new AttributeState(new AttributeRef(apartment1LivingroomThermostatId, "targetTemperature"), Values.create(15d))).toMetaItem()),initProtocolConfiguration(new AssetAttribute("eveningScene"), MacroProtocol.PROTOCOL_NAME)- .setMeta(+ .addMeta(new MacroAction(new AttributeState(new AttributeRef(apartment1Id, "alarmEnabled"), Values.create(false))).toMetaItem(),new MacroAction(new AttributeState(new AttributeRef(apartment1Id, "lastExecutedScene"), Values.create("EVENING"))).toMetaItem(),new MacroAction(new AttributeState(new AttributeRef(apartment1LivingroomThermostatId, "targetTemperature"), Values.create(22d))).toMetaItem()),initProtocolConfiguration(new AssetAttribute("nightScene"), MacroProtocol.PROTOCOL_NAME)- .setMeta(+ .addMeta(new MacroAction(new AttributeState(new AttributeRef(apartment1Id, "alarmEnabled"), Values.create(true))).toMetaItem(),new MacroAction(new AttributeState(new AttributeRef(apartment1Id, "lastExecutedScene"), Values.create("NIGHT"))).toMetaItem(),new MacroAction(new AttributeState(new AttributeRef(apartment1LivingroomThermostatId, "targetTemperature"), Values.create(19d))).toMetaItem()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 950c6a117..c4f87e102 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@@ -32,7 +32,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitdef conditions = new PollingConditions(timeout: 10, delay: 1)and: "a mock protocol"- def mockProtocolName = Constants.PROTOCOL_NAMESPACE + ":mockProtocol"+ def mockProtocolName = "urn:myCustom:mockProtocol"def protocolDeployed = falseList<AttributeEvent> sendToActuatorEvents = []def mockProtocol = new AbstractProtocol() {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.groovyindex dc8fcbfb3..3c5ce7d13 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@@ -51,7 +51,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {def conditions = new PollingConditions(timeout: 10, delay: 1)and: "a mock protocol"- def mockProtocolName = Constants.PROTOCOL_NAMESPACE + ":mockProtocol"+ def mockProtocolName = "urn:myCustom:mockProtocol"Map<String, Integer> protocolExpectedLinkedAttributeCount = [:]protocolExpectedLinkedAttributeCount['mockConfig1'] = 2protocolExpectedLinkedAttributeCount['mockConfig2'] = 2@@ -140,16 +140,16 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {mockAgent.setType(AssetType.AGENT)mockAgent.setAttributes(ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute("mockConfig1"), mockProtocolName)- .setMeta(+ .addMeta(new MetaItem("MOCK_REQUIRED_META", Values.create(true))),ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute("mockConfig2"), mockProtocolName),ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute("mockConfig3"), mockProtocolName)- .setMeta(+ .addMeta(new MetaItem("MOCK_THROW_EXCEPTION", Values.create(""))),ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute("mockConfig4"), mockProtocolName)- .setMeta(+ .addMeta(new MetaItem("MOCK_REQUIRED_META", Values.create(true)),new MetaItem(AssetMeta.ENABLED, Values.create(false)))diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AssetAttribute.javaindex be058a130..031ef5d08 100644--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java@@ -118,6 +118,13 @@ public class AssetAttribute extends Attribute {return this;}+ public AssetAttribute addMeta(MetaItem... meta) {+ if (meta != null) {+ getMeta().addAll(Arrays.asList(meta));+ }+ return this;+ }+/*** @return The current value and its timestamp represented as an attribute event.*/@@ -336,9 +343,17 @@ public class AssetAttribute extends Attribute {return copy;}-// ----------------------------------------------------// FUNCTIONAL METHODS BELOW-// ---------------------------------------------------+ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "assetId='" + assetId + '\'' ++ ", name='" + name + '\'' ++ "} " + objectValue.toJson();+ }++ // ---------------------------------------------------+ // FUNCTIONAL METHODS BELOW+ // ---------------------------------------------------/*** Returns non-private attributes with non-private meta items.diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.javaindex ad6ae3614..aa10fb5cf 100644--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java@@ -22,6 +22,7 @@ package org.openremote.model.asset;import org.openremote.model.attribute.AttributeExecuteStatus;import org.openremote.model.attribute.HasMetaName;import org.openremote.model.attribute.MetaItem;+import org.openremote.model.value.Value;import org.openremote.model.value.ValueType;import java.util.ArrayList;@@ -40,6 +41,12 @@ import static org.openremote.model.util.TextUtil.isNullOrEmpty;*/public enum AssetMeta implements HasMetaName {+ /**+ * Marks an attribute of an agent asset as a {@link org.openremote.model.asset.agent.ProtocolConfiguration}.+ * The attribute value is a protocol URN.+ */+ PROTOCOL_CONFIGURATION(ASSET_META_NAMESPACE + ":protocolConfiguration", new Access(false, false, true), ValueType.BOOLEAN),+/*** Links the attribute to an agent's {@link org.openremote.model.asset.agent.ProtocolConfiguration}, connecting it* to a sensor and/or actuator.@@ -112,26 +119,27 @@ public enum AssetMeta implements HasMetaName {STORE_DATA_POINTS(ASSET_META_NAMESPACE + ":storeDataPoints", new Access(true, false, true), ValueType.BOOLEAN),/**- * Should attribute writes be processed by the rules engines as facts in knowledge sessions, with a lifecycle- * that reflects the state of the asset attribute (the {@link AssetState} facts in the rules sessions are kept- * in sync with asset changes). If you want two types of facts in your rules knowledge session for a single+ * Should attribute writes be processed by the rules engines as {@link AssetState} facts in knowledge sessions,+ * with a lifecycle that reflects the state of the asset attribute. The state facts in the rules sessions are kept+ * in sync with asset changes: For an attribute there will always be a single fact that is updated+ * when the attribute is updated. If you want two types of facts in your rules knowledge session for a single* attribute, with state and event behavior, combine this with {@link #RULE_EVENT}.*/RULE_STATE(ASSET_META_NAMESPACE + ":ruleState", new Access(true, false, true), ValueType.BOOLEAN),/**- * Should attribute writes be processed by the rules engines as events in knowledge sessions with limited- * lifecycle that reflects how the event is processed (the {@link AssetEvent} facts- * in the rules sessions are expired automatically after a certain time and/or if they can no longer be matched- * by time operations). If you want two types of facts in your rules knowledge session for a single attribute,- * with state and event behavior, combine this with {@link #RULE_STATE\}.+ * Should attribute writes be processed by the rules engines as events in knowledge sessions. Any attribute+ * update will be inserted as an {@link AssetEvent} fact in the rules sessions, these events are expired+ * automatically after a defined time and/or if they can no longer be matched by rule LHS time constraints.+ * If you want two types of facts in your rules knowledge session for a single attribute, with state and event+ * behavior, combine this with {@link #RULE_STATE}.*/RULE_EVENT(ASSET_META_NAMESPACE + ":ruleEvent", new Access(true, false, true), ValueType.BOOLEAN),/**- * Override rules event expiration, for example "1h30m". Remove {@link AssetEvent}- * facts from the rules sessions if they are older than this value (using event source timestamp, not event- * processing time).+ * Set maximum lifetime of {@link AssetEvent} facts in knowledge sessions, for example "1h30m". The rules+ * engine will remove {@link AssetEvent} facts from the rules sessions if they are older than this value+ * (using event source timestamp, not event processing time).*/RULE_EVENT_EXPIRES(ASSET_META_NAMESPACE + ":ruleEventExpires", new Access(true, false, true), ValueType.STRING),@@ -229,8 +237,8 @@ public enum AssetMeta implements HasMetaName {}/**- * In theory, meta item values can be of any JSON type. In practice, these are the- * types we can edit/have editor UI for. We inspect the actual JSON value and+ * In theory, meta item values can be of any {@link ValueType}. In practice, these+ * are the types we can edit/have editor UI for.*/public enum EditableType {STRING("String", ValueType.STRING),diff --git a/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java b/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.javaindex cba6ee0bc..3f8432b6f 100644--- a/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java+++ b/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java@@ -19,32 +19,28 @@*/package org.openremote.model.asset.agent;-import org.openremote.model.Constants;import org.openremote.model.asset.AssetAttribute;import org.openremote.model.attribute.AttributeType;-import org.openremote.model.attribute.Meta;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.util.TextUtil;import org.openremote.model.value.Values;-import java.util.Locale;import java.util.Optional;-import java.util.function.Predicate;import java.util.function.UnaryOperator;+import static org.openremote.model.asset.AssetMeta.PROTOCOL_CONFIGURATION;+import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;+/**- * Agent attributes can be named protocol configurations.- * <p>- * A protocol configuration attribute value must be a URN string representation- * starting with {@link Constants#PROTOCOL_NAMESPACE}.+ * Agent attributes can be named protocol configurations, defining a logical instance of a protocol.* <p>- * TODO: How can we integrate 3rd party protocol namespaces?+ * A protocol configuration attribute must be marked+ * {@link org.openremote.model.asset.AssetMeta#PROTOCOL_CONFIGURATION} and its+ * value must be valid RfC 2141 URN.* <p>- * Configuration details are managed as {@link Meta} of the attribute.+ * Protocol-specific settings and details are managed as {@link MetaItem} of the attribute.*/final public class ProtocolConfiguration {- public static final Predicate<String> PROTOCOL_NAME_VALIDATOR = value ->- value != null && value- .toLowerCase(Locale.ROOT)- .startsWith(Constants.PROTOCOL_NAMESPACE);private ProtocolConfiguration() {}@@ -53,11 +49,11 @@ final public class ProtocolConfiguration {if (attribute == null) {return null;}-isValidProtocolNameOrThrow(protocolName);attribute.setEnabled(true);attribute.setTypeAndClearValue(AttributeType.STRING);attribute.setValue(Values.create(protocolName));+ attribute.getMeta().add(new MetaItem(PROTOCOL_CONFIGURATION, Values.create(true)));return attribute;}@@ -66,23 +62,17 @@ final public class ProtocolConfiguration {}public static boolean isValidProtocolName(String protocolName) {- return PROTOCOL_NAME_VALIDATOR.test(protocolName);+ return TextUtil.isValidURN(protocolName);}public static void isValidProtocolNameOrThrow(String protocolName) throws IllegalArgumentException {if (!isValidProtocolName(protocolName)) {- throw new IllegalArgumentException("Protocol name must start with the protocol URN prefix: " + Constants.PROTOCOL_NAMESPACE);+ throw new IllegalArgumentException("Protocol name must start with 'urn:' but is: " + protocolName);}}public static boolean isProtocolConfiguration(AssetAttribute attribute) {- return getProtocolName(attribute)- .isPresent();- }-- // TODO: Should this be able to validate the protocol name- public static boolean isValidProtocolConfiguration(AssetAttribute attribute) {- return isProtocolConfiguration(attribute);+ return getProtocolName(attribute).isPresent() && attribute.getMetaStream().anyMatch(isMetaNameEqualTo(PROTOCOL_CONFIGURATION));}public static Optional<String> getProtocolName(AssetAttribute attribute) {diff --git a/model/src/main/java/org/openremote/model/util/TextUtil.java b/model/src/main/java/org/openremote/model/util/TextUtil.javaindex 10c221a44..ad1c6982d 100644--- a/model/src/main/java/org/openremote/model/util/TextUtil.java+++ b/model/src/main/java/org/openremote/model/util/TextUtil.java@@ -19,12 +19,19 @@*/package org.openremote.model.util;+import com.google.gwt.regexp.shared.RegExp;+import java.util.Locale;import java.util.Objects;import java.util.Optional;+import java.util.function.Predicate;public class TextUtil {+ public static final String URN_PATTERN = "^urn:[a-zA-Z0-9][a-zA-Z0-9-]{0,31}:([a-zA-Z0-9()+,\\-.:=@;$_!*']|%[0-9a-f]{2})+$";+ public static final RegExp URN_REGEXP = RegExp.compile(URN_PATTERN);+ public static final Predicate<String> URN_VALIDATOR = name -> !isNullOrEmpty(name) && URN_REGEXP.test(name);+/*** Converts a String which represents a pollingInterval into an int which can be used as delay* for Thread.sleep(); <p>@@ -97,7 +104,7 @@ public class TextUtil {/*** Transforms <code>EXFooBar123</code> into <code>ex-foo-bar-123</code> and- * <code>attributeX</code> into <code>attribute-x</code> without regex (GWT!)+ * <code>attributeX</code> into <code>attribute-x</code> without regex.*/public static String toLowerCaseDash(String camelCase) {if (camelCase == null)@@ -188,4 +195,8 @@ public class TextUtil {return str;}++ public static boolean isValidURN(String name) {+ return URN_VALIDATOR.test(name);+ }}diff --git a/profile/demo.yml b/profile/demo.ymlindex 1c4f5197a..7afc96690 100644--- a/profile/demo.yml+++ b/profile/demo.yml@@ -57,7 +57,9 @@ services:# these tasks will clean and populate Keycloak and the Manager database with demo data!SETUP_INIT_CLEAN_DATABASE: 'true'SETUP_KEYCLOAK_ADMIN_PASSWORD: secret- SETUP_IMPORT_DEMO_DATA: 'true'+ SETUP_IMPORT_DEMO_USERS: 'true'+ SETUP_IMPORT_DEMO_ASSETS: 'true'+ SETUP_IMPORT_DEMO_RULES: 'true'# The public host name of this OpenRemote installation. This name is used in bearer tokens# and must be the name you access the web services under. If you are using Docker Toolbox,