Skip to content

armgit / core

Public Imported from GitHub
0

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

Implemented processing of attribute updates from client API

Christian Bauer87b8ec14f847
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.java
index 78bcb859b..b7e172797 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
@@ -42,7 +42,16 @@ public class SimulatorProtocol extends AbstractProtocol {
private static final Logger LOG = Logger.getLogger(org.openremote.agent3.protocol.simulator.SimulatorProtocol.class.getName());
public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":simulator";
- public static final String META_NAME_ELEMENT = PROTOCOL_NAME + ":element";
+
+ /**
+ * Required meta item, the simulator element that should be used, see subclasses of {@link SimulatorElement}.
+ */
+ public static final String SIMULATOR_ELEMENT = PROTOCOL_NAME + ":element";
+
+ /**
+ * Optional (defaults to false) meta item, whether actuator writes should immediately be reflected as sensor reads.
+ */
+ public static final String SIMULATOR_REFLECT_ACTUATOR_WRITES = PROTOCOL_NAME + ":reflectActuatorWrites";
static final protected Map<AttributeRef, SimulatorElement> elements = new HashMap<>();
@@ -53,9 +62,19 @@ public class SimulatorProtocol extends AbstractProtocol {
@Override
protected void onAttributeAdded(ThingAttribute attribute) {
- String elementType = attribute.firstMetaItemOrThrow(META_NAME_ELEMENT).getValueAsString();
- SimulatorElement element = createElement(elementType, attribute);
- element.setState(attribute.getValue());
+ String elementType = attribute.firstMetaItemOrThrow(SIMULATOR_ELEMENT).getValueAsString();
+
+ boolean reflectActuatorWrites =
+ attribute.hasMetaItem(SIMULATOR_REFLECT_ACTUATOR_WRITES)
+ && attribute.firstMetaItem(SIMULATOR_REFLECT_ACTUATOR_WRITES).isValueTrue();
+
+ SimulatorElement element = createElement(elementType, reflectActuatorWrites, attribute);
+ try {
+ element.setState(attribute.getValue());
+ } catch (IllegalArgumentException ex) {
+ throw new RuntimeException("Error setting initial state of: " + attribute, ex);
+ }
+
LOG.info("Putting element '" + element + "' for: " + attribute);
elements.put(attribute.getAttributeRef(), element);
}
@@ -75,20 +94,28 @@ public class SimulatorProtocol extends AbstractProtocol {
putState(event.getAttributeState(), false);
}
+ /**
+ * Call this to simulate a sensor read.
+ */
public void putState(String entityId, String attributeName, JsonValue value) {
putState(new AttributeState(new AttributeRef(entityId, attributeName), value), true);
}
+ /**
+ * Call this to simulate a sensor read.
+ */
public void putState(AttributeRef attributeRef, JsonValue value) {
putState(new AttributeState(attributeRef, value), true);
}
/**
- * @param isSensorUpdate <code>true</code> if an {@link AttributeState} message should be produced
+ * Call this to simulate a sensor read or actuator write.
+ *
+ * @param simulateSensorRead <code>true</code> if an {@link AttributeEvent} sensor update should be produced
*/
- public void putState(AttributeState attributeState, boolean isSensorUpdate) {
+ public void putState(AttributeState attributeState, boolean simulateSensorRead) {
synchronized (elements) {
- LOG.info("Put simulator state (isSensorUpdate: " + isSensorUpdate + "): " + attributeState);
+ LOG.info("Put simulator state: " + attributeState);
AttributeRef attributeRef = attributeState.getAttributeRef();
SimulatorElement element = elements.get(attributeRef);
@@ -97,8 +124,11 @@ public class SimulatorProtocol extends AbstractProtocol {
element.setState(attributeState.getValue());
- if (isSensorUpdate) {
- LOG.info("Propagating state change as sensor update: " + element);
+ if (simulateSensorRead) {
+ LOG.info("Propagating state change as sensor read: " + element);
+ onSensorUpdate(new AttributeEvent(attributeState));
+ } else if (element.isReflectActuatorWrites()) {
+ LOG.info("Reflecting actuator write as sensor read: " + element);
onSensorUpdate(new AttributeEvent(attributeState));
}
}
@@ -117,22 +147,22 @@ public class SimulatorProtocol extends AbstractProtocol {
}
}
- protected SimulatorElement createElement(String elementType, ThingAttribute attribute) {
+ protected SimulatorElement createElement(String elementType, boolean reflectActuatorWrites, ThingAttribute attribute) {
switch (elementType.toLowerCase(Locale.ROOT)) {
- case "switch":
- return new SwitchSimulatorElement();
- case "integer":
- return new IntegerSimulatorElement();
- case "decimal":
- return new DecimalSimulatorElement();
- case "range":
+ case SwitchSimulatorElement.ELEMENT_NAME:
+ return new SwitchSimulatorElement(reflectActuatorWrites);
+ case IntegerSimulatorElement.ELEMENT_NAME_INTEGER:
+ return new IntegerSimulatorElement(reflectActuatorWrites);
+ case DecimalSimulatorElement.ELEMENT_NAME:
+ return new DecimalSimulatorElement(reflectActuatorWrites);
+ case IntegerSimulatorElement.ELEMENT_NAME_RANGE:
MetaItem minItem = attribute.firstMetaItem(RANGE_MIN);
MetaItem maxItem = attribute.firstMetaItem(RANGE_MAX);
double min = minItem != null ? minItem.getValueAsInteger() : 0;
double max = maxItem != null ? maxItem.getValueAsInteger() : 100;
- return new IntegerSimulatorElement(min, max);
- case "color":
- return new ColorSimulatorElement();
+ return new IntegerSimulatorElement(reflectActuatorWrites, min, max);
+ case ColorSimulatorElement.ELEMENT_NAME:
+ return new ColorSimulatorElement(reflectActuatorWrites);
default:
throw new UnsupportedOperationException("Can't simulate element '" + elementType + "': " + attribute);
}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java
index 77c9d225e..e7424ea95 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java
@@ -23,7 +23,9 @@ import org.openremote.model.AttributeType;
public class ColorSimulatorElement extends SimulatorElement {
- public ColorSimulatorElement() {
- super(AttributeType.INTEGER_ARRAY);
+ public static final String ELEMENT_NAME = "color";
+
+ public ColorSimulatorElement(boolean reflectActuatorWrites) {
+ super(AttributeType.INTEGER_ARRAY, reflectActuatorWrites);
}
}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/DecimalSimulatorElement.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/DecimalSimulatorElement.java
index 9899624bd..71a967795 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/DecimalSimulatorElement.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/DecimalSimulatorElement.java
@@ -23,8 +23,9 @@ import org.openremote.model.AttributeType;
public class DecimalSimulatorElement extends SimulatorElement {
- public DecimalSimulatorElement() {
- super(AttributeType.DECIMAL);
- }
+ public static final String ELEMENT_NAME = "decimal";
+ public DecimalSimulatorElement(boolean reflectActuatorWrites) {
+ super(AttributeType.DECIMAL, reflectActuatorWrites);
+ }
}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/IntegerSimulatorElement.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/IntegerSimulatorElement.java
index b4b677f13..677f9731d 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/IntegerSimulatorElement.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/IntegerSimulatorElement.java
@@ -24,15 +24,18 @@ import org.openremote.model.AttributeType;
public class IntegerSimulatorElement extends SimulatorElement {
+ public static final String ELEMENT_NAME_INTEGER = "integer";
+ public static final String ELEMENT_NAME_RANGE = "range";
+
final protected Double min;
final protected Double max;
- public IntegerSimulatorElement() {
- this(null, null);
+ public IntegerSimulatorElement(boolean reflectActuatorWrites) {
+ this(reflectActuatorWrites, null, null);
}
- public IntegerSimulatorElement(Double min, Double max) {
- super(AttributeType.INTEGER);
+ public IntegerSimulatorElement(boolean reflectActuatorWrites, Double min, Double max) {
+ super(AttributeType.INTEGER, reflectActuatorWrites);
this.min = min;
this.max = max;
}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SimulatorElement.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SimulatorElement.java
index b30d7a4b1..c51569927 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SimulatorElement.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SimulatorElement.java
@@ -27,10 +27,13 @@ import org.openremote.model.AttributeType;
public abstract class SimulatorElement<T> {
final protected AttributeType expectedType;
+ final protected boolean reflectActuatorWrites;
+
protected JsonValue state = Json.createNull();
- public SimulatorElement(AttributeType expectedType) {
+ public SimulatorElement(AttributeType expectedType, boolean reflectActuatorWrites) {
this.expectedType = expectedType;
+ this.reflectActuatorWrites = reflectActuatorWrites;
}
public JsonValue getState() {
@@ -45,10 +48,17 @@ public abstract class SimulatorElement<T> {
if (isValid(state)) {
this.state = state;
} else {
- throw new IllegalArgumentException("Invalid state, expected JSON type '" + expectedType + "': " + state.getType());
+ throw new IllegalArgumentException(
+ "Invalid state, expected JSON type '" + expectedType + "' but got '" + state.getType() + "' on: " + this
+ );
}
}
+
+ public boolean isReflectActuatorWrites() {
+ return reflectActuatorWrites;
+ }
+
protected boolean isValid(JsonValue value) {
return value == null || value.getType() == JsonType.NULL || value.getType() == expectedType.getJsonType();
}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SwitchSimulatorElement.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SwitchSimulatorElement.java
index 5b3c33c7c..f459e5d4e 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SwitchSimulatorElement.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SwitchSimulatorElement.java
@@ -23,7 +23,9 @@ import org.openremote.model.AttributeType;
public class SwitchSimulatorElement extends SimulatorElement {
- public SwitchSimulatorElement() {
- super(AttributeType.BOOLEAN);
+ public static final String ELEMENT_NAME = "switch";
+
+ public SwitchSimulatorElement(boolean reflectActuatorWrites) {
+ super(AttributeType.BOOLEAN, reflectActuatorWrites);
}
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetActivity.java
index b954da7ce..e70385ae9 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetActivity.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetActivity.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016, OpenRemote Inc.
+ * Copyright 2017, OpenRemote Inc.
*
* See the CONTRIBUTORS.txt file in the distribution for a
* full listing of individual contributors.
@@ -25,12 +25,12 @@ import org.openremote.manager.client.assets.AssetMapper;
import org.openremote.manager.client.assets.AssetsDashboardPlace;
import org.openremote.manager.client.assets.browser.AssetBrowser;
import org.openremote.manager.client.assets.browser.AssetBrowsingActivity;
+import org.openremote.manager.client.event.ShowInfoEvent;
import org.openremote.manager.client.event.bus.EventBus;
import org.openremote.manager.client.event.bus.EventRegistration;
import org.openremote.manager.client.interop.elemental.JsonObjectMapper;
import org.openremote.manager.client.widget.AttributesEditor;
import org.openremote.manager.shared.asset.AssetResource;
-import org.openremote.manager.client.event.ShowInfoEvent;
import org.openremote.manager.shared.map.MapResource;
import org.openremote.model.Attributes;
import org.openremote.model.asset.Asset;
@@ -210,9 +210,7 @@ public class AssetActivity
readParent();
environment.getRequestService().execute(
assetMapper,
- requestParams -> {
- assetResource.update(requestParams, assetId, asset);
- },
+ requestParams -> assetResource.update(requestParams, assetId, asset),
204,
() -> {
view.setFormBusy(false);
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowsingActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowsingActivity.java
index 734959fef..b5c8329e6 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowsingActivity.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowsingActivity.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016, OpenRemote Inc.
+ * Copyright 2017, OpenRemote Inc.
*
* See the CONTRIBUTORS.txt file in the distribution for a
* full listing of individual contributors.
@@ -20,20 +20,20 @@
package org.openremote.manager.client.assets.browser;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
-import org.openremote.model.Consumer;
import org.openremote.manager.client.Environment;
import org.openremote.manager.client.assets.AssetMapper;
import org.openremote.manager.client.event.bus.EventBus;
import org.openremote.manager.client.event.bus.EventRegistration;
import org.openremote.manager.client.mvp.AppActivity;
import org.openremote.manager.client.util.TextUtil;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetInfo;
import org.openremote.manager.shared.asset.AssetResource;
-import org.openremote.model.asset.AssetType;
import org.openremote.manager.shared.map.GeoJSON;
import org.openremote.manager.shared.map.GeoJSONFeature;
import org.openremote.manager.shared.map.GeoJSONGeometry;
+import org.openremote.model.Consumer;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetInfo;
+import org.openremote.model.asset.AssetType;
import java.util.Collection;
import java.util.logging.Logger;
@@ -146,7 +146,7 @@ abstract public class AssetBrowsingActivity<V extends AssetBrowsingView, T exten
assetMapper,
requestParams -> assetResource.get(requestParams, id),
200,
- assetConsumer::accept,
+ assetConsumer,
ex -> handleRequestException(ex, environment)
);
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
index eea4a8395..369def13e 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
@@ -148,7 +148,7 @@ public class AgentService extends RouteBuilder implements ContainerService {
protocol.linkAttributes(attributes.get(protocolName));
} catch (Exception ex) {
// TODO: Better error handling?
- LOG.log(Level.INFO, "Ignoring error on attribute unlink for: " + thing, ex);
+ LOG.log(Level.WARNING, "Ignoring error on attribute link for: " + thing, ex);
}
}
}
@@ -164,7 +164,7 @@ public class AgentService extends RouteBuilder implements ContainerService {
protocol.unlinkAttributes(thing.getId());
} catch (Exception ex) {
// TODO: Better error handling?
- LOG.log(Level.INFO, "Ignoring error on attribute unlink for: " + thing, ex);
+ LOG.log(Level.WARNING, "Ignoring error on attribute unlink for: " + thing, ex);
}
}
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java
index 1926c899d..44a03f0b4 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
@@ -23,14 +23,14 @@ import org.apache.camel.builder.RouteBuilder;
import org.openremote.agent3.protocol.Protocol;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
+import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.message.MessageBrokerSetupService;
+import org.openremote.container.persistence.PersistenceEvent;
import org.openremote.manager.server.agent.ThingAttributes;
import org.openremote.manager.server.datapoint.AssetDatapointService;
import org.openremote.manager.server.rules.AssetRulesService;
-import org.openremote.model.Attribute;
-import org.openremote.model.AttributeEvent;
-import org.openremote.model.AttributeState;
-import org.openremote.model.Consumer;
+import org.openremote.model.*;
+import org.openremote.model.asset.Asset;
import org.openremote.model.asset.ThingAttribute;
import java.util.ArrayList;
@@ -38,7 +38,10 @@ import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
+import static org.openremote.agent3.protocol.Protocol.ACTUATOR_TOPIC;
import static org.openremote.agent3.protocol.Protocol.SENSOR_TOPIC;
+import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
+import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;
import static org.openremote.model.asset.AssetType.THING;
/**
@@ -46,9 +49,40 @@ import static org.openremote.model.asset.AssetType.THING;
* <ul>
* <li>
* Listens to {@link AttributeState} messages on {@link Protocol#SENSOR_TOPIC} and processes them
- * with consumers: {@link AssetRulesService}, {@link AssetStorageService}, {@link AssetDatapointService}
+ * with: {@link AssetRulesService}, {@link AssetStorageService}, {@link AssetDatapointService}
+ * </li>
+ * <li>
+ * Listens for {@link PersistenceEvent} of {@link Asset} entity and detects changed attributes. Any
+ * created or updated {@link ThingAttribute} will be send to its {@link Protocol#ACTUATOR_TOPIC}. Any
+ * other created or updated attribute will be processed with: {@link AssetRulesService},
+ * {@link AssetStorageService}, {@link AssetDatapointService}
* </li>
* </ul>
+ * TODO What's the call path for thing attribute value updates from clients (northbound, not sensors)?
+ * <p>
+ * Proposal:
+ * <p>
+ * 1. Receive AttributeEvent on client API
+ * <p>
+ * 2. Handle security and verify the message is for a linked agent/thing/attribute in the asset database
+ * <p>
+ * 3. Send the AttributeEvent to the Protocol through ACTUATOR_TOPIC and trigger device/service call
+ * <p>
+ * 4a. We assume that most protocol implementations are not using fire-and-forget but request/reply
+ * communication. Thus, an AttributeEvent has no further consequences besides triggering an
+ * actuator. We expect that a sensor "response" will let us know "soon" if the call was successful.
+ * Only a sensor value change will result in an update of the asset database state. The window of
+ * inconsistency we can accept depends on how "soon" a protocol typically responds.
+ * <p>
+ * 4b. Alternatively, if the updated attribute is configured with the "forceUpdate" meta item, we write
+ * the new attribute state directly into the asset database after triggering the actuator. This flag
+ * is useful if the protocol does not reflect actuator changes "immediately". For example, if we
+ * send a value to a light dimmer actuator, does the light dimmer also have a sensor that responds
+ * quickly with the new value? If the device/service does not reply to value changes, we can force
+ * an update of the "current state" in our database and simply assume that the actuator call was
+ * successful.
+ * <p>
+ * 4c. Should "forceUpdate" be the default behavior?
*/
public class AssetProcessingService extends RouteBuilder implements ContainerService {
@@ -57,6 +91,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
protected AssetRulesService assetRulesService;
protected AssetStorageService assetStorageService;
protected AssetDatapointService assetDatapointService;
+ protected MessageBrokerService messageBrokerService;
final protected List<Consumer<AssetUpdate>> processors = new ArrayList<>();
@@ -65,6 +100,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
assetRulesService = container.getService(AssetRulesService.class);
assetStorageService = container.getService(AssetStorageService.class);
assetDatapointService = container.getService(AssetDatapointService.class);
+ messageBrokerService = container.getService(MessageBrokerService.class);
processors.add(assetRulesService);
processors.add(assetStorageService);
@@ -90,48 +126,95 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
from(SENSOR_TOPIC)
.filter(body().isInstanceOf(AttributeEvent.class))
.process(exchange -> {
- AttributeEvent attributeEvent = exchange.getIn().getBody(AttributeEvent.class);
+ processSensorUpdate(exchange.getIn().getBody(AttributeEvent.class));
+ });
- // From sensor topic means this must update a thing asset
- ServerAsset thing = assetStorageService.find(attributeEvent.getEntityId());
- if (thing.getWellKnownType() != THING) {
- LOG.fine("Ignoring " + attributeEvent + ", not a thing: " + thing);
- return;
- }
+ // If any asset was modified in the database, detect changed attributes
+ from(PERSISTENCE_TOPIC)
+ .filter(isPersistenceEventForEntityType(Asset.class))
+ .process(exchange -> {
+ PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);
+ Asset asset = (Asset) persistenceEvent.getEntity();
+ // TODO: Detect which attribute was created/updated in the database and handle it
+ });
+ }
- // Get the attribute and check it is actually linked to an agent (although the
- // event comes from a Protocol, we can not assume that the attribute is still linked,
- // consider a protocol that receives a batch of messages because a gateway was offline
- // for a day)
- ThingAttributes thingAttributes = new ThingAttributes(thing);
+ public void processClientUpdate(AttributeEvent attributeEvent) {
+
+ ServerAsset asset = assetStorageService.find(attributeEvent.getEntityId());
+
+ switch (asset.getWellKnownType()) {
+ case THING:
+ // Send it to the protocol actuator after checking if it's a thing asset and linked attribute
+ LOG.fine("Processing client " + attributeEvent + " for thing: " + asset);
+
+ ThingAttributes thingAttributes = new ThingAttributes(asset);
ThingAttribute thingAttribute = thingAttributes.getLinkedAttribute(
assetStorageService.getAgentLinkResolver(), attributeEvent.getAttributeName()
);
- processAssetUpdate(thing, thingAttribute, attributeEvent, true);
- });
+ if (thingAttribute == null) {
+ throw new RuntimeException("Ignoring " + attributeEvent + ", thing attribute not available or linked to agent: " + asset);
+ }
+
+ // TODO See class Javadoc, should we have a forceUpdate flag?
+ // processUpdate(asset, thingAttribute, attributeEvent, false);
+
+ // Push it to protocol actuator
+ messageBrokerService.getProducerTemplate().sendBody(ACTUATOR_TOPIC, attributeEvent);
+
+ break;
+
+ case AGENT:
+ // TODO We don't want to allow agent attribute updates?! Not sure why but it seems like a good idea...
+ throw new RuntimeException("Agent attributes can not be updated individually, update the whole asset instead");
+
+ default:
+ // Perform regular asset attribute update
+ LOG.fine("Processing client " + attributeEvent + " for: " + asset);
+ Attributes attributes = new Attributes(asset.getAttributes());
+ Attribute attribute = attributes.get(attributeEvent.getAttributeName());
+ processUpdate(asset, attribute, attributeEvent, false); // Don't ignore readOnly flag
+ break;
+ }
}
- public void processAssetUpdate(ServerAsset asset,
- Attribute attribute,
- AttributeEvent attributeEvent) {
- processAssetUpdate(asset, attribute, attributeEvent, false);
+ protected void processSensorUpdate(AttributeEvent attributeEvent) {
+ // Must reference a thing asset
+ ServerAsset thing = assetStorageService.find(attributeEvent.getEntityId());
+ if (thing.getWellKnownType() != THING) {
+ LOG.fine("Ignoring " + attributeEvent + ", not a thing: " + thing);
+ return;
+ }
+
+ LOG.fine("Processing sensor " + attributeEvent + " for thing: " + thing);
+
+ // Get the attribute and check it is actually linked to an agent (although the
+ // event comes from a Protocol, we can not assume that the attribute is still linked,
+ // consider a protocol that receives a batch of messages because a gateway was offline
+ // for a day)
+ ThingAttributes thingAttributes = new ThingAttributes(thing);
+ ThingAttribute thingAttribute = thingAttributes.getLinkedAttribute(
+ assetStorageService.getAgentLinkResolver(), attributeEvent.getAttributeName()
+ );
+
+ processUpdate(thing, thingAttribute, attributeEvent, true);
}
- protected void processAssetUpdate(ServerAsset asset,
- Attribute attribute,
- AttributeEvent attributeEvent,
- boolean ignoreReadOnly) {
+ protected void processUpdate(ServerAsset asset,
+ Attribute attribute,
+ AttributeEvent attributeEvent,
+ boolean ignoreReadOnly) {
// Check the asset has this attribute (might also not be present if a Thing's attribute is unlinked)
if (attribute == null) {
- LOG.fine("Ignoring " + attributeEvent + ", attribute not available: " + asset);
+ LOG.warning("Ignoring " + attributeEvent + ", attribute not available: " + asset);
return;
}
// Check attribute isn't readonly
if (!ignoreReadOnly && attribute.isReadOnly()) {
- LOG.fine("Ignoring " + attributeEvent + ", attribute is read-only in: " + asset);
+ LOG.warning("Ignoring " + attributeEvent + ", attribute is read-only in: " + asset);
return;
}
@@ -140,7 +223,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
// Allow a leniency of 1s
if (attributeEvent.getTimestamp() - System.currentTimeMillis() > 1000) {
// TODO: Decide how to handle update events in the future - ignore or change timestamp
- LOG.fine("Ignoring " + attributeEvent + ", event-time is in the future in:" + asset);
+ LOG.warning("Ignoring " + attributeEvent + ", event-time is in the future in:" + asset);
return;
}
@@ -150,7 +233,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
// Check the last update timestamp of the attribute, ignoring any event that is older than last udpate
// TODO: This means we drop out-of-sequence events, we might need better at-least-once handling
if (lastStateEvent.getTimestamp() >= 0 && attributeEvent.getTimestamp() - lastStateEvent.getTimestamp() < 1000) {
- LOG.fine("Ignoring " + attributeEvent + ", event-time is older than attribute's last value in: " + asset);
+ LOG.warning("Ignoring " + attributeEvent + ", event-time is older than attribute's last value in: " + asset);
return;
}
@@ -158,18 +241,14 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
try {
attribute.applyStateEvent(attributeEvent);
} catch (IllegalArgumentException ex) {
- LOG.log(Level.FINE, "Ignoring " + attributeEvent + ", attribute constraint violation in: " + asset, ex);
+ LOG.log(Level.WARNING, "Ignoring " + attributeEvent + ", attribute constraint violation in: " + asset, ex);
return;
}
- processAssetUpdate(
- new AssetUpdate(asset, attribute, attributeEvent, lastStateEvent)
- );
+ processUpdate(new AssetUpdate(asset, attribute, attributeEvent, lastStateEvent));
}
- protected void processAssetUpdate(AssetUpdate assetUpdate) {
-
- // Create and process the attributeState change
+ protected void processUpdate(AssetUpdate assetUpdate) {
for (Consumer<AssetUpdate> processor : processors) {
try {
LOG.fine("Processor " + processor + " accepts: " + assetUpdate);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
index 7854e8418..bbe15653a 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
@@ -19,10 +19,12 @@
*/
package org.openremote.manager.server.asset;
-import elemental.json.JsonValue;
import org.openremote.container.web.WebResource;
import org.openremote.manager.shared.asset.AssetResource;
import org.openremote.manager.shared.http.RequestParams;
+import org.openremote.model.AttributeEvent;
+import org.openremote.model.AttributeRef;
+import org.openremote.model.AttributeState;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetInfo;
import org.openremote.model.asset.ProtectedAssetInfo;
@@ -30,6 +32,9 @@ import org.openremote.model.asset.ProtectedAssetInfo;
import javax.ws.rs.BeanParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
import java.util.logging.Logger;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
@@ -40,9 +45,11 @@ public class AssetResourceImpl extends WebResource implements AssetResource {
private static final Logger LOG = Logger.getLogger(AssetResourceImpl.class.getName());
protected final AssetStorageService assetStorageService;
+ protected final AssetProcessingService assetProcessingService;
- public AssetResourceImpl(AssetStorageService assetStorageService) {
+ public AssetResourceImpl(AssetStorageService assetStorageService, AssetProcessingService assetProcessingService) {
this.assetStorageService = assetStorageService;
+ this.assetProcessingService = assetProcessingService;
}
@Override
@@ -51,7 +58,18 @@ public class AssetResourceImpl extends WebResource implements AssetResource {
if (isSuperUser() || !isRestrictedUser()) {
return new ProtectedAssetInfo[0];
}
- return assetStorageService.findProtectedOfUser(getAuthenticatedRealm(), getUsername());
+ List<ProtectedAssetInfo> assets = Arrays.asList(assetStorageService.findProtectedOfUser(getUsername()));
+ // Filter assets that might have been moved into a different realm and can no longer be accessed by user
+ // TODO: Should we forbid moving assets between realms?
+ Iterator<ProtectedAssetInfo> it = assets.iterator();
+ while (it.hasNext()) {
+ ProtectedAssetInfo assetInfo = it.next();
+ if (!assetInfo.getRealm().equals(getAuthenticatedRealm())) {
+ LOG.warning("User '" + getUsername() + "' has protected asset outside of authenticated realm, skipping: " + assetInfo);
+ it.remove();
+ }
+ }
+ return assets.toArray(new ProtectedAssetInfo[assets.size()]);
} catch (IllegalStateException ex) {
throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);
}
@@ -152,8 +170,41 @@ public class AssetResourceImpl extends WebResource implements AssetResource {
}
@Override
- public void updateAttribute(@BeanParam RequestParams requestParams, String assetId, String attributeName, JsonValue value) {
- throw new UnsupportedOperationException("Not Implemented"); // TODO
+ public void updateAttribute(@BeanParam RequestParams requestParams, AttributeState attributeState) {
+ try {
+ if (isRestrictedUser()) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ }
+ AttributeRef attributeRef = attributeState.getAttributeRef();
+ ServerAsset asset = assetStorageService.find(attributeRef.getEntityId());
+ if (asset == null)
+ throw new WebApplicationException(NOT_FOUND);
+
+ // Check realm, must be accessible
+ if (!isRealmAccessibleByUser(asset.getRealm())) {
+ LOG.fine(
+ "Forbidden access for user '" + getUsername() + "', can't update asset '"
+ + attributeRef.getEntityId() + " + ' of realm: " + asset.getRealm()
+ );
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ }
+
+ // Check restricted
+ if (isRestrictedUser() &&
+ !assetStorageService.findProtectedOfUserContains(getUsername(), asset.getId())) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ }
+
+ // Process update
+ try {
+ assetProcessingService.processClientUpdate(new AttributeEvent(attributeState));
+ } catch (RuntimeException ex) {
+ throw new IllegalStateException("Error updating attribute: " + attributeState, ex);
+ }
+
+ } catch (IllegalStateException ex) {
+ throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);
+ }
}
@Override
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
index 2aa18494b..22bd10ff9 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
@@ -68,7 +68,7 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda
managerIdentityService = container.getService(ManagerIdentityService.class);
container.getService(WebService.class).getApiSingletons().add(
- new AssetResourceImpl(this)
+ new AssetResourceImpl(this, container.getService(AssetProcessingService.class))
);
}
@@ -167,22 +167,21 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda
/**
* Find protected assets by primary keys.
*
- * @param realm The realm in which the assets must be.
* @param assetIds The primary key identifier values of the assets to find.
* @return The found assets or an empty array
*/
- public ProtectedAssetInfo[] findProtectedById(String realm, String[] assetIds) {
- if (realm == null || realm.length() == 0)
- throw new IllegalArgumentException("Realm must be provided to query assets");
+ public ProtectedAssetInfo[] findProtectedById(String[] assetIds) {
+ // The IN SQL clause on Postgres is unlimited, so we must do some sanity check
+ if (assetIds.length > 1000) {
+ throw new IllegalArgumentException("Can't query more than 1000 asset IDs at a time");
+ }
return persistenceService.doReturningTransaction(em -> {
- // TODO The SQL IN clause is not limited on Postgres, we should have some sanity check here on the number of IDs!
List<ProtectedAssetInfo> result = em.createQuery(
"select new org.openremote.manager.server.asset.ProtectedServerAssetInfo(" +
"a.id, a.version, a.name, a.createdOn, a.realm, a.type, a.parent.id, a.location, a.attributes" +
- ") from Asset a where a.id in :assetIds and a.realm = :realm order by a.createdOn asc",
+ ") from Asset a where a.id in :assetIds order by a.createdOn asc",
ProtectedAssetInfo.class
- ).setParameter("realm", realm)
- .setParameter("assetIds", Arrays.asList(assetIds))
+ ).setParameter("assetIds", Arrays.asList(assetIds))
.getResultList();
return result.toArray(new ProtectedAssetInfo[result.size()]);
});
@@ -191,11 +190,10 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda
/**
* Find protected assets linked to a user.
*
- * @param realm The realm in which the assets must be.
* @param username The username of the user.
* @return The found assets or an empty array
*/
- public ProtectedAssetInfo[] findProtectedOfUser(String realm, String username) {
+ public ProtectedAssetInfo[] findProtectedOfUser(String username) {
return persistenceService.doReturningTransaction(em -> {
Query userAttributesQuery = em.createNativeQuery(
"SELECT ua.NAME, ua.VALUE " +
@@ -206,7 +204,31 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda
String[] assetIds = ProtectedUserAssets.getAssetIdsFromUserAttributes(
userAttributesQuery.setParameter("username", username).getResultList()
);
- return findProtectedById(realm, assetIds);
+ return findProtectedById(assetIds);
+ });
+ }
+
+ /**
+ * Confirm if protected assets linked to a user contains given asset.
+ *
+ * @param username The username of the user.
+ * @param assetId The asset ID value.
+ * @return The found assets or an empty array
+ */
+ public boolean findProtectedOfUserContains(String username, String assetId) {
+ return persistenceService.doReturningTransaction(em -> {
+ Query userAttributesQuery = em.createNativeQuery(
+ "SELECT ua.VALUE " +
+ "FROM USER_ATTRIBUTE ua JOIN USER_ENTITY u ON u.ID = ua.USER_ID " +
+ "WHERE u.USERNAME = :username " +
+ "AND ua.NAME = :assetsAttributeName " +
+ "AND ua.VALUE = :assetId"
+ );
+ List result = userAttributesQuery.setParameter("username", username)
+ .setParameter("assetsAttributeName", ProtectedUserAssets.ASSETS_ATTRIBUTE)
+ .setParameter("assetId", assetId)
+ .getResultList();
+ return result.size() > 0;
});
}
@@ -322,7 +344,8 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda
);
if (!storeAttributeValue(assetId, attributeName, value, valueTimestamp)) {
throw new RuntimeException("Database update failed, no rows updated");
- };
+ }
+ ;
}
protected ServerAsset loadAsset(EntityManager em, String assetId) {
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesResourceImpl.java
index 31815b6b1..e7d87df2c 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesResourceImpl.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesResourceImpl.java
@@ -27,7 +27,6 @@ import org.openremote.manager.shared.rules.GlobalRulesDefinition;
import org.openremote.manager.shared.rules.RulesResource;
import org.openremote.manager.shared.rules.TenantRulesDefinition;
import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.ProtectedAssetInfo;
import javax.ws.rs.BeanParam;
import javax.ws.rs.WebApplicationException;
@@ -77,8 +76,9 @@ public class RulesResourceImpl extends WebResource implements RulesResource {
if (!isRealmAccessibleByUser(realm)) {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
- if (isRestrictedUser()) {
- checkProtectedAccess(assetId);
+ if (isRestrictedUser() &&
+ !assetStorageService.findProtectedOfUserContains(getUsername(), assetId)) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
}
List<AssetRulesDefinition> result = rulesStorageService.findAssetDefinitions(realm, assetId);
return result.toArray(new AssetRulesDefinition[result.size()]);
@@ -196,8 +196,9 @@ public class RulesResourceImpl extends WebResource implements RulesResource {
if (!isRealmAccessibleByUser(asset.getRealm())) {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
- if (isRestrictedUser()) {
- checkProtectedAccess(assetId);
+ if (isRestrictedUser() &&
+ !assetStorageService.findProtectedOfUserContains(getUsername(), asset.getId())) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
}
rulesDefinition = rulesStorageService.merge(rulesDefinition);
}
@@ -215,8 +216,9 @@ public class RulesResourceImpl extends WebResource implements RulesResource {
if (!isRealmAccessibleByUser(asset.getRealm())) {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
- if (isRestrictedUser()) {
- checkProtectedAccess(asset.getId());
+ if (isRestrictedUser() &&
+ !assetStorageService.findProtectedOfUserContains(getUsername(), asset.getId())) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
}
return existingDefinition;
}
@@ -234,8 +236,9 @@ public class RulesResourceImpl extends WebResource implements RulesResource {
if (!isRealmAccessibleByUser(asset.getRealm())) {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
- if (isRestrictedUser()) {
- checkProtectedAccess(asset.getId());
+ if (isRestrictedUser() &&
+ !assetStorageService.findProtectedOfUserContains(getUsername(), asset.getId())) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
}
if (!id.equals(rulesDefinition.getId())) {
throw new WebApplicationException("Requested ID and definition ID don't match", BAD_REQUEST);
@@ -259,24 +262,11 @@ public class RulesResourceImpl extends WebResource implements RulesResource {
if (!isRealmAccessibleByUser(asset.getRealm())) {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
- if (isRestrictedUser()) {
- checkProtectedAccess(asset.getId());
+ if (isRestrictedUser() &&
+ !assetStorageService.findProtectedOfUserContains(getUsername(), asset.getId())) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
}
rulesStorageService.delete(AssetRulesDefinition.class, id);
}
- /* ################################################################################################# */
-
- protected void checkProtectedAccess(String assetId) {
- boolean foundProtected = false;
- ProtectedAssetInfo[] protectedAssets =
- assetStorageService.findProtectedOfUser(getAuthenticatedRealm(), getUsername());
- for (ProtectedAssetInfo protectedAsset : protectedAssets) {
- if (protectedAsset.getId().equals(assetId))
- foundProtected = true;
- }
- if (!foundProtected) {
- throw new WebApplicationException(Response.Status.FORBIDDEN);
- }
- }
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesStorageService.java
index cdfa2b8b5..389f1a9a7 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesStorageService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesStorageService.java
@@ -56,6 +56,10 @@ public class RulesStorageService implements ContainerService {
}
+ /**
+ * The {@link RulesDefinition#rules} property is not populated for this query to avoid
+ * loading multiple large strings.
+ */
public List<GlobalRulesDefinition> findGlobalDefinitions() {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
@@ -69,6 +73,10 @@ public class RulesStorageService implements ContainerService {
);
}
+ /**
+ * The {@link RulesDefinition#rules} property is not populated for this query to avoid
+ * loading multiple large strings.
+ */
public List<TenantRulesDefinition> findTenantDefinitions(String realm) {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
@@ -83,6 +91,10 @@ public class RulesStorageService implements ContainerService {
);
}
+ /**
+ * The {@link RulesDefinition#rules} property is not populated for this query to avoid
+ * loading multiple large strings.
+ */
public List<AssetRulesDefinition> findAssetDefinitions(String realm, String assetId) {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
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.java
index 5bd628471..d014c3417 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
@@ -23,6 +23,10 @@ import com.vividsolutions.jts.geom.Coordinate;
import elemental.json.Json;
import org.apache.commons.io.IOUtils;
import org.openremote.agent3.protocol.simulator.SimulatorProtocol;
+import org.openremote.agent3.protocol.simulator.element.ColorSimulatorElement;
+import org.openremote.agent3.protocol.simulator.element.DecimalSimulatorElement;
+import org.openremote.agent3.protocol.simulator.element.IntegerSimulatorElement;
+import org.openremote.agent3.protocol.simulator.element.SwitchSimulatorElement;
import org.openremote.container.Container;
import org.openremote.manager.server.agent.AgentAttributes;
import org.openremote.manager.server.agent.ThingAttributes;
@@ -147,7 +151,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
new AttributeRef(agent.getId(), "simulator123").asJsonValue()
))
.add(new MetaItem(
- SimulatorProtocol.META_NAME_ELEMENT, Json.create("switch")
+ SimulatorProtocol.SIMULATOR_ELEMENT, Json.create(SwitchSimulatorElement.ELEMENT_NAME)
))
),
new Attribute("light1Dimmer", INTEGER) // No initial value!
@@ -169,7 +173,10 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
new AttributeRef(agent.getId(), "simulator123").asJsonValue()
))
.add(new MetaItem(
- SimulatorProtocol.META_NAME_ELEMENT, Json.create("range")
+ SimulatorProtocol.SIMULATOR_ELEMENT, Json.create(IntegerSimulatorElement.ELEMENT_NAME_RANGE)
+ ))
+ .add(new MetaItem(
+ SimulatorProtocol.SIMULATOR_REFLECT_ACTUATOR_WRITES, Json.create(true)
))
),
new Attribute("light1Color", INTEGER_ARRAY, new ColorRGB(88, 123, 88).asJsonValue())
@@ -187,7 +194,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
new AttributeRef(agent.getId(), "simulator123").asJsonValue()
))
.add(new MetaItem(
- SimulatorProtocol.META_NAME_ELEMENT, Json.create("color")
+ SimulatorProtocol.SIMULATOR_ELEMENT, Json.create(ColorSimulatorElement.ELEMENT_NAME)
))
),
new Attribute("light1PowerConsumption", DECIMAL, Json.create(12.345))
@@ -209,7 +216,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
new AttributeRef(agent.getId(), "simulator123").asJsonValue()
))
.add(new MetaItem(
- SimulatorProtocol.META_NAME_ELEMENT, Json.create("decimal")
+ SimulatorProtocol.SIMULATOR_ELEMENT, Json.create(DecimalSimulatorElement.ELEMENT_NAME)
))
.add(new MetaItem(
AssetMeta.STORE_DATA_POINTS.getName(), Json.create(true)
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java
index 4dd9cae8b..a6d4e798a 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java
@@ -19,10 +19,10 @@
*/
package org.openremote.manager.shared.asset;
-import elemental.json.JsonValue;
import jsinterop.annotations.JsType;
import org.openremote.manager.shared.http.RequestParams;
import org.openremote.manager.shared.http.SuccessStatusCode;
+import org.openremote.model.AttributeState;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetInfo;
import org.openremote.model.asset.ProtectedAssetInfo;
@@ -132,24 +132,19 @@ public interface AssetResource {
void update(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, Asset asset);
/**
- * Updates an attribute of a user with a JSON value. Regular users can only update assets in
+ * Updates an attribute of an asset. Regular users can only update assets in
* their authenticated realm, the superuser can update assets in other (all) realms. A 403 status
* is returned if a regular user tries to update an asset in a realm different than its
* authenticated realm, or if the user is restricted and the asset to update is not in the set of linked
* assets of the restricted user. A 400 status is returned if the update was not successful, e.g. because
* the given value does not match the attribute's type.
- * // TODO Consider attribute state class instead, and test this
*/
@PUT
- @Path("{assetId}/attribute/{attributeName}")
+ @Path("{assetId}/attribute")
@Consumes(APPLICATION_JSON)
@SuccessStatusCode(204)
@RolesAllowed({"write:assets"})
- void updateAttribute(@BeanParam RequestParams requestParams,
- @PathParam("assetId") String assetId,
- @PathParam("attributeName") String attributeName,
- JsonValue value);
-
+ void updateAttribute(@BeanParam RequestParams requestParams, AttributeState attributeState);
/**
* Creates an asset. The identifier value of the asset can be provided, it should be a
diff --git a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy
index 99a3555f8..6212835bf 100644
--- a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy
@@ -4,7 +4,7 @@ import elemental.json.Json
import elemental.json.JsonObject
import elemental.json.JsonType
import org.openremote.agent3.protocol.simulator.SimulatorProtocol
-import org.openremote.container.message.MessageBrokerService
+import org.openremote.manager.server.asset.AssetProcessingService
import org.openremote.manager.server.asset.AssetStorageService
import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.server.setup.builtin.ManagerDemoSetup
@@ -15,8 +15,6 @@ import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import static org.openremote.agent3.protocol.Protocol.ACTUATOR_TOPIC
-
class AgentDeploymentTest extends Specification implements ManagerContainerTrait {
def "Check agent and thing deployment"() {
@@ -29,7 +27,8 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
def container = startContainer(defaultConfig(serverPort), defaultServices())
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def simulatorProtocol = container.getService(SimulatorProtocol.class)
- def assetService = container.getService(AssetStorageService.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
then: "the simulator elements should have the initial state"
conditions.eventually {
@@ -41,42 +40,18 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
when: "a client wants to change a thing attributes' value, triggering an actuator"
conditions = new PollingConditions(timeout: 3, initialDelay: 2)
- /* TODO What's the call path for thing attribute value updates and therefore the asset client API?
-
- Proposal:
-
- 1. Receive AttributeState on client API
-
- 2. Handle security and verify the message is for a linked agent/thing/attribute in the asset database
-
- 3. Send the AttributeState to the Protocol through ACTUATOR_TOPIC and trigger device/service call
-
- 4a. We assume that most protocol implementations are not using fire-and-forget but request/reply
- communication. Thus, an AttributeState has no further consequences besides triggering an
- actuator. We expect that a sensor "response" will let us know "soon" if the call was successful.
- Only a sensor value change will result in an update of the asset database state. The window of
- inconsistency we can accept depends on how "soon" a protocol typically responds.
-
- 4b. Alternatively, if the updated attribute is configured with the "forceUpdate" meta item, we write
- the new attribute state directly into the asset database after triggering the actuator. This flag
- is useful if the protocol does not reflect actuator changes "immediately". For example, if we
- send a value to a light dimmer actuator, does the light dimmer also have a sensor that responds
- quickly with the new value? If the device/service does not reply to value changes, we can force
- an update of the "current state" in our database and simply assume that the actuator call was
- successful.
-
- 4c. Should "forceUpdate" be the default behavior?
- */
def light1DimmerChange = new AttributeEvent(
managerDemoSetup.thingId, "light1Dimmer", Json.create(66)
)
- container.getService(MessageBrokerService.class).getProducerTemplate().sendBody(
- ACTUATOR_TOPIC, light1DimmerChange
- )
+ assetProcessingService.processClientUpdate(light1DimmerChange)
- then: "the simulator state should be updated"
+ then: "the simulator state and thing attribute value should be updated (simulator reflects actuator write as sensor read)"
conditions.eventually {
assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Dimmer").asNumber() == 66
+ def thing = assetStorageService.find(managerDemoSetup.thingId)
+ def attributes = new Attributes(thing.getAttributes())
+ assert attributes.get("light1Dimmer").getValue().getType() == JsonType.NUMBER
+ assert attributes.get("light1Dimmer").getValueAsInteger() == 66
}
when: "a simulated sensor changes its value"
@@ -85,7 +60,7 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
then: "the thing attribute value should be updated"
conditions.eventually {
- def thing = assetService.find(managerDemoSetup.thingId)
+ def thing = assetStorageService.find(managerDemoSetup.thingId)
def attributes = new Attributes(thing.getAttributes())
assert attributes.get("light1Dimmer").getValue().getType() == JsonType.NUMBER
assert attributes.get("light1Dimmer").getValueAsInteger() == 77
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy
index 033315d7d..943cc8a45 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy
@@ -4,7 +4,7 @@ import elemental.json.Json
import elemental.json.JsonObject
import elemental.json.JsonType
import org.openremote.agent3.protocol.simulator.SimulatorProtocol
-import org.openremote.container.message.MessageBrokerService
+import org.openremote.manager.server.asset.AssetProcessingService
import org.openremote.manager.server.asset.AssetStorageService
import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.server.setup.builtin.ManagerDemoSetup
@@ -15,8 +15,6 @@ import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import static org.openremote.agent3.protocol.Protocol.ACTUATOR_TOPIC
-
class RulesDeploymentTest extends Specification implements ManagerContainerTrait {
def "Check agent and thing deployment"() {
@@ -29,7 +27,8 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
def container = startContainer(defaultConfig(serverPort), defaultServices())
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def simulatorProtocol = container.getService(SimulatorProtocol.class)
- def assetService = container.getService(AssetStorageService.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
then: "the simulator elements should have the initial state"
conditions.eventually {
@@ -41,51 +40,27 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
when: "a client wants to change a thing attributes' value, triggering an actuator"
conditions = new PollingConditions(timeout: 3, initialDelay: 2)
- /* TODO What's the call path for thing attribute value updates and therefore the asset client API?
-
- Proposal:
-
- 1. Receive AttributeState on client API
-
- 2. Handle security and verify the message is for a linked agent/thing/attribute in the asset database
-
- 3. Send the AttributeState to the Protocol through ACTUATOR_TOPIC and trigger device/service call
-
- 4a. We assume that most protocol implementations are not using fire-and-forget but request/reply
- communication. Thus, an AttributeState has no further consequences besides triggering an
- actuator. We expect that a sensor "response" will let us know "soon" if the call was successful.
- Only a sensor value change will result in an update of the asset database state. The window of
- inconsistency we can accept depends on how "soon" a protocol typically responds.
-
- 4b. Alternatively, if the updated attribute is configured with the "forceUpdate" meta item, we write
- the new attribute state directly into the asset database after triggering the actuator. This flag
- is useful if the protocol does not reflect actuator changes "immediately". For example, if we
- send a value to a light dimmer actuator, does the light dimmer also have a sensor that responds
- quickly with the new value? If the device/service does not reply to value changes, we can force
- an update of the "current state" in our database and simply assume that the actuator call was
- successful.
-
- 4c. Should "forceUpdate" be the default behavior?
- */
def light1DimmerChange = new AttributeEvent(
managerDemoSetup.thingId, "light1Dimmer", Json.create(66)
)
- container.getService(MessageBrokerService.class).getProducerTemplate().sendBody(
- ACTUATOR_TOPIC, light1DimmerChange
- )
+ assetProcessingService.processClientUpdate(light1DimmerChange)
- then: "the simulator state should be updated"
+ then: "the simulator state and thing attribute value should be updated (simulator reflects actuator write as sensor read)"
conditions.eventually {
assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Dimmer").asNumber() == 66
+ def thing = assetStorageService.find(managerDemoSetup.thingId)
+ def attributes = new Attributes(thing.getAttributes())
+ assert attributes.get("light1Dimmer").getValue().getType() == JsonType.NUMBER
+ assert attributes.get("light1Dimmer").getValueAsInteger() == 66
}
when: "a simulated sensor changes its value"
conditions = new PollingConditions(timeout: 3, initialDelay: 2)
- simulatorProtocol.putState(managerDemoSetup.thingId, "light1Dimmer", Json.create(77),)
+ simulatorProtocol.putState(managerDemoSetup.thingId, "light1Dimmer", Json.create(77))
then: "the thing attribute value should be updated"
conditions.eventually {
- def thing = assetService.find(managerDemoSetup.thingId)
+ def thing = assetStorageService.find(managerDemoSetup.thingId)
def attributes = new Attributes(thing.getAttributes())
assert attributes.get("light1Dimmer").getValue().getType() == JsonType.NUMBER
assert attributes.get("light1Dimmer").getValueAsInteger() == 77
diff --git a/model/src/main/java/org/openremote/model/AttributeRef.java b/model/src/main/java/org/openremote/model/AttributeRef.java
index 4d2691de2..724d5a2bf 100644
--- a/model/src/main/java/org/openremote/model/AttributeRef.java
+++ b/model/src/main/java/org/openremote/model/AttributeRef.java
@@ -31,11 +31,15 @@ import elemental.json.JsonArray;
*/
public class AttributeRef {
- final protected String entityId;
- final protected String attributeName;
+ protected String entityId;
+ protected String attributeName;
+
// Optional, can be null if reference has not been resolved
protected String entityName;
+ public AttributeRef() {
+ }
+
public AttributeRef(String entityId, String attributeName) {
this.entityId = entityId;
this.attributeName = attributeName;
diff --git a/model/src/main/java/org/openremote/model/AttributeState.java b/model/src/main/java/org/openremote/model/AttributeState.java
index 078f35a2d..75e18999b 100644
--- a/model/src/main/java/org/openremote/model/AttributeState.java
+++ b/model/src/main/java/org/openremote/model/AttributeState.java
@@ -28,8 +28,11 @@ import elemental.json.JsonValue;
*/
public class AttributeState {
- final protected AttributeRef attributeRef;
- final protected JsonValue value;
+ protected AttributeRef attributeRef;
+ protected JsonValue value;
+
+ public AttributeState() {
+ }
public AttributeState(AttributeRef attributeRef, JsonValue value) {
this.attributeRef = attributeRef;
diff --git a/model/src/main/java/org/openremote/model/asset/ProtectedUserAssets.java b/model/src/main/java/org/openremote/model/asset/ProtectedUserAssets.java
index 61366a98d..ff956f9d0 100644
--- a/model/src/main/java/org/openremote/model/asset/ProtectedUserAssets.java
+++ b/model/src/main/java/org/openremote/model/asset/ProtectedUserAssets.java
@@ -47,11 +47,13 @@ import static org.openremote.model.Constants.NAMESPACE;
* The actual linked assets identifiers are stored in {@link #ASSETS_ATTRIBUTE} and therefore
* in the Keycloak table <code>USER_ATTRIBUTES</code>. We query that table directly to retrieve
* the assets linked to a user.
+ *
+ * TODO This doesn't work, users can change their own attributes!
*/
public class ProtectedUserAssets {
// Keycloak user attribute where the boolean flag "this user has linked assets" is stored
- public static final String RESTRICTED_ATTRIBUTE = NAMESPACE + ":restrictedUser";
+ public static final String RESTRICTED_ATTRIBUTE = "restrictedUser";
// Keycloak user attribute where the actual linked asset identifiers are stored
public static final String ASSETS_ATTRIBUTE = NAMESPACE + ":userAssets";