Skip to content

armgit / core

Public Imported from GitHub
0

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

Implemented ProtocolAssetService updateAssetLocation

Rich Turnerd8038a884bc2
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
index 849a60487..1a1d58aae 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
@@ -19,6 +19,9 @@
*/
package org.openremote.agent.protocol;
+import com.vividsolutions.jts.geom.Coordinate;
+import com.vividsolutions.jts.geom.GeometryFactory;
+import com.vividsolutions.jts.geom.Point;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.openremote.agent.protocol.filter.MessageFilter;
@@ -36,9 +39,7 @@ import org.openremote.model.asset.agent.ConnectionStatus;
import org.openremote.model.asset.agent.ProtocolConfiguration;
import org.openremote.model.asset.agent.ProtocolDescriptor;
import org.openremote.model.attribute.*;
-import org.openremote.model.value.Value;
-import org.openremote.model.value.ValueType;
-import org.openremote.model.value.Values;
+import org.openremote.model.value.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
@@ -50,8 +51,8 @@ public abstract class AbstractProtocol implements Protocol {
protected static class LinkedProtocolInfo {
- AssetAttribute protocolConfiguration;
- Consumer<ConnectionStatus> connectionStatusConsumer;
+ final AssetAttribute protocolConfiguration;
+ final Consumer<ConnectionStatus> connectionStatusConsumer;
ConnectionStatus currentConnectionStatus;
protected LinkedProtocolInfo(
@@ -86,6 +87,7 @@ public abstract class AbstractProtocol implements Protocol {
protected final Map<AttributeRef, AssetAttribute> linkedAttributes = new HashMap<>();
protected final Map<AttributeRef, LinkedProtocolInfo> linkedProtocolConfigurations = new HashMap<>();
protected final Map<AttributeRef, List<MessageFilter>> linkedAttributeFilters = new HashMap<>();
+ protected final List<AttributeRef> locationLinkedAttributes = new ArrayList<>();
protected MessageBrokerContext messageBrokerContext;
protected ProducerTemplate producerTemplate;
protected TimerService timerService;
@@ -172,12 +174,20 @@ public abstract class AbstractProtocol implements Protocol {
// Need to add to map before actual linking as protocols may want to update the value as part of
// linking process and without entry in the map any update would be blocked
linkedAttributes.put(attributeRef, attribute);
+
Optional<List<MessageFilter>> messageFilters = Protocol.getLinkedAttributeMessageFilters(attribute);
- if (messageFilters.isPresent()) {
+ messageFilters.ifPresent(mFilters -> {
synchronized (linkedAttributeFilters) {
- linkedAttributeFilters.put(attributeRef, messageFilters.get());
+ linkedAttributeFilters.put(attributeRef, mFilters);
}
- }
+ });
+
+ attribute.getMetaItem(AssetMeta.LOCATION_LINK).ifPresent(metaItem -> {
+ synchronized (locationLinkedAttributes) {
+ locationLinkedAttributes.add(attribute.getReferenceOrThrow());
+ }
+ });
+
try {
doLinkAttribute(attribute, protocolConfiguration);
} catch (Exception e) {
@@ -186,6 +196,9 @@ public abstract class AbstractProtocol implements Protocol {
synchronized (linkedAttributeFilters) {
linkedAttributeFilters.remove(attributeRef);
}
+ synchronized (locationLinkedAttributes) {
+ locationLinkedAttributes.remove(attributeRef);
+ }
}
});
}
@@ -201,6 +214,9 @@ public abstract class AbstractProtocol implements Protocol {
synchronized (linkedAttributeFilters) {
linkedAttributeFilters.remove(attributeRef);
}
+ synchronized (locationLinkedAttributes) {
+ locationLinkedAttributes.remove(attributeRef);
+ }
doUnlinkAttribute(attribute, protocolConfiguration);
});
}
@@ -268,6 +284,8 @@ public abstract class AbstractProtocol implements Protocol {
@SuppressWarnings("unchecked")
protected void updateLinkedAttribute(AttributeState state, long timestamp) {
AssetAttribute attribute;
+ boolean updateLocation;
+
synchronized (linkedAttributes) {
attribute = linkedAttributes.get(state.getAttributeRef());
}
@@ -334,6 +352,41 @@ public abstract class AbstractProtocol implements Protocol {
AttributeEvent attributeEvent = new AttributeEvent(state, timestamp);
LOG.fine("Sending on sensor queue: " + attributeEvent);
producerTemplate.sendBodyAndHeader(SENSOR_QUEUE, attributeEvent, Protocol.SENSOR_QUEUE_SOURCE_PROTOCOL, getProtocolName());
+
+
+ synchronized (locationLinkedAttributes) {
+ updateLocation = locationLinkedAttributes.contains(state.getAttributeRef());
+ }
+
+ if (updateLocation) {
+
+ // Check value type is compatible
+ Point location = state.getCurrentValue().map(value -> {
+ if (value.getType() != ValueType.ARRAY) {
+ LOG.warning("Location linked attribute type is not an array");
+ return null;
+ }
+
+ Optional<List<NumberValue>> coordinates = Values.getArrayElements((ArrayValue)value, NumberValue.class, false, false);
+ if (!coordinates.isPresent()
+ || coordinates.get().size() != 2
+ || Math.abs(coordinates.get().get(0).getNumber()) > 180
+ || Math.abs(coordinates.get().get(1).getNumber()) > 90) {
+ LOG.warning("Location linked attribute value must contain longitude then latitude in a 2 value number array");
+ return null;
+ }
+
+ try {
+ return new GeometryFactory().createPoint(
+ new Coordinate(coordinates.get().get(0).getNumber(), coordinates.get().get(1).getNumber())
+ );
+ } catch (Exception e) {
+ return null;
+ }
+ }).orElse(null);
+
+ updateAssetLocation(state.getAttributeRef().getEntityId(), location);
+ }
}
/**
@@ -344,6 +397,10 @@ public abstract class AbstractProtocol implements Protocol {
updateLinkedAttribute(state, timerService.getCurrentTimeMillis());
}
+ protected void updateAssetLocation(String assetId, Point location) {
+ assetService.updateAssetLocation(assetId, location);
+ }
+
/**
* Update a linked protocol configuration; allows protocols to reconfigure their own protocol configurations to
* persist changing data e.g. authorization tokens. First this clones the existing protocolConfiguration and calls
diff --git a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
index d8573dadd..5f5ab4977 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
@@ -23,15 +23,13 @@ import org.openremote.agent.protocol.filter.MessageFilter;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
import org.openremote.model.AbstractValueHolder;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetAttribute;
-import org.openremote.model.asset.AssetMeta;
-import org.openremote.model.asset.AssetType;
+import org.openremote.model.asset.*;
import org.openremote.model.asset.agent.ConnectionStatus;
import org.openremote.model.asset.agent.ProtocolConfiguration;
import org.openremote.model.asset.agent.ProtocolDescriptor;
import org.openremote.model.attribute.*;
import org.openremote.model.value.ArrayValue;
+import org.openremote.model.value.NumberValue;
import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.ValueType;
@@ -80,6 +78,11 @@ import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
* a linked attributes' value by sending an {@link AttributeEvent} messages on the
* {@link #SENSOR_QUEUE}, including the source protocol name in header {@link #SENSOR_QUEUE_SOURCE_PROTOCOL}.
* <p>
+ * As well as an {@link AssetMeta#AGENT_LINK} meta item; if an attribute also has an {@link AssetMeta#LOCATION_LINK}
+ * meta item then the protocol should push location data into the {@link Asset} location property (if the protocol and
+ * device support it and the attribute is correctly configured to receive location data and the value must be of type
+ * {@link ArrayValue} and contain two {@link NumberValue}s representing longitude and latitude in that order.
+ * <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
@@ -145,12 +148,13 @@ public interface Protocol extends ContainerService {
/**
* {@link MetaItem} for defining {@link MessageFilter}s to apply to values before they are sent on the
* {@link #SENSOR_QUEUE} (i.e. before it is used to update a protocol linked attribute); this is particularly
- * useful for generic protocols. The {@link MetaItem} should be an {@link ArrayValue} of {@link ObjectValue}s where
- * each {@link ObjectValue} represents a serialised {@link MessageFilter}. The message should pass through the
+ * useful for generic protocols. The {@link MetaItem} value should be an {@link ArrayValue} of {@link ObjectValue}s
+ * where each {@link ObjectValue} represents a serialised {@link MessageFilter}. The message should pass through the
* filters in array order.
*/
String META_PROTOCOL_FILTERS = PROTOCOL_NAMESPACE + ":filters";
+
// TODO: Some of these options should be configurable depending on expected load etc.
// Message topic for communicating from asset/thing to protocol layer (asset attribute changed, trigger actuator)
diff --git a/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java b/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java
index 5cbd628bd..c2ba46df5 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java
@@ -19,10 +19,13 @@
*/
package org.openremote.agent.protocol;
+import com.vividsolutions.jts.geom.Point;
import org.openremote.container.ContainerService;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetMeta;
import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.attribute.MetaItem;
import java.util.function.Predicate;
@@ -90,6 +93,13 @@ public interface ProtocolAssetService extends ContainerService {
*/
void updateProtocolConfiguration(AssetAttribute protocolConfiguration);
+ /**
+ * Protocols can update an assets location. This is generally to be used for linked attributes
+ * that also have a {@link AssetMeta#LOCATION_LINK} {@link MetaItem}. Set location to null to
+ * clear an asset's location.
+ */
+ void updateAssetLocation(String assetId, Point location);
+
/**
* Protocols may store assets in the context or update existing assets. A unique identifier
* must be set by the protocol implementor, as well as a parent identifier. This operation
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpServerProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpServerProtocol.java
index 2ad9f1534..ffc33e31d 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpServerProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpServerProtocol.java
@@ -19,7 +19,6 @@
*/
package org.openremote.agent.protocol.tcp;
-import io.netty.channel.socket.SocketChannel;
import org.openremote.agent.protocol.AbstractProtocol;
import org.openremote.model.AbstractValueHolder;
import org.openremote.model.asset.AssetAttribute;
@@ -34,7 +33,6 @@ import org.openremote.model.value.Values;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
-import java.util.function.BiConsumer;
import java.util.logging.Logger;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
@@ -66,7 +64,7 @@ public abstract class AbstractTcpServerProtocol<T extends TcpServer<U>, U> exten
public static final String META_PROTOCOL_BIND_ADDRESS = PROTOCOL_NAME + ":bindAddress";
private static final Logger LOG = Logger.getLogger(AbstractTcpServerProtocol.class.getName());
- protected Map<AttributeRef, T> tcpServerMap = new HashMap<>();
+ protected final Map<AttributeRef, T> tcpServerMap = new HashMap<>();
@Override
protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
@@ -94,7 +92,13 @@ public abstract class AbstractTcpServerProtocol<T extends TcpServer<U>, U> exten
T tcpServer = createTcpServer(port, bindAddress.map(StringValue::getString).orElse(null), protocolConfiguration);
tcpServerMap.put(protocolRef, tcpServer);
startTcpServer(protocolRef, tcpServer);
- updateStatus(protocolRef, ConnectionStatus.CONNECTED);
+
+ if (!tcpServer.isStarted()) {
+ LOG.warning("Failed to start TCP server instance");
+ updateStatus(protocolRef, ConnectionStatus.ERROR);
+ } else {
+ updateStatus(protocolRef, ConnectionStatus.CONNECTED);
+ }
}
@Override
diff --git a/manager/src/main/java/org/openremote/manager/agent/AgentService.java b/manager/src/main/java/org/openremote/manager/agent/AgentService.java
index 5f56d198d..795d71315 100644
--- a/manager/src/main/java/org/openremote/manager/agent/AgentService.java
+++ b/manager/src/main/java/org/openremote/manager/agent/AgentService.java
@@ -19,6 +19,7 @@
*/
package org.openremote.manager.agent;
+import com.vividsolutions.jts.geom.Point;
import org.apache.camel.builder.RouteBuilder;
import org.openremote.agent.protocol.Protocol;
import org.openremote.agent.protocol.ProtocolAssetService;
@@ -214,6 +215,19 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
assetStorageService.merge(agent);
}
+ @Override
+ public void updateAssetLocation(String assetId, Point location) {
+ ServerAsset asset = assetStorageService.find(assetId, true);
+ if (asset == null) {
+ LOG.warning("Asset with requested ID doesn't exist: " + assetId);
+ return;
+ }
+
+ asset.setLocation(location);
+ LOG.fine("Updating asset location '" + assetId + "': " + Arrays.toString(asset.getCoordinates()));
+ assetStorageService.merge(asset);
+ }
+
@Override
public Asset mergeAsset(Asset asset) {
Objects.requireNonNull(asset.getId());
@@ -370,9 +384,10 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
break;
case UPDATE:
+ List<String> propertyNames = Arrays.asList(persistenceEvent.getPropertyNames());
// Check if attributes of the asset have been modified
- int attributesIndex = Arrays.asList(persistenceEvent.getPropertyNames()).indexOf("attributes");
+ int attributesIndex = propertyNames.indexOf("attributes");
if (attributesIndex < 0) {
return;
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
index ea5cdb521..5281f4161 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
@@ -21,9 +21,7 @@ package org.openremote.model.asset;
import org.openremote.model.ValidationFailure;
import org.openremote.model.attribute.*;
-import org.openremote.model.value.Value;
-import org.openremote.model.value.ValueType;
-import org.openremote.model.value.Values;
+import org.openremote.model.value.*;
import java.util.Optional;
import java.util.function.Function;
@@ -74,6 +72,21 @@ public enum AssetMeta implements MetaItemDescriptor {
: new ValidationFailure(META_ITEM_VALUE_MISMATCH, AttributeRef.class.getSimpleName()))
),
+
+ /**
+ * Links an attribute to the location of the owning {@link Asset}; this is intended to be coupled with
+ * {@link #AGENT_LINK} to allow protocols to write an {@link Asset}'s location.
+ */
+ LOCATION_LINK(
+ ASSET_META_NAMESPACE + ":locationLink",
+ ACCESS_PRIVATE,
+ ValueType.BOOLEAN,
+ null,
+ null,
+ Values.create(true),
+ true
+ ),
+
/**
* Links the attribute to another attribute, so an attribute event on the attribute triggers the same attribute
* event on the linked attribute.