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
Work on server-side agent/device message routing
Christian Bauer122093e957c8
diff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2Component.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2Component.javaindex 90efea884..4fdd6045a 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2Component.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2Component.java@@ -20,30 +20,25 @@package org.openremote.agent.controller2;import org.apache.camel.Endpoint;-import org.apache.camel.impl.UriEndpointComponent;+import org.apache.camel.impl.DefaultComponent;import org.openremote.manager.shared.agent.Agent;-import org.openremote.manager.shared.asset.Asset;import org.openremote.manager.shared.attribute.AttributeType;+import org.openremote.manager.shared.attribute.Attributes;import org.openremote.manager.shared.connector.ConnectorComponent;import org.openremote.manager.shared.connector.ConnectorUtil;-import org.openremote.manager.shared.connector.ChildAssetSupport;-import org.openremote.manager.shared.attribute.Attributes;import java.net.URI;import java.nio.file.Path;import java.nio.file.Paths;+import java.util.Arrays;+import java.util.Collection;import java.util.Map;-import java.util.logging.Logger;-public class Controller2Component extends UriEndpointComponent implements ConnectorComponent {-- private static final Logger LOG = Logger.getLogger(Controller2Component.class.getName());+public class Controller2Component extends DefaultComponent implements ConnectorComponent {public static final String TYPE = "urn:openremote:connector:controller2";public static final String DISPLAY_NAME = "OpenRemote Controller";- public static final String URI_SYNTAX = "'controller2://<IP or host name>:<port>/([<device key>/<resource key>]|[discovery|inventory])[?username=username&password=secret]";- public static final String HEADER_DEVICE_KEY = Controller2Component.class.getCanonicalName() + ".HEADER_DEVICE_KEY";- public static final String HEADER_DEVICE_RESOURCE_KEY = Controller2Component.class.getCanonicalName() + ".HEADER_DEVICE_RESOURCE_KEY";+ public static final String URI_SYNTAX = "'controller2://<IP or host name>:<port>/[discovery|inventory|read|write|listen/<deviceKey>][?username=username&password=secret]";protected final Controller2AdapterManager adapterManager;public static final Attributes SETTINGS;@@ -83,7 +78,6 @@ public class Controller2Component extends UriEndpointComponent implements Connec}public Controller2Component(Controller2AdapterManager adapterManager) {- super(Controller2Endpoint.class);this.adapterManager = adapterManager;}@@ -129,26 +123,65 @@ public class Controller2Component extends UriEndpointComponent implements Connecreturn SETTINGS;}- // TODO These dynamic routes are safe? Should we escape values before we concatenate strings?+ @Override+ public Collection<Capability> getConsumerCapabilities() {+ return Arrays.asList(+ Capability.inventory,+ Capability.listen+ );+ }@Override- public String getInventoryUri(String agentAssetId, Agent agent) {- String host = agent.getAttributes().hasAttribute("host") ? agent.getAttributes().get("host").getValueAsString() : null;- Integer port = agent.getAttributes().hasAttribute("port") ? agent.getAttributes().get("port").getValueAsDouble().intValue() : null;- // TODO username and password- return "controller2://" + host + ":" + port + "/inventory";+ public Collection<Capability> getProducerCapabilities() {+ return Arrays.asList(+ Capability.discovery,+ Capability.inventory,+ Capability.read,+ Capability.write+ );}@Override- public boolean isSupportingDiscoveryTrigger() {- return true;+ public String buildConsumerEndpoint(Capability capability, String agentAssetId, Agent agent, String deviceKey) {+ String host = getAgentAttributeHost(agent.getAttributes());+ Integer port = getAgentAttributePort(agent.getAttributes());+ if (host == null || port == null) {+ throw new IllegalArgumentException("Host and port must be available in agent: " + agentAssetId);+ }+ switch (capability) {+ case inventory:+ return "controller2://" + host + ":" + port + "/inventory";+ case listen:+ return "controller2://" + host + ":" + port + "/listen/" + deviceKey;+ }+ throw new UnsupportedOperationException("Can't build endpoint for capability: " + capability);}@Override- public String getDiscoveryTriggerUri(String agentAssetId, Agent agent) {- String host = agent.getAttributes().hasAttribute("host") ? agent.getAttributes().get("host").getValueAsString() : null;- Integer port = agent.getAttributes().hasAttribute("port") ? agent.getAttributes().get("port").getValueAsDouble().intValue() : null;- // TODO username and password- return "controller2://" + host + ":" + port + "/discovery";+ public String buildProducerEndpoint(Capability capability, String agentAssetId, Agent agent) {+ String host = getAgentAttributeHost(agent.getAttributes());+ Integer port = getAgentAttributePort(agent.getAttributes());+ if (host == null || port == null) {+ throw new IllegalArgumentException("Host and port must be available in agent: " + agentAssetId);+ }+ switch (capability) {+ case discovery:+ return "controller2://" + host + ":" + port + "/discovery";+ case inventory:+ return "controller2://" + host + ":" + port + "/inventory";+ case read:+ return "controller2://" + host + ":" + port + "/read";+ case write:+ return "controller2://" + host + ":" + port + "/write";+ }+ throw new UnsupportedOperationException("Can't build endpoint for capability: " + capability);+ }++ protected String getAgentAttributeHost(Attributes agentAttributes) {+ return agentAttributes.hasAttribute("host") ? agentAttributes.get("host").getValueAsString() : null;+ }++ protected Integer getAgentAttributePort(Attributes agentAttributes) {+ return agentAttributes.hasAttribute("port") ? agentAttributes.get("port").getValueAsDouble().intValue() : null;}}diff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2Endpoint.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2Endpoint.javaindex 7b80efbe3..1a132048b 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2Endpoint.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2Endpoint.java@@ -23,57 +23,42 @@ import org.apache.camel.Consumer;import org.apache.camel.Processor;import org.apache.camel.Producer;import org.apache.camel.impl.DefaultEndpoint;-import org.apache.camel.spi.UriEndpoint;-import org.apache.camel.spi.UriParam;+import org.openremote.manager.shared.connector.ConnectorComponent;import java.net.MalformedURLException;import java.net.URL;import java.nio.file.Path;-@UriEndpoint(- scheme = "controller2",- title = "OpenRemote Controller 2.x",- syntax = Controller2Component.URI_SYNTAX,- consumerClass = Controller2Consumer.class-)public class Controller2Endpoint extends DefaultEndpoint {final protected Controller2AdapterManager adapterManager;- final protected boolean isDiscovery;- final protected boolean isInventory;+ final protected ConnectorComponent.Capability capability;- @UriParamprotected String host;-- @UriParamprotected Integer port;-- @UriParamprotected String username;-- @UriParamprotected String password;protected String deviceKey;- protected String deviceResourceKey;protected Controller2Adapter adapter;public Controller2Endpoint(String endpointUri, Controller2Component component, Controller2AdapterManager adapterManager, Path path) {super(endpointUri, component);-this.adapterManager = adapterManager;- this.isDiscovery = path.getNameCount() == 1 && path.getName(0).toString().equals("discovery");- this.isInventory= path.getNameCount() == 1 && path.getName(0).toString().equals("inventory");- if (!isDiscovery && !isInventory) {- if (path.getNameCount() == 2) {- this.deviceKey = path.getName(0).toString();- this.deviceResourceKey = path.getName(1).toString();- }- if (deviceKey == null || deviceKey.length() == 0 || deviceResourceKey ==null || deviceResourceKey.length() ==0) {+ if (path.getNameCount() <= 0) {+ throw new IllegalArgumentException(+ "Desired endpoint capability missing from endpoint URI path: " + endpointUri+ );+ }++ capability = ConnectorComponent.Capability.valueOf(path.getName(0).toString());++ if (capability == ConnectorComponent.Capability.listen) {+ if (path.getNameCount() < 2 || (deviceKey = path.getName(1).toString()).length() == 0) {throw new IllegalArgumentException(- "Both device and resource key must be defined for this endpoint: " + endpointUri+ "Listen capability requires /" + ConnectorComponent.Capability.listen.name() + "/<deviceKey> in endpoint URI path: " + endpointUri);}}@@ -125,29 +110,28 @@ public class Controller2Endpoint extends DefaultEndpoint {@Overridepublic Producer createProducer() throws Exception {- if (isDiscovery) {- return new Controller2DiscoveryProducer(this);+ switch(capability) {+ case discovery:+ return new Controller2DiscoveryProducer(this);+ case inventory:+ return new Controller2InventoryProducer(this);+ case read:+ return new Controller2ReadProducer(this);+ case write:+ return new Controller2WriteProducer(this);}- return new Controller2WriteProducer(this, deviceKey, deviceResourceKey);+ throw new IllegalStateException("Unsupported producer capability: " + capability);}@Overridepublic Consumer createConsumer(Processor processor) throws Exception {- if (isDiscovery) {- throw new UnsupportedOperationException(- "Discovery only supports producers (triggering discovery), use an inventory endpoint to receive devices"- );- } else if (isInventory) {- return new Controller2InventoryConsumer(this, processor);- }-- // Read consumer needs specific device and resource so gateway can- // deal with providing push notifications whichever way it needs to- if (deviceKey != null && deviceResourceKey != null) {- return new Controller2ReadConsumer(this, processor, deviceKey, deviceResourceKey);- } else {- throw new UnsupportedOperationException("Read consumer requires device and resource keys");+ switch(capability) {+ case inventory:+ return new Controller2InventoryConsumer(this, processor);+ case listen:+ return new Controller2ListenConsumer(this, processor, deviceKey);}+ throw new IllegalStateException("Unsupported consumer capability: " + capability);}@Overridediff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2InventoryProducer.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2InventoryProducer.javaindex 1b467ced3..cb6fca910 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2InventoryProducer.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2InventoryProducer.java@@ -1,3 +1,22 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */package org.openremote.agent.controller2;import org.apache.camel.Endpoint;@@ -7,12 +26,11 @@ import org.apache.camel.util.URISupport;import java.util.logging.Logger;-public class Controller2InventoryProducer extends DefaultProducer {private static final Logger LOG = Logger.getLogger(Controller2InventoryProducer.class.getName());- public Controller2InventoryProducer(Endpoint endpoint) {+ public Controller2InventoryProducer(Controller2Endpoint endpoint) {super(endpoint);}@@ -23,7 +41,7 @@ public class Controller2InventoryProducer extends DefaultProducer {@Overridepublic void process(Exchange exchange) throws Exception {- // TODO: Implement inventory producer (should support add, remove, update)+ LOG.info("### TODO: Implement inventory producer (should support add, remove, update)");}@Overridediff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ReadConsumer.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ListenConsumer.javasimilarity index 82%rename from connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ReadConsumer.javarename to connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ListenConsumer.javaindex 67048b493..b1b60e2cc 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ReadConsumer.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ListenConsumer.java@@ -25,17 +25,15 @@ import org.openremote.agent.controller2.model.SensorListener;import java.util.logging.Logger;-public class Controller2ReadConsumer extends Controller2Consumer implements SensorListener {+public class Controller2ListenConsumer extends Controller2Consumer implements SensorListener {- private static final Logger LOG = Logger.getLogger(Controller2ReadConsumer.class.getName());+ private static final Logger LOG = Logger.getLogger(Controller2ListenConsumer.class.getName());- protected String deviceKey;- protected String resourceKey;+ final protected String deviceKey;- public Controller2ReadConsumer(Controller2Endpoint endpoint, Processor processor, String deviceKey, String resourceKey) {+ public Controller2ListenConsumer(Controller2Endpoint endpoint, Processor processor, String deviceKey) {super(endpoint, processor);this.deviceKey = deviceKey;- this.resourceKey = resourceKey;}@Override@@ -56,16 +54,13 @@ public class Controller2ReadConsumer extends Controller2Consumer implements Sens}@Override- public String getDeviceResourceKey() {- return resourceKey;- }-- @Override- public void onUpdate(Object newValue) {+ public void onUpdate(String resourceKey, Object newValue) {// Push value into message body and camel type converter can be used to// get value into the required type by the next processor in the routeLOG.fine("Consuming state change from '" + deviceKey + " : " + resourceKey + "': " + newValue);Exchange exchange = getEndpoint().createExchange();+ exchange.getIn().setHeader(Controller2Component.HEADER_DEVICE_KEY, deviceKey);+ exchange.getIn().setHeader(Controller2Component.HEADER_DEVICE_RESOURCE_KEY, resourceKey);exchange.getIn().setBody(newValue);try {getProcessor().process(exchange);diff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ReadProducer.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ReadProducer.javaindex 181fa8713..5824ae493 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ReadProducer.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ReadProducer.java@@ -1,18 +1,34 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */package org.openremote.agent.controller2;-import org.apache.camel.Endpoint;import org.apache.camel.Exchange;import org.apache.camel.impl.DefaultProducer;import org.apache.camel.util.URISupport;-import java.util.logging.Logger;-+import static org.openremote.manager.shared.connector.ConnectorComponent.HEADER_DEVICE_KEY;+import static org.openremote.manager.shared.connector.ConnectorComponent.HEADER_DEVICE_RESOURCE_KEY;public class Controller2ReadProducer extends DefaultProducer {- private static final Logger LOG = Logger.getLogger(Controller2ReadProducer.class.getName());-- public Controller2ReadProducer(Endpoint endpoint) {+ public Controller2ReadProducer(Controller2Endpoint endpoint) {super(endpoint);}@@ -23,7 +39,16 @@ public class Controller2ReadProducer extends DefaultProducer {@Overridepublic void process(Exchange exchange) throws Exception {- // TODO: Implement read producer (should support inOut response for ad-hoc resource reading)+ String deviceKey = exchange.getIn().getHeader(HEADER_DEVICE_KEY, null, String.class);+ String resourceKey = exchange.getIn().getHeader(HEADER_DEVICE_RESOURCE_KEY, null, String.class);+ if (deviceKey == null || "".equals(deviceKey) || resourceKey == null || "".equals(resourceKey)) {+ throw new IllegalArgumentException(+ "Both device and resource key message headers must be defined for read producer"+ );+ }++ Object value = getEndpoint().getAdapter().getControllerState().readResource(deviceKey, resourceKey);+ exchange.getIn().setBody(value);}@Overridediff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2WriteProducer.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2WriteProducer.javaindex 1641fe364..06d663a7c 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2WriteProducer.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2WriteProducer.java@@ -1,3 +1,22 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */package org.openremote.agent.controller2;import org.apache.camel.Endpoint;@@ -8,18 +27,15 @@ import org.apache.camel.util.URISupport;import java.util.logging.Level;import java.util.logging.Logger;+import static org.openremote.manager.shared.connector.ConnectorComponent.HEADER_DEVICE_KEY;+import static org.openremote.manager.shared.connector.ConnectorComponent.HEADER_DEVICE_RESOURCE_KEY;public class Controller2WriteProducer extends DefaultProducer {private static final Logger LOG = Logger.getLogger(Controller2WriteProducer.class.getName());- protected String deviceKey;- protected String resourceKey;-- public Controller2WriteProducer(Endpoint endpoint, String deviceKey, String resourceKey) {+ public Controller2WriteProducer(Controller2Endpoint endpoint) {super(endpoint);- this.deviceKey = deviceKey;- this.resourceKey = resourceKey;}@Override@@ -29,32 +45,19 @@ public class Controller2WriteProducer extends DefaultProducer {@Overridepublic void process(Exchange exchange) throws Exception {- // Extract write related headers- String deviceUri = exchange.getIn().getHeader(- Controller2Component.HEADER_DEVICE_KEY,- this.deviceKey,- String.class- );-- String resourceUri = exchange.getIn().getHeader(- Controller2Component.HEADER_DEVICE_RESOURCE_KEY,- this.resourceKey,- String.class- );-- Object commandValue = exchange.getIn().getBody();-- if (deviceUri == null || "".equals(deviceUri) || resourceUri == null || "".equals(resourceUri)) {+ String deviceKey = exchange.getIn().getHeader(HEADER_DEVICE_KEY, null, String.class);+ String resourceKey = exchange.getIn().getHeader(HEADER_DEVICE_RESOURCE_KEY, null, String.class);+ if (deviceKey == null || "".equals(deviceKey) || resourceKey == null || "".equals(resourceKey)) {throw new IllegalArgumentException(- "Both device and resource URI message headers must be defined for write producer"+ "Both device and resource key message headers must be defined for write producer");}+ Object commandValue = exchange.getIn().getBody();if (LOG.isLoggable(Level.FINE)) {- LOG.fine("Writing to '" + deviceUri + " : " + resourceUri + "' with value: " + commandValue);+ LOG.fine("Writing to '" + deviceKey + " : " + resourceKey+ "' with value: " + commandValue);}-- getEndpoint().getAdapter().getControllerState().writeResource(deviceUri, resourceUri, commandValue);+ getEndpoint().getAdapter().getControllerState().writeResource(deviceKey, resourceKey, commandValue);}@Overridediff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/ControllerState.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/ControllerState.javaindex 99f56f655..78d7df096 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/ControllerState.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/ControllerState.java@@ -97,8 +97,8 @@ public class ControllerState {}public void addSensorListener(SensorListener listener) {- if (listener != null && (listener.getDeviceKey() == null || listener.getDeviceResourceKey() == null)) {- LOG.warning("Ignoring invalid sensor listener (" + controllerUrl + "), missing device or resource key: " + listener);+ if (listener != null && (listener.getDeviceKey() == null)) {+ LOG.warning("Ignoring invalid sensor listener (" + controllerUrl + "), missing device key: " + listener);return;}LOG.fine("Adding sensor listener (" + controllerUrl + "): " + listener);@@ -120,14 +120,7 @@ public class ControllerState {return;}- DeviceResourceMapping resourceMapping = deviceMapping.getResourceMap().get(listener.getDeviceResourceKey());-- if (resourceMapping == null) {- LOG.fine("Device resource key for sensor listener cannot be found so ignoring: " + listener.getDeviceResourceKey());- return;- }-- resourceMapping.removeSensorListener(listener);+ deviceMapping.removeSensorListener(listener);}public void addDeviceListener(DeviceListener listener) {@@ -152,6 +145,30 @@ public class ControllerState {deviceListeners.forEach(this::announceDevices);}+ public Object readResource(String deviceKey, String resourceKey) {+ LOG.fine("Reading resource (" + controllerUrl + "): " + deviceKey + "/" + resourceKey);++ DeviceMapping deviceMapping = deviceMap.get(deviceKey);+ if (deviceMapping == null) {+ LOG.info("Request to read to unknown device key '" + deviceKey + "' will be ignored");+ return null;+ }++ DeviceResourceMapping resourceMapping = deviceMapping.getResourceMap().get(resourceKey);+ if (resourceMapping == null) {+ LOG.info("Request to read to unknown resource key '" + resourceKey + "' will be ignored");+ return null;+ }++ if (resourceMapping.getSensor() == null) {+ LOG.info("Request to read non-sensor device resource '" + resourceKey + "' will be ignored");+ return null;+ }++ // TODO: This only reads the cached value?! It doesn't actually call a command on the controller...+ return resourceMapping.getSensor().getStringValue();+ }+public void writeResource(String deviceKey, String resourceKey, Object resourceValue) {LOG.fine("Writing resource (" + controllerUrl + "): " + deviceKey + "/" + resourceKey + ": " + resourceValue);@@ -230,9 +247,9 @@ public class ControllerState {}@Override- public void onSuccess(org.openremote.entities.controller.Device gatewayDevice) {+ public void onSuccess(Device device) {LOG.fine("Got device '" + deviceName + "' from the controller");- mapping.setDevice(gatewayDevice);+ mapping.setDevice(device);latch.countDown();}});@@ -241,10 +258,12 @@ public class ControllerState {{final CountDownLatch latch = new CountDownLatch(1);- // Register the gateway device (so we get sensor change events and can send commands), this starts+ // Register the device (so we get sensor change events and can send commands), this starts// the polling of sensor values - effectively long-lasting HTTP connection for each device!+ // TODO This will NOT scale! Well, depends on the internal implementation of our HTTP connector...if (mapping.getDevice() != null) {mapping.setRegistrationHandle(+ // TODO: Should be documented somewhere that this call blocks if the HTTP connector is not asynchronouscontroller.registerDevice(mapping.getDevice(), new AsyncRegistrationCallback() {@Overridepublic void onFailure(ControllerResponseCode controllerResponseCode) {@@ -276,14 +295,8 @@ public class ControllerState {return;}- DeviceResourceMapping resourceMapping = deviceMapping.getResourceMap().get(listener.getDeviceResourceKey());-- if (resourceMapping == null) {- LOG.fine("Resource for sensor listener cannot be found so ignoring, resource key was: " + listener.getDeviceResourceKey());- return;- }- LOG.fine("Adding sensor listener to device resource mapping: " + resourceMapping.getResource().getName());- resourceMapping.addSensorListener(listener);+ LOG.fine("Adding sensor listener to device mapping: " + listener.getDeviceKey());+ deviceMapping.addSensorListener(listener);}protected void announceDevices(DeviceListener listener) {@@ -295,14 +308,12 @@ public class ControllerState {protected void processWriteRequest(WriteResourceRequest request) {DeviceMapping deviceMapping = deviceMap.get(request.getDeviceKey());-if (deviceMapping == null) {LOG.info("Request to write to unknown device key '" + request.getDeviceKey() + "' will be ignored");return;}DeviceResourceMapping resourceMapping = deviceMapping.getResourceMap().get(request.getResourceKey());-if (resourceMapping == null) {LOG.info("Request to write to unknown resource key '" + request.getResourceKey() + "' will be ignored");return;@@ -314,7 +325,7 @@ public class ControllerState {if (resourceValue != null && resourceMapping.getSendCommand2() != null) {// This is a switch the command to send varies depending on the value// (whoever invented this better not raise their hand...)- switch(resourceValue.toString().toLowerCase(Locale.ROOT)) {+ switch (resourceValue.toString().toLowerCase(Locale.ROOT)) {case "off":case "false":resourceValue = "off";@@ -334,7 +345,7 @@ public class ControllerState {return;}- LOG.fine("Sending command on '" + deviceMapping.getDevice().getName() + "': " + sendCommand);+ LOG.fine("Sending command on '" + deviceMapping.getDevice().getName() + "': " + sendCommand.getName());// TODO: Callback handling? Should maybe just log something...deviceMapping.getDevice().sendCommand(sendCommand,diff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/DeviceMapping.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/DeviceMapping.javaindex a8013762d..280cdffde 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/DeviceMapping.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/DeviceMapping.java@@ -45,6 +45,18 @@ public class DeviceMapping {protected DeviceRegistrationHandle registrationHandle;protected Map<String, DeviceResourceMapping> resourceMap = new HashMap<>();+ public void addSensorListener(SensorListener listener) {+ for (DeviceResourceMapping deviceResourceMapping : resourceMap.values()) {+ deviceResourceMapping.addSensorListener(listener);+ }+ }++ public void removeSensorListener(SensorListener listener) {+ for (DeviceResourceMapping deviceResourceMapping : resourceMap.values()) {+ deviceResourceMapping.removeSensorListener(listener);+ }+ }+public Device getDevice() {return device;}@@ -73,6 +85,10 @@ public class DeviceMapping {deviceAsset = null;Device device = getDevice();+ // Remove sensor change listeners from sensors+ // TODO Not sure this is necessary, as we always have fresh instances (Device, Sensor) during update...+ resourceMap.values().forEach(DeviceResourceMapping::detachSensorListeners);+if (device != null) {// TODO Take first command protocol as the device type?@@ -130,17 +146,19 @@ public class DeviceMapping {break;}+ String deviceResourceKey = sensor.getName().toLowerCase(Locale.ROOT);+DeviceResource deviceResource = new DeviceResource(sensor.getName(),- sensor.getName().toLowerCase(Locale.ROOT),+ deviceResourceKey,resourceType,access);- DeviceResourceMapping resourceMapping = new DeviceResourceMapping();+ DeviceResourceMapping resourceMapping = new DeviceResourceMapping(deviceResourceKey);resourceMapping.setResource(deviceResource);- resourceMapping.setGatewaySensor(sensor);- getResourceMap().put(deviceResource.getValueAsString(), resourceMapping);+ resourceMapping.setSensor(sensor);+ resourceMap.put(deviceResource.getValueAsString(), resourceMapping);deviceAttributes.put(deviceResource);@@ -174,14 +192,17 @@ public class DeviceMapping {// TODO: All commands are of string type?unassignedCommands.forEach(command -> {++ String deviceResourceKey = command.getName().toLowerCase(Locale.ROOT);+DeviceResource deviceResource = new DeviceResource(command.getName(),- command.getName().toLowerCase(Locale.ROOT),+ deviceResourceKey,AttributeType.STRING,DeviceResource.Access.W);- DeviceResourceMapping resourceMapping = new DeviceResourceMapping();+ DeviceResourceMapping resourceMapping = new DeviceResourceMapping(deviceResourceKey);resourceMapping.setResource(deviceResource);resourceMapping.setSendCommand1(command);getResourceMap().put(deviceResource.getValueAsString(), resourceMapping);diff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/DeviceResourceMapping.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/DeviceResourceMapping.javaindex f473fb4fe..d2dac1d1c 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/DeviceResourceMapping.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/DeviceResourceMapping.java@@ -28,19 +28,14 @@ import org.openremote.manager.shared.device.DeviceResource;*/public class DeviceResourceMapping {- final protected SensorPropertyChangeListener sensorPropertyChangeListener = new SensorPropertyChangeListener();-protected DeviceResource resource;- protected Sensor gatewaySensor;+ protected Sensor sensor;+ protected SensorPropertyChangeListener sensorPropertyChangeListener;protected Command sendCommand1;protected Command sendCommand2;- public void addSensorListener(SensorListener listener) {- sensorPropertyChangeListener.addListener(listener);- }-- public void removeSensorListener(SensorListener listener) {- sensorPropertyChangeListener.removeListener(listener);+ public DeviceResourceMapping(String resourceKey) {+ sensorPropertyChangeListener = new SensorPropertyChangeListener(resourceKey);}public DeviceResource getResource() {@@ -51,14 +46,32 @@ public class DeviceResourceMapping {this.resource = resource;}- public Sensor getGatewaySensor() {- return gatewaySensor;+ public Sensor getSensor() {+ return sensor;+ }++ public void setSensor(Sensor sensor) {+ if (this.sensor != null) {+ this.sensor.removePropertyChangeListener(sensorPropertyChangeListener);+ }+ this.sensor = sensor;+ this.sensor.addPropertyChangeListener(sensorPropertyChangeListener);+ }++ public void addSensorListener(SensorListener sensorListener) {+ if (this.sensor != null) {+ sensorPropertyChangeListener.addListener(sensorListener);+ }+ }++ public void removeSensorListener(SensorListener sensorListener) {+ sensorPropertyChangeListener.removeListener(sensorListener);}- public void setGatewaySensor(Sensor gatewaySensor) {- // Yeah, this is just fantastic... another level of callbacks and indirection- gatewaySensor.addPropertyChangeListener(sensorPropertyChangeListener);- this.gatewaySensor = gatewaySensor;+ public void detachSensorListeners() {+ if (this.sensor != null) {+ this.sensor.removePropertyChangeListener(sensorPropertyChangeListener);+ }}public Command getSendCommand1() {diff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/SensorListener.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/SensorListener.javaindex 176e54dad..32f51976a 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/SensorListener.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/SensorListener.java@@ -19,11 +19,12 @@*/package org.openremote.agent.controller2.model;+/**+ * Listen to all resource value updates of a given device.+ */public interface SensorListener {String getDeviceKey();- String getDeviceResourceKey();-- void onUpdate(Object obj);+ void onUpdate(String resourceKey, Object obj);}diff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/SensorPropertyChangeListener.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/SensorPropertyChangeListener.javaindex 558e0c509..80861bbcb 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/SensorPropertyChangeListener.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/SensorPropertyChangeListener.java@@ -32,7 +32,12 @@ public class SensorPropertyChangeListener implements PropertyChangeListener {private static final Logger LOG = Logger.getLogger(SensorPropertyChangeListener.class.getName());- protected List<SensorListener> listeners = new CopyOnWriteArrayList<>();+ final protected List<SensorListener> listeners = new CopyOnWriteArrayList<>();+ final protected String resourceKey;++ public SensorPropertyChangeListener(String resourceKey) {+ this.resourceKey = resourceKey;+ }public void addListener(SensorListener listener) {listeners.add(listener);@@ -46,7 +51,7 @@ public class SensorPropertyChangeListener implements PropertyChangeListener {public void propertyChange(PropertyChangeEvent evt) {LOG.fine("Propagating controller change event to " + listeners.size() + " sensor listeners: " + evt.getNewValue());listeners.stream().forEach(sensorListener -> {- sensorListener.onUpdate(evt.getNewValue());+ sensorListener.onUpdate(resourceKey, evt.getNewValue());});}}diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java b/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.javaindex 5f8f4b430..449ed4eaf 100644--- a/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java@@ -19,8 +19,6 @@*/package org.openremote.container.persistence;-import org.apache.camel.Predicate;-public class PersistenceEvent<T> {// TODO: Unbounded queue@@ -29,13 +27,6 @@ public class PersistenceEvent<T> {public static final String HEADER_ENTITY_TYPE = PersistenceEvent.class.getSimpleName() + ".ENTITY_TYPE";- public static Predicate matchesEntityType(Class<?> type) {- return exchange -> {- Class<?> entityType = exchange.getIn().getHeader(HEADER_ENTITY_TYPE, Class.class);- return type.isAssignableFrom(entityType);- };- }-public enum Cause {INSERT, UPDATE, DELETE}diff --git a/container/src/main/java/org/openremote/container/web/socket/IsUserInRole.java b/container/src/main/java/org/openremote/container/web/socket/UserPredicates.javasimilarity index 63%rename from container/src/main/java/org/openremote/container/web/socket/IsUserInRole.javarename to container/src/main/java/org/openremote/container/web/socket/UserPredicates.javaindex 72f0e9277..76b94c72a 100644--- a/container/src/main/java/org/openremote/container/web/socket/IsUserInRole.java+++ b/container/src/main/java/org/openremote/container/web/socket/UserPredicates.java@@ -19,26 +19,20 @@*/package org.openremote.container.web.socket;-import org.apache.camel.Exchange;import org.apache.camel.Predicate;-public class IsUserInRole implements Predicate {+public class UserPredicates {- final protected String[] roles;-- public IsUserInRole(String... roles) {- this.roles = roles;- }-- @Override- public boolean matches(Exchange exchange) {- if (roles == null)+ public static Predicate isUserInRole(String... roles) {+ return exchange -> {+ if (roles == null)+ return true;+ WebsocketAuth auth = exchange.getIn().getHeader(WebsocketConstants.AUTH, WebsocketAuth.class);+ for (String role : roles) {+ if (!auth.isUserInRole(role))+ return false;+ }return true;- WebsocketAuth auth = exchange.getIn().getHeader(WebsocketConstants.AUTH, WebsocketAuth.class);- for (String role : roles) {- if (!auth.isUserInRole(role))- return false;- }- return true;+ };}}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/device/DeviceAttributesEditor.java b/manager/client/src/main/java/org/openremote/manager/client/assets/device/DeviceAttributesEditor.javaindex fbcd75406..844477f50 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/device/DeviceAttributesEditor.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/device/DeviceAttributesEditor.java@@ -43,14 +43,11 @@ public class DeviceAttributesEditor extends AttributesEditor<DeviceAttributesEdiString writeButton();}- final protected DeviceAttributes deviceAttributes;-final protected FormGroup deviceActionsGroup = new FormGroup();final protected FormCheckBox enableLiveUpdatesCheckBox = new FormCheckBox();public DeviceAttributesEditor(Environment environment, Container<DeviceAttributesEditor.Style> container, Attributes attributes) {super(environment, container, attributes);- this.deviceAttributes = new DeviceAttributes(attributes.getJsonObject());FormLabel enableLiveUpdates = new FormLabel();enableLiveUpdates.addStyleName("larger");@@ -101,6 +98,7 @@ public class DeviceAttributesEditor extends AttributesEditor<DeviceAttributesEdiDeviceResource deviceResource = new DeviceResource(attribute);+// TODO These actions don't do anythingFlowPanel actionPanel = new FlowPanel();actionPanel.setStyleName("flex layout horizontal center");diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentRoutes.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentRoutes.javaindex 8e1ae1cd0..4b469f1cd 100644--- a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentRoutes.java+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentRoutes.java@@ -20,71 +20,186 @@package org.openremote.manager.server.agent;import org.apache.camel.builder.RouteBuilder;+import org.openremote.agent.controller2.Controller2Component;import org.openremote.container.message.MessageBrokerContext;-import org.openremote.manager.server.event.EventPredicate;import org.openremote.manager.shared.agent.Agent;import org.openremote.manager.shared.agent.InventoryModifiedEvent;import org.openremote.manager.shared.asset.Asset;import org.openremote.manager.shared.connector.ConnectorComponent;+import org.openremote.manager.shared.device.DeviceAttributes;+import java.util.Collection;+import java.util.Set;+import java.util.concurrent.CopyOnWriteArraySet;import java.util.logging.Logger;+import static org.openremote.manager.server.event.EventPredicates.isEventType;+/*** The messaging routes of a running agent instance.+ **/-public abstract class AgentRoutes extends RouteBuilder {+public abstract class AgentRoutes {++ private static final Logger LOG = Logger.getLogger(AgentRoutes.class.getName());- public static String TRIGGER_DISCOVERY_ROUTE(String agentAssetId) {- return "direct:urn:openremote:agent:triggerDiscovery:" + agentAssetId;+ public static String PRODUCER_INVENTORY_ROUTE(String agentAssetId) {+ return "direct:urn:openremote:agent:inventory:" + agentAssetId;}- private static final Logger LOG = Logger.getLogger(AgentRoutes.class.getName());+ public static String PRODUCER_DISCOVERY_ROUTE(String agentAssetId) {+ return "direct:urn:openremote:agent:discovery:" + agentAssetId;+ }+ public static String PRODUCER_READ_ROUTE(String agentAssetId) {+ return "direct:urn:openremote:agent:read:" + agentAssetId;+ }++ public static String PRODUCER_WRITE_ROUTE(String agentAssetId) {+ return "direct:urn:openremote:agent:write:" + agentAssetId;+ }++ final protected Set<String> agentRouteIds = new CopyOnWriteArraySet<>();+ final protected Set<String> deviceRouteIds = new CopyOnWriteArraySet<>();final protected Asset agentAsset;final protected Agent agent;final protected ConnectorComponent connectorComponent;- final protected String inventoryUri;- final protected String triggerDiscoveryUri;public AgentRoutes(Asset agentAsset, Agent agent, ConnectorComponent connectorComponent) {this.agentAsset = agentAsset;this.agent = agent;this.connectorComponent = connectorComponent;+ }- inventoryUri = connectorComponent.getInventoryUri(agentAsset.getId(), agent);- triggerDiscoveryUri = connectorComponent.getDiscoveryTriggerUri(agentAsset.getId(), agent);+ public RouteBuilder buildAgentRoutes() throws Exception {+ return new RouteBuilder() {++ String routeId;+ String endpointUri;++ @Override+ public void configure() throws Exception {+ for (ConnectorComponent.Capability capability : connectorComponent.getConsumerCapabilities()) {+ switch (capability) {+ case inventory:+ routeId = "Agent Inventory Consumer - " + agentAsset.getId();+ endpointUri = connectorComponent.buildConsumerEndpoint(capability, agentAsset.getId(), agent, null);+ if (endpointUri == null)+ throwCapabilityMismatchException(capability);+ from(endpointUri)+ .routeId(routeId)+ .filter(isEventType(InventoryModifiedEvent.class))+ .process(exchange -> {+ handleInventoryModified(+ exchange.getIn().getBody(InventoryModifiedEvent.class)+ );+ });+ agentRouteIds.add(routeId);+ break;+ }+ }++ for (ConnectorComponent.Capability capability : connectorComponent.getProducerCapabilities()) {+ switch (capability) {+ case discovery:+ routeId = "Agent Discovery Producer - " + agentAsset.getId();+ endpointUri = connectorComponent.buildProducerEndpoint(capability, agentAsset.getId(), agent);+ if (endpointUri == null)+ throwCapabilityMismatchException(capability);+ from(PRODUCER_DISCOVERY_ROUTE(agentAsset.getId()))+ .routeId(routeId)+ .to(endpointUri);+ agentRouteIds.add(routeId);+ break;+ case inventory:+ routeId = "Agent Inventory Producer - " + agentAsset.getId();+ endpointUri = connectorComponent.buildProducerEndpoint(capability, agentAsset.getId(), agent);+ if (endpointUri == null)+ throwCapabilityMismatchException(capability);+ from(PRODUCER_INVENTORY_ROUTE(agentAsset.getId()))+ .routeId(routeId)+ .to(endpointUri);+ agentRouteIds.add(routeId);+ break;+ case read:+ routeId = "Agent Read Producer - " + agentAsset.getId();+ endpointUri = connectorComponent.buildProducerEndpoint(capability, agentAsset.getId(), agent);+ if (endpointUri == null)+ throwCapabilityMismatchException(capability);+ from(PRODUCER_READ_ROUTE(agentAsset.getId()))+ .routeId(routeId)+ .to(endpointUri);+ agentRouteIds.add(routeId);+ break;+ case write:+ routeId = "Agent Write Producer - " + agentAsset.getId();+ endpointUri = connectorComponent.buildProducerEndpoint(capability, agentAsset.getId(), agent);+ if (endpointUri == null)+ throwCapabilityMismatchException(capability);+ from(PRODUCER_WRITE_ROUTE(agentAsset.getId()))+ .routeId(routeId)+ .to(endpointUri);+ agentRouteIds.add(routeId);+ break;+ }+ }+ }+ };}- @Override- public void configure() throws Exception {- if (inventoryUri != null) {- from(inventoryUri)- .routeId("Agent Inventory - " + agentAsset.getId())- .filter(new EventPredicate<>(InventoryModifiedEvent.class))- .process(exchange -> {- handleInventoryModified(- exchange.getIn().getBody(InventoryModifiedEvent.class)- );- });+ public RouteBuilder buildDeviceRoutes(Collection<Asset> deviceAssets) throws Exception {+ if (!connectorComponent.getConsumerCapabilities().contains(ConnectorComponent.Capability.listen)) {+ throw new IllegalArgumentException(+ "Connector does not support capability " + ConnectorComponent.Capability.listen + ": " + connectorComponent.getType()+ );}+ return new RouteBuilder() {+ @Override+ public void configure() throws Exception {+ for (Asset deviceAsset : deviceAssets) {+ DeviceAttributes deviceAttributes = new DeviceAttributes(deviceAsset.getAttributes());+ String deviceKey = deviceAttributes.getKey();+ String routeId = "Agent Listen Consumer - " + agentAsset.getId() + "(" + deviceKey + ")";+ String endpointUri = connectorComponent.buildConsumerEndpoint(+ ConnectorComponent.Capability.listen, agentAsset.getId(), agent, deviceKey+ );+ from(endpointUri)+ .routeId(routeId)+ .process(exchange -> {+ String receivedDeviceKey = exchange.getIn().getHeader(Controller2Component.HEADER_DEVICE_KEY, String.class);+ String receivedResourceKey = exchange.getIn().getHeader(Controller2Component.HEADER_DEVICE_RESOURCE_KEY, String.class);+ Object value = exchange.getIn().getBody();+ handleResourceValueUpdate(receivedDeviceKey, receivedResourceKey, value);+ });+ deviceRouteIds.add(routeId);+ }+ }+ };+ }- if (triggerDiscoveryUri != null) {- from(TRIGGER_DISCOVERY_ROUTE(agentAsset.getId()))- .routeId("Agent Trigger Discovery - " + agentAsset.getId())- .to(triggerDiscoveryUri);+ public void stopAgentRoutes(MessageBrokerContext context) throws Exception {+ for (String agentRouteId : agentRouteIds) {+ LOG.fine("Stopping agent route: " + agentRouteId);+ context.stopRoute(agentRouteId);+ context.removeRoute(agentRouteId);}}- public void stop(MessageBrokerContext context) throws Exception {- if (inventoryUri != null) {- context.stopRoute("Agent Inventory - " + agentAsset.getId());- context.removeRoute("Agent Inventory - " + agentAsset.getId());- }- if (triggerDiscoveryUri != null) {- context.stopRoute("Agent Trigger Discovery - " + agentAsset.getId());- context.removeRoute("Agent Trigger Discovery - " + agentAsset.getId());+ public void stopDeviceRoutes(MessageBrokerContext context) throws Exception {+ for (String deviceRouteId : deviceRouteIds) {+ LOG.fine("Stopping agent device route: " + deviceRouteId);+ context.stopRoute(deviceRouteId);+ context.removeRoute(deviceRouteId);}}+ protected void throwCapabilityMismatchException(ConnectorComponent.Capability capability) {+ throw new IllegalStateException(+ "Capability '" + capability +"' announced but component didn't build endpoint: " + connectorComponent.getType()+ );+ }+protected abstract void handleInventoryModified(InventoryModifiedEvent event);++ protected abstract void handleResourceValueUpdate(String deviceKey, String deviceResourceKey, Object value);}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 9bc10cba1..52f1cdec1 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@@ -19,7 +19,6 @@*/package org.openremote.manager.server.agent;-import org.apache.camel.Exchange;import org.apache.camel.FailedToCreateRouteException;import org.apache.camel.builder.RouteBuilder;import org.openremote.container.Container;@@ -28,20 +27,17 @@ import org.openremote.container.message.MessageBrokerContext;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.persistence.PersistenceEvent;import org.openremote.container.util.IdentifierUtil;-import org.openremote.container.web.WebService;-import org.openremote.container.web.socket.IsUserInRole;import org.openremote.manager.server.asset.AssetService;import org.openremote.manager.server.asset.ServerAsset;-import org.openremote.manager.server.event.EventPredicate;import org.openremote.manager.server.event.EventService;import org.openremote.manager.shared.agent.Agent;+import org.openremote.manager.shared.agent.DeviceResourceValueEvent;import org.openremote.manager.shared.agent.InventoryModifiedEvent;-import org.openremote.manager.shared.agent.RefreshInventoryEvent;import org.openremote.manager.shared.asset.Asset;+import org.openremote.manager.shared.asset.AssetInfo;import org.openremote.manager.shared.asset.AssetType;import org.openremote.manager.shared.attribute.Attributes;import org.openremote.manager.shared.connector.ConnectorComponent;-import org.openremote.manager.shared.util.Util;import java.nio.charset.Charset;import java.util.ArrayList;@@ -51,69 +47,46 @@ import java.util.Map;import java.util.logging.Level;import java.util.logging.Logger;-import static org.apache.camel.builder.PredicateBuilder.not;import static org.openremote.container.persistence.PersistenceEvent.Cause.UPDATE;import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_EVENT_TOPIC;-import static org.openremote.container.persistence.PersistenceEvent.matchesEntityType;+import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForAssetType;+import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;--public class AgentService implements ContainerService {+public class AgentService extends RouteBuilder implements ContainerService {private static final Logger LOG = Logger.getLogger(AgentService.class.getName());- protected MessageBrokerService messageBrokerService;+ final protected Map<String, AgentRoutes> agentInstanceMap = new LinkedHashMap<>();+ protected MessageBrokerService messageBrokerService;+ protected MessageBrokerContext messageBrokerContext;protected AssetService assetService;protected ConnectorService connectorService;-- final protected Map<String, AgentRoutes> agentInstanceMap = new LinkedHashMap<>();+ protected AgentServiceEventRoutes agentServiceEventRoutes;@Overridepublic void init(Container container) throws Exception {messageBrokerService = container.getService(MessageBrokerService.class);+ messageBrokerContext = messageBrokerService.getContext();assetService = container.getService(AssetService.class);connectorService = container.getService(ConnectorService.class);- messageBrokerService.getContext().addRoutes(new RouteBuilder() {+ agentServiceEventRoutes = new AgentServiceEventRoutes(+ new DeviceResourceSubscriptions(container.getService(EventService.class))+ ) {@Override- public void configure() throws Exception {-- // If any agent was modified in the database, reconfigure this service- from(PERSISTENCE_EVENT_TOPIC)- .filter(matchesEntityType(Asset.class))- .filter(exchange -> {- PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);- Asset asset = (Asset) persistenceEvent.getEntity();- return AssetType.AGENT.equals(asset.getWellKnownType());- })- .process(exchange -> {- PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);- Asset agent = (Asset) persistenceEvent.getEntity();-- ServerAsset[] agents = assetService.findByType(agent.getRealm(), AssetType.AGENT);- LOG.fine("Reconfigure agents of realm '" + agent.getRealm() + "': " + agents.length);- reconfigureAgents(agents, persistenceEvent.getCause() == UPDATE ? agent : null);- });-- // Dynamically route discovery trigger messages to agents- from(Agent.TOPIC_TRIGGER_DISCOVERY)- .routingSlip(method(AgentService.this, "triggerDiscoverySlip"))- .ignoreInvalidEndpoints();+ protected Asset getAsset(String assetId) {+ return assetService.get(assetId);+ }- from(EventService.INCOMING_EVENT_QUEUE)- .filter(new EventPredicate<>(RefreshInventoryEvent.class))- .choice()- .when(not(new IsUserInRole("write:assets")))- .to("log:org.openremote.event.forbidden?level=INFO&showAll=true&multiline=true")- .otherwise()- .process(exchange -> {- String agentId = exchange.getIn().getBody(RefreshInventoryEvent.class).getAgentId();- LOG.fine("Refreshing inventory of agent: " + agentId);- clearInventory(agentId);- triggerDiscovery(agentId);- });+ @Override+ protected void deleteAssetChildren(String parentAssetId) {+ assetService.deleteChildren(parentAssetId);}- });+ };++ messageBrokerService.getContext().addRoutes(this);+ messageBrokerService.getContext().addRoutes(agentServiceEventRoutes);}@Override@@ -129,30 +102,21 @@ public class AgentService implements ContainerService {@Overridepublic void stop(Container container) throws Exception {-}- protected void clearInventory(String agentId) {- assetService.deleteChildren(agentId);- }-- protected void triggerDiscovery(String agentId) {- if (agentId != null) {- messageBrokerService.getProducerTemplate().sendBody(Agent.TOPIC_TRIGGER_DISCOVERY, agentId);- } else {- /* TODO: Do we need this?- if (realm == null || realm.length() == 0) {- throw new IllegalArgumentException(- "Realm must be provided to trigger discovery of all agents (in that realm)"- );- }- messageBrokerService.getProducerTemplate().sendBodyAndHeader(- Agent.TOPIC_TRIGGER_DISCOVERY,- null,- Agent.TOPIC_TRIGGER_DISCOVERY_HEADER_REALM, realm- );- */- }+ @Override+ public void configure() throws Exception {+ // If any agent was modified in the database, reconfigure this service+ from(PERSISTENCE_EVENT_TOPIC)+ .filter(isPersistenceEventForEntityType(Asset.class))+ .filter(isPersistenceEventForAssetType(AssetType.AGENT))+ .process(exchange -> {+ PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);+ Asset agent = (Asset) persistenceEvent.getEntity();+ ServerAsset[] agents = assetService.findByType(agent.getRealm(), AssetType.AGENT);+ LOG.fine("Reconfigure agents of realm '" + agent.getRealm() + "': " + agents.length);+ reconfigureAgents(agents, persistenceEvent.getCause() == UPDATE ? agent : null);+ });}protected void reconfigureAgents(ServerAsset[] agents, Asset updatedAgent) {@@ -160,7 +124,6 @@ public class AgentService implements ContainerService {for (ServerAsset agentAsset : agents) {Agent agent = new Agent(new Attributes(agentAsset.getAttributes()));if (agent.isEnabled()) {-if (!agentInstanceMap.containsKey(agentAsset.getId())) {LOG.fine("Agent is enabled and was not running: " + agentAsset.getId());startAgent(agentAsset);@@ -244,21 +207,35 @@ public class AgentService implements ContainerService {assetService.delete(combinedAssetId);break;}++ try {+ AgentService.this.stopDeviceRoutes(this);+ AgentService.this.startDeviceRoutes(agentAsset, this);+ } catch (Exception ex) {+ LOG.log(Level.SEVERE, "Error restarting device routes of agent: " + agentAsset.getId(), ex);+ // TODO: We should mark the agent or fire event, or...+ }}- };- agentInstanceMap.put(agentAsset.getId(), agentRoutes);+ @Override+ protected void handleResourceValueUpdate(String deviceKey, String deviceResourceKey, Object value) {+ // TODO Value conversion?+ DeviceResourceValueEvent event = new DeviceResourceValueEvent(+ agentAsset.getId(), deviceKey, deviceResourceKey, value != null ? value.toString() : null+ );+ agentServiceEventRoutes.getDeviceResourceSubscriptions().dispatch(event);+ }+ };try {-- MessageBrokerContext context = messageBrokerService.getContext();- context.addRoutes(agentRoutes);-+ messageBrokerContext.addRoutes(agentRoutes.buildAgentRoutes());+ startDeviceRoutes(agentAsset, agentRoutes);+ agentInstanceMap.put(agentAsset.getId(), agentRoutes);} catch (FailedToCreateRouteException ex) {- LOG.log(Level.SEVERE, "Error starting agent" + agentAsset, ex);+ LOG.log(Level.SEVERE, "Error starting agent: " + agentAsset, ex);// TODO: We should mark the agent or fire event, or...} catch (Exception ex) {- LOG.log(Level.SEVERE, "Error starting agent" + agentAsset, ex);+ LOG.log(Level.SEVERE, "Error starting agent: " + agentAsset, ex);// TODO: We should mark the agent or fire event, or...}}@@ -267,48 +244,30 @@ public class AgentService implements ContainerService {LOG.fine("Stopping agent: " + agentId);if (agentInstanceMap.containsKey(agentId)) {AgentRoutes agentRoutes = agentInstanceMap.remove(agentId);- MessageBrokerContext context = messageBrokerService.getContext();try {- agentRoutes.stop(context);- } catch (FailedToCreateRouteException ex) {- LOG.log(Level.SEVERE, "Error stopping agent" + agentId, ex);- // TODO: We should mark the agent or fire event, or...+ stopDeviceRoutes(agentRoutes);+ agentRoutes.stopAgentRoutes(messageBrokerContext);} catch (Exception ex) {- LOG.log(Level.SEVERE, "Error stopping agent" + agentId, ex);+ LOG.log(Level.SEVERE, "Error stopping agent: " + agentId, ex);// TODO: We should mark the agent or fire event, or...}}}- public String triggerDiscoverySlip(String agentAssetId, Exchange exchange) {- // Find given or all agents of given realm, add their trigger discovery endpoints to the routing slip- List<String> destinations = new ArrayList<>();- if (agentAssetId != null && agentAssetId.length() > 0) {- Asset agentAsset = assetService.get(agentAssetId);- if (agentAsset != null) {- LOG.fine("Routing trigger discovery message for agent: " + agentAssetId);- destinations.add(- AgentRoutes.TRIGGER_DISCOVERY_ROUTE(agentAssetId)- );- }- } else {- String realm = exchange.getIn().getHeader(- Agent.TOPIC_TRIGGER_DISCOVERY_HEADER_REALM, String.class- );- if (realm != null) {- LOG.fine("Routing trigger discovery message for all agents of realm: " + realm);- Asset[] allAgents = assetService.findByType(realm, AssetType.AGENT);- for (Asset agent : allAgents) {- destinations.add(- AgentRoutes.TRIGGER_DISCOVERY_ROUTE(agent.getId())- );- }+ protected void startDeviceRoutes(Asset agentAsset, AgentRoutes agentRoutes) throws Exception {+ // We start listener routes for all device children of the agent asset+ // TODO: We should selectively enable this on a per-device basis+ List<Asset> deviceAssets = new ArrayList<>();+ AssetInfo[] agentChildren = assetService.getChildren(agentAsset.getId());+ for (AssetInfo agentChild : agentChildren) {+ if (agentChild.getWellKnownType() == AssetType.DEVICE) {+ deviceAssets.add(assetService.get(agentChild.getId()));}}+ messageBrokerContext.addRoutes(agentRoutes.buildDeviceRoutes(deviceAssets));+ }- LOG.fine("Triggering discovery on agents: " + destinations);- return Util.toCommaSeparated(- destinations.toArray(new String[destinations.size()])- );+ protected void stopDeviceRoutes(AgentRoutes agentRoutes) throws Exception {+ agentRoutes.stopDeviceRoutes(messageBrokerContext);}}\ No newline at end of filediff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentServiceEventRoutes.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentServiceEventRoutes.javanew file mode 100644index 000000000..f7565debd--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentServiceEventRoutes.java@@ -0,0 +1,182 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.server.agent;++import org.apache.camel.builder.RouteBuilder;+import org.apache.camel.model.ChoiceDefinition;+import org.openremote.container.web.socket.UserPredicates;+import org.openremote.manager.server.event.EventService;+import org.openremote.manager.shared.agent.*;+import org.openremote.manager.shared.asset.Asset;++import java.util.logging.Logger;++import static org.openremote.container.web.socket.UserPredicates.isUserInRole;+import static org.openremote.manager.server.event.EventPredicates.isEventType;+import static org.openremote.manager.shared.connector.ConnectorComponent.HEADER_DEVICE_KEY;+import static org.openremote.manager.shared.connector.ConnectorComponent.HEADER_DEVICE_RESOURCE_KEY;++/**+ * The messaging routes of all running agent instances, central dispatch.+ */+public abstract class AgentServiceEventRoutes extends RouteBuilder {++ private static final Logger LOG = Logger.getLogger(AgentServiceEventRoutes.class.getName());++ final protected DeviceResourceSubscriptions deviceResourceSubscriptions;++ public AgentServiceEventRoutes(DeviceResourceSubscriptions deviceResourceSubscriptions) {+ this.deviceResourceSubscriptions = deviceResourceSubscriptions;+ }++ @Override+ public void configure() throws Exception {+ ChoiceDefinition incomingEventRoute =+ from(EventService.INCOMING_EVENT_QUEUE)+ .routeId("Agent Service Event Route")+ .choice();+ buildInventoryEventRoute(incomingEventRoute);+ buildDeviceEventRoute(incomingEventRoute);+ }++ public DeviceResourceSubscriptions getDeviceResourceSubscriptions() {+ return deviceResourceSubscriptions;+ }++ protected void buildInventoryEventRoute(ChoiceDefinition routeDefinition) {+ routeDefinition+ .when(isEventType(RefreshInventoryEvent.class))+ .choice()+ .when(isUserInRole("write:assets"))+ .process(exchange -> {+ String agentAssetId = exchange.getIn().getBody(RefreshInventoryEvent.class).getAgentId();+ Asset agentAsset = getAsset(agentAssetId);+ if (agentAsset == null)+ return;+ LOG.fine("Clearing inventory of agent: " + agentAssetId);+ deleteAssetChildren(agentAssetId);++ exchange.getIn().getHeaders().clear();+ exchange.getIn().setBody(null);++ exchange.getIn().setHeader(+ "routingSlip",+ AgentRoutes.PRODUCER_DISCOVERY_ROUTE(agentAssetId)+ );+ })+ .routingSlip(header("routingSlip")).ignoreInvalidEndpoints()+ .end()+ .otherwise()+ .to("log:org.openremote.event.forbidden?level=INFO&showAll=true&multiline=true")+ .endChoice();+ }++ protected void buildDeviceEventRoute(ChoiceDefinition routeDefinition) {+ routeDefinition+ .when(isEventType(SubscribeDeviceResourceUpdates.class))+ .choice()+ .when(UserPredicates.isUserInRole("read:assets"))+ .process(exchange -> {+ String sessionKey = EventService.getSessionKey(exchange);+ SubscribeDeviceResourceUpdates event = exchange.getIn().getBody(SubscribeDeviceResourceUpdates.class);+ Asset agentAsset = getAsset(event.getAgentId());+ if (agentAsset == null) {+ LOG.fine("Agent with identifier '" + event.getAgentId() + "' not found, ignoring subscription on session: " + sessionKey);+ return;+ }+ deviceResourceSubscriptions.addSubscription(sessionKey, event);+ })+ .otherwise()+ .to("log:org.openremote.event.forbidden?level=INFO&showAll=true&multiline=true")+ .endChoice()++ .when(isEventType(UnsubscribeDeviceResourceUpdates.class))+ .choice()+ .when(UserPredicates.isUserInRole("read:assets"))+ .process(exchange -> {+ String sessionKey = EventService.getSessionKey(exchange);+ UnsubscribeDeviceResourceUpdates event = exchange.getIn().getBody(UnsubscribeDeviceResourceUpdates.class);+ deviceResourceSubscriptions.removeSubscription(sessionKey, event);+ })+ .otherwise()+ .to("log:org.openremote.event.forbidden?level=INFO&showAll=true&multiline=true")+ .endChoice()++ .when(isEventType(DeviceResourceWrite.class))+ .choice()+ .when(UserPredicates.isUserInRole("write:assets"))+ .process(exchange -> {+ DeviceResourceWrite event = exchange.getIn().getBody(DeviceResourceWrite.class);+ LOG.fine("Processing: " + event);+ exchange.getIn().setHeader(+ "routingSlip",+ AgentRoutes.PRODUCER_WRITE_ROUTE(event.getAgentId())+ );+ exchange.getIn().setHeader(HEADER_DEVICE_KEY, event.getDeviceKey());+ exchange.getIn().setHeader(HEADER_DEVICE_RESOURCE_KEY, event.getDeviceResourceKey());+ exchange.getIn().setBody(event.getValue());+ })+ .routingSlip(header("routingSlip")).ignoreInvalidEndpoints()+ .end()+ .otherwise()+ .to("log:org.openremote.event.forbidden?level=INFO&showAll=true&multiline=true")+ .endChoice()++ .when(isEventType(DeviceResourceRead.class))+ .choice()+ .when(UserPredicates.isUserInRole("read:assets"))+ .process(exchange -> {+ DeviceResourceRead event = exchange.getIn().getBody(DeviceResourceRead.class);+ LOG.fine("Processing: " + event);+ exchange.getIn().setHeader(+ "routingSlip",+ AgentRoutes.PRODUCER_READ_ROUTE(event.getAgentId())+ );+ exchange.getIn().setHeader("agentId", event.getAgentId());+ exchange.getIn().setHeader(HEADER_DEVICE_KEY, event.getDeviceKey());+ exchange.getIn().setHeader(HEADER_DEVICE_RESOURCE_KEY, event.getDeviceResourceKey());+ })+ .routingSlip(header("routingSlip"))+ .ignoreInvalidEndpoints()+ .process(exchange -> {+ // TODO value conversion?+ if (exchange.getIn().getBody() != null) {+ DeviceResourceValueEvent event = new DeviceResourceValueEvent(+ exchange.getIn().getHeader("agentId", String.class),+ exchange.getIn().getHeader(HEADER_DEVICE_KEY, String.class),+ exchange.getIn().getHeader(HEADER_DEVICE_RESOURCE_KEY, String.class),+ exchange.getIn().getBody(String.class)+ );+ exchange.getIn().setBody(event);+ } else {+ LOG.fine("Read did not result in a value, ignoring");+ }+ })+ .to(EventService.OUTGOING_EVENT_QUEUE)+ .endChoice()+ .otherwise()+ .to("log:org.openremote.event.forbidden?level=INFO&showAll=true&multiline=true")+ .endChoice();+ }++ abstract protected Asset getAsset(String assetId);++ abstract protected void deleteAssetChildren(String parentAssetId);+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/ConnectorResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/agent/ConnectorResourceImpl.javaindex 921db04b3..fcbd704bb 100644--- a/manager/server/src/main/java/org/openremote/manager/server/agent/ConnectorResourceImpl.java+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/ConnectorResourceImpl.java@@ -44,7 +44,7 @@ public class ConnectorResourceImpl extends WebResource implements ConnectorResou.map(c -> new Connector(c.getDisplayName(),c.getType(),- c.isSupportingDiscoveryTrigger(),+ c.getProducerCapabilities().contains(ConnectorComponent.Capability.discovery),c.getConnectorSettings())).toArray(Connector[]::new);diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/DeviceResourceSubscription.java b/manager/server/src/main/java/org/openremote/manager/server/agent/DeviceResourceSubscription.javanew file mode 100644index 000000000..167d0a099--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/DeviceResourceSubscription.java@@ -0,0 +1,88 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.server.agent;++import org.openremote.manager.shared.agent.DeviceResourceValueEvent;+import org.openremote.manager.shared.agent.UnsubscribeDeviceResourceUpdates;++import java.util.Objects;++public class DeviceResourceSubscription {++ final protected String agentId;+ final protected String deviceKey;+ final protected long timestamp;++ public DeviceResourceSubscription(String agentId, String deviceKey, long timestamp) {+ Objects.requireNonNull(agentId, "Agent asset identifier must be provided when creating a subscription");+ Objects.requireNonNull(deviceKey, "Device key must be provided when creating a subscription");+ this.agentId = agentId;+ this.deviceKey = deviceKey;+ this.timestamp = timestamp;+ }++ public String getAgentId() {+ return agentId;+ }++ public String getDeviceKey() {+ return deviceKey;+ }++ public long getTimestamp() {+ return timestamp;+ }++ public boolean matches(DeviceResourceValueEvent event) {+ return event.getAgentId().equals(agentId) && event.getDeviceKey().equals(deviceKey);+ }++ public boolean matches(UnsubscribeDeviceResourceUpdates event) {+ return event.getAgentId().equals(agentId) && event.getDeviceKey().equals(deviceKey);+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) return true;+ if (o == null || getClass() != o.getClass()) return false;++ DeviceResourceSubscription that = (DeviceResourceSubscription) o;++ if (!agentId.equals(that.agentId)) return false;+ return deviceKey.equals(that.deviceKey);++ }++ @Override+ public int hashCode() {+ int result = agentId.hashCode();+ result = 31 * result + deviceKey.hashCode();+ return result;+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "agentId='" + agentId + '\'' ++ ", deviceKey='" + deviceKey + '\'' ++ ", timestamp=" + timestamp ++ '}';+ }+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/DeviceResourceSubscriptions.java b/manager/server/src/main/java/org/openremote/manager/server/agent/DeviceResourceSubscriptions.javanew file mode 100644index 000000000..06e88b550--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/DeviceResourceSubscriptions.java@@ -0,0 +1,116 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.server.agent;++import org.openremote.manager.server.event.EventService;+import org.openremote.manager.shared.agent.DeviceResourceValueEvent;+import org.openremote.manager.shared.agent.SubscribeDeviceResourceUpdates;+import org.openremote.manager.shared.agent.UnsubscribeDeviceResourceUpdates;++import java.util.HashSet;+import java.util.Iterator;+import java.util.Map;+import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.Executors;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.TimeUnit;+import java.util.logging.Logger;++// TODO this is quite a hack to get some publish/subscribe system going, it will have to be replaced+public class DeviceResourceSubscriptions {++ private static final Logger LOG = Logger.getLogger(DeviceResourceSubscriptions.class.getName());++ public static final int DEVICE_RESOURCE_SUBSCRIPTION_LIFETIME_SECONDS = 60;++ final protected EventService eventService;+ final protected Map<String, Set<DeviceResourceSubscription>> subscriptions = new ConcurrentHashMap<>();+ final protected ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);++ public DeviceResourceSubscriptions(EventService eventService) {+ this.eventService = eventService;++ scheduler.scheduleAtFixedRate(() -> {+ synchronized (subscriptions) {+ subscriptions.forEach((sessionKey, subscriptions) -> {+ Iterator<DeviceResourceSubscription> it = subscriptions.iterator();+ while (it.hasNext()) {+ DeviceResourceSubscription subscription = it.next();+ if (subscription.timestamp + (DEVICE_RESOURCE_SUBSCRIPTION_LIFETIME_SECONDS * 1000) < System.currentTimeMillis()) {+ LOG.fine("Removing from session '" + sessionKey + "' due to timeout: " + subscription);+ it.remove();+ }+ }+ if (subscriptions.size() ==0) {+ this.subscriptions.remove(sessionKey);+ }+ });++ }+ }, DEVICE_RESOURCE_SUBSCRIPTION_LIFETIME_SECONDS, DEVICE_RESOURCE_SUBSCRIPTION_LIFETIME_SECONDS, TimeUnit.SECONDS);+ }++ public void addSubscription(String sessionKey, SubscribeDeviceResourceUpdates event) {+ DeviceResourceSubscription subscription = new DeviceResourceSubscription(+ event.getAgentId(),+ event.getDeviceKey(),+ System.currentTimeMillis()+ );+ synchronized (subscriptions) {+ Set<DeviceResourceSubscription> subscriptions = this.subscriptions.get(sessionKey);+ if (subscriptions == null) {+ subscriptions = new HashSet<>();+ }+ LOG.fine("Event session '" + sessionKey + "' adding/updating: " + subscription);+ subscriptions.add(subscription);+ this.subscriptions.put(sessionKey, subscriptions);+ }+ }++ public void removeSubscription(String sessionKey, UnsubscribeDeviceResourceUpdates event) {+ synchronized (subscriptions) {+ Set<DeviceResourceSubscription> subscriptions = this.subscriptions.get(sessionKey);+ Iterator<DeviceResourceSubscription> it = subscriptions.iterator();+ while (it.hasNext()) {+ DeviceResourceSubscription subscription = it.next();+ if (subscription.matches(event)) {+ LOG.fine("Event session '" + sessionKey + "' removing: " + subscription);+ it.remove();+ }+ }+ }+ }++ public void dispatch(DeviceResourceValueEvent updatedEvent) {+ synchronized (subscriptions) {+ for (Map.Entry<String, Set<DeviceResourceSubscription>> entry : subscriptions.entrySet()) {+ String sessionKey = entry.getKey();+ for (DeviceResourceSubscription subscription : entry.getValue()) {+ if (subscription.matches(updatedEvent)) {+ LOG.fine("For session '" + sessionKey + "' matching subscription of : " + updatedEvent);+ eventService.sendEvent(sessionKey, updatedEvent);+ }+ }+ }+ }+ }++}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetListenerSubscriptions.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetListenerSubscriptions.javanew file mode 100644index 000000000..cbf873110--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetListenerSubscriptions.java@@ -0,0 +1,162 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.server.asset;++import org.openremote.container.persistence.PersistenceEvent;+import org.openremote.manager.server.event.EventService;+import org.openremote.manager.shared.asset.*;++import java.util.ArrayList;+import java.util.List;+import java.util.Map;+import java.util.Objects;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.Executors;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.TimeUnit;+import java.util.logging.Logger;++// TODO this is quite a hack to get some publish/subscribe system going, it will have to be replaced+// TODO More fine grained selection assets to subscribe to - currently all+public abstract class AssetListenerSubscriptions {++ private static final Logger LOG = Logger.getLogger(AssetListenerSubscriptions.class.getName());++ final protected int ASSET_LISTENERS_MAX_LIFETIME_SECONDS = 60;++ final protected EventService eventService;+ final protected Map<String, Long> subscriptions = new ConcurrentHashMap<>();+ final protected ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);++ public AssetListenerSubscriptions(EventService eventService) {+ this.eventService = eventService;++ // Max life time of listeners is 60 seconds+ scheduler.scheduleAtFixedRate(() -> {+ subscriptions.forEach((sessionKey, timeStamp) -> {+ if (timeStamp + (ASSET_LISTENERS_MAX_LIFETIME_SECONDS * 1000) < System.currentTimeMillis()) {+ LOG.fine("Removing asset listener session due to timeout: " + sessionKey);+ subscriptions.remove(sessionKey);+ }+ });+ }, ASSET_LISTENERS_MAX_LIFETIME_SECONDS, ASSET_LISTENERS_MAX_LIFETIME_SECONDS, TimeUnit.SECONDS);++ }++ public void addSubscription(String sessionKey, SubscribeAssetModified event) {+ Long timestamp = System.currentTimeMillis();+ LOG.fine("Subscribing/updating subscription to asset change events for session: " + sessionKey);+ subscriptions.put(sessionKey, timestamp);+ }++ public void removeSubscription(String sessionKey, UnsubscribeAssetModified event) {+ LOG.fine("Unsubscribing from asset change events for session: " + sessionKey);+ subscriptions.remove(sessionKey);+ }++ public void dispatch(PersistenceEvent persistenceEvent) {+ //noinspection unchecked+ for (AssetModifiedEvent assetModifiedEvent : createAssetModifiedEvents(persistenceEvent)) {+ LOG.fine("Publishing asset modified event to asset listeners: " + subscriptions.size());+ for (String sessionKey : subscriptions.keySet()) {+ eventService.sendEvent(sessionKey, assetModifiedEvent);+ }+ }+ }++ private AssetModifiedEvent[] createAssetModifiedEvents(PersistenceEvent<Asset> persistenceEvent) {+ List<AssetModifiedEvent> events = new ArrayList<>();++ Asset asset = persistenceEvent.getEntity();+ // Assets are a composite structure and we want to be able to fire events that say+ // "a child was removed/inserted for this or that parent". To do this we need to+ // compare old and new entity state, figuring out which parent was modified. There+ // is also the special case of assets without parent: In that case we fire a "children+ // modified" for a special "empty" asset, which clients should consider to be the root+ // item of the whole tree. It has no name, no id, no parent, etc.+ List<String> modifiedParentIds = new ArrayList<>();++ AssetModifiedEvent.Cause cause = null;++ switch (persistenceEvent.getCause()) {+ case INSERT:+ cause = AssetModifiedEvent.Cause.CREATE;+ if (asset.getParentId() != null) {+ modifiedParentIds.add(asset.getParentId());+ } else {+ // The "root without id" asset was modified+ events.add(new AssetModifiedEvent(new AssetInfo(), AssetModifiedEvent.Cause.CHILDREN_MODIFIED));+ }+ break;+ case UPDATE:+ cause = AssetModifiedEvent.Cause.UPDATE;++ // Find out if the asset has a new parent+ String previousParentId = persistenceEvent.getPreviousState("parentId");+ String currentParentId = persistenceEvent.getCurrentState("parentId");+ if (previousParentId == null && currentParentId == null) {+ // The "root without id" asset was modified+ events.add(new AssetModifiedEvent(new AssetInfo(), AssetModifiedEvent.Cause.CHILDREN_MODIFIED));+ } else {+ if (previousParentId == null) {+ // The "root without id" asset was modified+ events.add(new AssetModifiedEvent(new AssetInfo(), AssetModifiedEvent.Cause.CHILDREN_MODIFIED));+ modifiedParentIds.add(currentParentId);+ } else if (currentParentId == null) {+ // The "root without id" asset was modified+ events.add(new AssetModifiedEvent(new AssetInfo(), AssetModifiedEvent.Cause.CHILDREN_MODIFIED));+ modifiedParentIds.add(previousParentId);+ }+ }++ // Only send "children modified" of the parent if the name of the asset changed+ String previousName = persistenceEvent.getPreviousState("name");+ String currentName = persistenceEvent.getCurrentState("name");+ boolean isEqualName = Objects.equals(previousName, currentName);+ if (!isEqualName){+ modifiedParentIds.add(asset.getParentId());+ }++ break;+ case DELETE:+ cause = AssetModifiedEvent.Cause.DELETE;+ if (asset.getParentId() != null) {+ modifiedParentIds.add(asset.getParentId());+ } else {+ // The "root without id" asset was modified+ events.add(new AssetModifiedEvent(new AssetInfo(), AssetModifiedEvent.Cause.CHILDREN_MODIFIED));+ }+ break;+ }++ events.add(new AssetModifiedEvent(asset, cause));++ for (String modifiedParentId : modifiedParentIds) {+ Asset parent = getAsset(modifiedParentId);+ if (parent != null) {+ events.add(new AssetModifiedEvent(parent, AssetModifiedEvent.Cause.CHILDREN_MODIFIED));+ }+ }++ return events.toArray(new AssetModifiedEvent[events.size()]);+ }++ abstract protected Asset getAsset(String assetId);+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetPredicates.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetPredicates.javanew file mode 100644index 000000000..a5577fab8--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetPredicates.java@@ -0,0 +1,45 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.server.asset;++import org.apache.camel.Predicate;+import org.openremote.container.persistence.PersistenceEvent;+import org.openremote.manager.shared.asset.Asset;+import org.openremote.manager.shared.asset.AssetType;++public class AssetPredicates {++ public static Predicate isPersistenceEventForEntityType(Class<?> type) {+ return exchange -> {+ Class<?> entityType = exchange.getIn().getHeader(PersistenceEvent.HEADER_ENTITY_TYPE, Class.class);+ return type.isAssignableFrom(entityType);+ };+ }++ public static Predicate isPersistenceEventForAssetType(AssetType assetType) {+ return exchange -> {+ if (!(exchange.getIn().getBody() instanceof PersistenceEvent))+ return false;+ PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);+ Asset asset = (Asset) persistenceEvent.getEntity();+ return assetType.equals(asset.getWellKnownType());+ };+ }+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.javaindex 974a6362d..ab7836b75 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java@@ -28,35 +28,25 @@ import org.openremote.container.persistence.PersistenceEvent;import org.openremote.container.persistence.PersistenceService;import org.openremote.container.web.WebService;import org.openremote.container.web.socket.WebsocketConstants;-import org.openremote.manager.server.event.EventPredicate;import org.openremote.manager.server.event.EventService;import org.openremote.manager.shared.asset.*;import javax.persistence.EntityManager;import java.sql.PreparedStatement;import java.sql.ResultSet;-import java.util.*;-import java.util.concurrent.ConcurrentHashMap;-import java.util.concurrent.Executors;-import java.util.concurrent.ScheduledExecutorService;-import java.util.concurrent.TimeUnit;-import java.util.logging.Logger;+import java.util.Arrays;+import java.util.List;import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_EVENT_TOPIC;-import static org.openremote.container.persistence.PersistenceEvent.matchesEntityType;+import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;+import static org.openremote.manager.server.event.EventPredicates.isEventType;-public class AssetService implements ContainerService {-- private static final Logger LOG = Logger.getLogger(AssetService.class.getName());-- // TODO this is quite a hack to get some publish/subscribe system going, it will have to be replaced- final protected Map<String, Long> assetListeners = new ConcurrentHashMap<>();- final protected int ASSET_LISTENERS_MAX_LIFETIME_SECONDS = 60;- final protected ScheduledExecutorService assetListenerScheduler = Executors.newScheduledThreadPool(1);+public class AssetService extends RouteBuilder implements ContainerService {protected MessageBrokerService messageBrokerService;protected EventService eventService;protected PersistenceService persistenceService;+ protected AssetListenerSubscriptions assetListenerSubscriptions;@Overridepublic void init(Container container) throws Exception {@@ -64,52 +54,14 @@ public class AssetService implements ContainerService {eventService = container.getService(EventService.class);persistenceService = container.getService(PersistenceService.class);- // Max life time of listeners is 60 seconds- assetListenerScheduler.scheduleAtFixedRate(() -> {- assetListeners.forEach((sessionKey, timeStamp) -> {- if (timeStamp + (ASSET_LISTENERS_MAX_LIFETIME_SECONDS * 1000) < System.currentTimeMillis()) {- LOG.fine("Removing asset listener session due to timeout: " + sessionKey);- assetListeners.remove(sessionKey);- }- });- }, ASSET_LISTENERS_MAX_LIFETIME_SECONDS, ASSET_LISTENERS_MAX_LIFETIME_SECONDS, TimeUnit.SECONDS);-- messageBrokerService.getContext().addRoutes(new RouteBuilder() {+ assetListenerSubscriptions = new AssetListenerSubscriptions(eventService) {@Override- public void configure() throws Exception {-- // TODO None of this is secure or considers the realm of an asset or the logged-in user's realm- from(EventService.INCOMING_EVENT_QUEUE)- .filter(new EventPredicate<>(SubscribeAssetModified.class))- .process(exchange -> {- String sessionKey = exchange.getIn().getHeader(WebsocketConstants.SESSION_KEY, String.class);- Long timestamp = System.currentTimeMillis();- LOG.fine("Subscribing/updating subscription to asset change events for session: " + sessionKey);- assetListeners.put(sessionKey, timestamp);- });-- from(EventService.INCOMING_EVENT_QUEUE)- .filter(new EventPredicate<>(UnsubscribeAssetModified.class))- .process(exchange -> {- String sessionKey = exchange.getIn().getHeader(WebsocketConstants.SESSION_KEY, String.class);- LOG.fine("Unsubscribing from asset change events for session: " + sessionKey);- assetListeners.remove(sessionKey);- });-- from(PERSISTENCE_EVENT_TOPIC)- .filter(matchesEntityType(Asset.class))- .process(exchange -> {- PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);- //noinspection unchecked- for (AssetModifiedEvent assetModifiedEvent : createAssetModifiedEvents(persistenceEvent)) {- LOG.fine("Publishing asset modified event to asset listeners: " + assetListeners.size());- for (String sessionKey : assetListeners.keySet()) {- eventService.sendEvent(sessionKey, assetModifiedEvent);- }- }- });+ protected Asset getAsset(String assetId) {+ return AssetService.this.get(assetId);}- });+ };++ messageBrokerService.getContext().addRoutes(this);}@Override@@ -128,6 +80,37 @@ public class AssetService implements ContainerService {}+ @Override+ public void configure() throws Exception {+ // TODO None of this is secure or considers the realm of an asset or the logged-in user's realm+ from(EventService.INCOMING_EVENT_QUEUE)+ .filter(isEventType(SubscribeAssetModified.class))+ .process(exchange -> {+ String sessionKey = EventService.getSessionKey(exchange);+ assetListenerSubscriptions.addSubscription(+ sessionKey,+ exchange.getIn().getBody(SubscribeAssetModified.class)+ );+ });++ from(EventService.INCOMING_EVENT_QUEUE)+ .filter(isEventType(UnsubscribeAssetModified.class))+ .process(exchange -> {+ String sessionKey = EventService.getSessionKey(exchange);+ assetListenerSubscriptions.removeSubscription(+ sessionKey,+ exchange.getIn().getBody(UnsubscribeAssetModified.class)+ );+ });++ from(PERSISTENCE_EVENT_TOPIC)+ .filter(isPersistenceEventForEntityType(Asset.class))+ .process(exchange -> {+ PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);+ assetListenerSubscriptions.dispatch(persistenceEvent);+ });+ }+public AssetInfo[] getRoot(String realm) {if (realm == null || realm.length() == 0)throw new IllegalArgumentException("Realm must be provided to query assets");@@ -259,82 +242,4 @@ public class AssetService implements ContainerService {if (Arrays.asList(parent.getPath()).contains(asset.getId()))throw new IllegalStateException("Parent asset can not be a child of the asset: " + asset.getParentId());}-- private AssetModifiedEvent[] createAssetModifiedEvents(PersistenceEvent<Asset> persistenceEvent) {- List<AssetModifiedEvent> events = new ArrayList<>();-- Asset asset = persistenceEvent.getEntity();- // Assets are a composite structure and we want to be able to fire events that say- // "a child was removed/inserted for this or that parent". To do this we need to- // compare old and new entity state, figuring out which parent was modified. There- // is also the special case of assets without parent: In that case we fire a "children- // modified" for a special "empty" asset, which clients should consider to be the root- // item of the whole tree. It has no name, no id, no parent, etc.- List<String> modifiedParentIds = new ArrayList<>();-- AssetModifiedEvent.Cause cause = null;-- switch (persistenceEvent.getCause()) {- case INSERT:- cause = AssetModifiedEvent.Cause.CREATE;- if (asset.getParentId() != null) {- modifiedParentIds.add(asset.getParentId());- } else {- // The "root without id" asset was modified- events.add(new AssetModifiedEvent(new AssetInfo(), AssetModifiedEvent.Cause.CHILDREN_MODIFIED));- }- break;- case UPDATE:- cause = AssetModifiedEvent.Cause.UPDATE;-- // Find out if the asset has a new parent- String previousParentId = persistenceEvent.getPreviousState("parentId");- String currentParentId = persistenceEvent.getCurrentState("parentId");- if (previousParentId == null && currentParentId == null) {- // The "root without id" asset was modified- events.add(new AssetModifiedEvent(new AssetInfo(), AssetModifiedEvent.Cause.CHILDREN_MODIFIED));- } else {- if (previousParentId == null) {- // The "root without id" asset was modified- events.add(new AssetModifiedEvent(new AssetInfo(), AssetModifiedEvent.Cause.CHILDREN_MODIFIED));- modifiedParentIds.add(currentParentId);- } else if (currentParentId == null) {- // The "root without id" asset was modified- events.add(new AssetModifiedEvent(new AssetInfo(), AssetModifiedEvent.Cause.CHILDREN_MODIFIED));- modifiedParentIds.add(previousParentId);- }- }-- // Only send "children modified" of the parent if the name of the asset changed- String previousName = persistenceEvent.getPreviousState("name");- String currentName = persistenceEvent.getCurrentState("name");- boolean isEqualName = Objects.equals(previousName, currentName);- if (!isEqualName){- modifiedParentIds.add(asset.getParentId());- }-- break;- case DELETE:- cause = AssetModifiedEvent.Cause.DELETE;- if (asset.getParentId() != null) {- modifiedParentIds.add(asset.getParentId());- } else {- // The "root without id" asset was modified- events.add(new AssetModifiedEvent(new AssetInfo(), AssetModifiedEvent.Cause.CHILDREN_MODIFIED));- }- break;- }-- events.add(new AssetModifiedEvent(asset, cause));-- for (String modifiedParentId : modifiedParentIds) {- Asset parent = get(modifiedParentId);- if (parent != null) {- events.add(new AssetModifiedEvent(parent, AssetModifiedEvent.Cause.CHILDREN_MODIFIED));- }- }-- return events.toArray(new AssetModifiedEvent[events.size()]);- }-}\ No newline at end of filediff --git a/manager/server/src/main/java/org/openremote/manager/server/event/EventPredicate.java b/manager/server/src/main/java/org/openremote/manager/server/event/EventPredicates.javasimilarity index 75%rename from manager/server/src/main/java/org/openremote/manager/server/event/EventPredicate.javarename to manager/server/src/main/java/org/openremote/manager/server/event/EventPredicates.javaindex b2ef7665c..e6267dd61 100644--- a/manager/server/src/main/java/org/openremote/manager/server/event/EventPredicate.java+++ b/manager/server/src/main/java/org/openremote/manager/server/event/EventPredicates.java@@ -19,21 +19,14 @@*/package org.openremote.manager.server.event;-import org.apache.camel.Exchange;import org.apache.camel.Predicate;import org.openremote.manager.shared.event.Event;-public class EventPredicate<T extends Event> implements Predicate {+public class EventPredicates {- final protected Class<T> eventType;-- public EventPredicate(Class<T> eventType) {- this.eventType = eventType;- }-- @Override- public boolean matches(Exchange exchange) {- return exchange.getIn().getBody() != null+ public static <T extends Event> Predicate isEventType(Class<T> eventType) {+ return exchange -> exchange.getIn().getBody() != null&& eventType.isAssignableFrom(exchange.getIn().getBody().getClass());}+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java b/manager/server/src/main/java/org/openremote/manager/server/event/EventService.javaindex 187510da7..b0418a9aa 100644--- a/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java@@ -25,15 +25,11 @@ import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.container.message.MessageBrokerContext;import org.openremote.container.message.MessageBrokerService;-import org.openremote.container.web.socket.IsUserInRole;import org.openremote.container.web.socket.WebsocketConstants;import org.openremote.manager.shared.event.Event;-import java.util.logging.Level;import java.util.logging.Logger;-import static org.apache.camel.builder.PredicateBuilder.not;-public class EventService implements ContainerService {private static final Logger LOG = Logger.getLogger(EventService.class.getName());@@ -61,21 +57,13 @@ public class EventService implements ContainerService {@Overridepublic void configure() throws Exception {- // TODO This is only a simple example for role checking in routes- /*- interceptFrom("websocket://" + WEBSOCKET_EVENTS)- .when(not(new IsUserInRole("read")))- .to("log:org.openremote.event.forbidden?level=INFO&showAll=true&multiline=true")- .stop();- */-from("websocket://" + WEBSOCKET_EVENTS)- .routeId("Receive incoming events on WebSocket")+ .routeId("Receive incoming events on WebSocket session(s)").convertBodyTo(Event.class).to(EventService.INCOMING_EVENT_QUEUE);from(EventService.OUTGOING_EVENT_QUEUE)- .routeId("Send outgoing events to all WebSocket sessions")+ .routeId("Send outgoing events to WebSocket session(s)").to("websocket://" + WEBSOCKET_EVENTS);}});@@ -91,7 +79,7 @@ public class EventService implements ContainerService {}- public static String getSession(Exchange exchange) {+ public static String getSessionKey(Exchange exchange) {return exchange.getIn().getHeader(WebsocketConstants.SESSION_KEY, null, String.class);}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/agent/Agent.java b/manager/shared/src/main/java/org/openremote/manager/shared/agent/Agent.javaindex fcf7cf659..5e9cca21f 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/agent/Agent.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/agent/Agent.java@@ -20,7 +20,6 @@package org.openremote.manager.shared.agent;import elemental.json.Json;-import org.openremote.manager.shared.asset.Asset;import org.openremote.manager.shared.attribute.*;import org.openremote.manager.shared.connector.Connector;@@ -35,20 +34,20 @@ import static org.openremote.manager.shared.connector.Connector.ASSET_ATTRIBUTE_* This information is combined with calls to a {@link org.openremote.manager.shared.connector.ConnectorComponent}* when routes and endpoint URIs are established.* <p>- * Communication with an agent is available through the messaging endpoint {@link #TOPIC_TRIGGER_DISCOVERY}.+ * You can communicate with an agent through events:+ * <ul>+ * <li>{@link RefreshInventoryEvent}</li>+ * <li>{@link SubscribeDeviceResourceUpdates}</li>+ * <li>{@link UnsubscribeDeviceResourceUpdates}</li>+ * <li>{@link DeviceResourceWrite}</li>+ * <li>{@link DeviceResourceRead}</li>+ * <li>{@link DeviceResourceValueEvent}</li>+ * </ul>*/public class Agent {private static final Logger LOG = Logger.getLogger(Agent.class.getName());- /**- * Send messages to this endpoint to trigger discovery of the assets available through an agent.- * If an agent asset identifier is present in the message body, only that agent will execute- * discovery. If the message body is empty, the {@link #TOPIC_TRIGGER_DISCOVERY_HEADER_REALM} header- * must be present, then all running agents of that realm will execute discovery.- */- public static String TOPIC_TRIGGER_DISCOVERY = "seda://urn:openremote:agent:discovery?multipleConsumers=true&waitForTaskToComplete=NEVER";- public static final String TOPIC_TRIGGER_DISCOVERY_HEADER_REALM = "TRIGGER_DISCOVERY_REALM";final protected Attributes attributes;diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/agent/DeviceResourceRead.java b/manager/shared/src/main/java/org/openremote/manager/shared/agent/DeviceResourceRead.javanew file mode 100644index 000000000..680e68705--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/agent/DeviceResourceRead.java@@ -0,0 +1,63 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.shared.agent;++import org.openremote.manager.shared.event.Event;++/**+ * Read a device resource value asynchronously, a {@link DeviceResourceValueEvent} will+ * be send by the service.+ */+public class DeviceResourceRead extends Event {++ protected String agentId;+ protected String deviceKey;+ protected String deviceResourceKey;++ public DeviceResourceRead() {+ }++ public DeviceResourceRead(String agentId, String deviceKey, String deviceResourceKey) {+ this.agentId = agentId;+ this.deviceKey = deviceKey;+ this.deviceResourceKey = deviceResourceKey;+ }++ public String getAgentId() {+ return agentId;+ }++ public String getDeviceKey() {+ return deviceKey;+ }++ public String getDeviceResourceKey() {+ return deviceResourceKey;+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "agentId='" + agentId + '\'' ++ ", deviceKey='" + deviceKey + '\'' ++ ", deviceResourceKey='" + deviceResourceKey + '\'' ++ "}";+ }+}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/agent/DeviceResourceValueEvent.java b/manager/shared/src/main/java/org/openremote/manager/shared/agent/DeviceResourceValueEvent.javanew file mode 100644index 000000000..27cb4149f--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/agent/DeviceResourceValueEvent.java@@ -0,0 +1,66 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.shared.agent;++import org.openremote.manager.shared.event.Event;++public class DeviceResourceValueEvent extends Event {++ protected String agentId;+ protected String deviceKey;+ protected String deviceResourceKey;+ protected String value;++ public DeviceResourceValueEvent() {+ }++ public DeviceResourceValueEvent(String agentId, String deviceKey, String deviceResourceKey, String value) {+ this.agentId = agentId;+ this.deviceKey = deviceKey;+ this.deviceResourceKey = deviceResourceKey;+ this.value = value;+ }++ public String getAgentId() {+ return agentId;+ }++ public String getDeviceKey() {+ return deviceKey;+ }++ public String getDeviceResourceKey() {+ return deviceResourceKey;+ }++ public String getValue() {+ return value;+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "agentId='" + agentId + '\'' ++ ", deviceKey='" + deviceKey + '\'' ++ ", deviceResourceKey='" + deviceResourceKey + '\'' ++ ", value='" + value + '\'' ++ "}";+ }+}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/agent/DeviceResourceWrite.java b/manager/shared/src/main/java/org/openremote/manager/shared/agent/DeviceResourceWrite.javanew file mode 100644index 000000000..1f580b9fb--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/agent/DeviceResourceWrite.java@@ -0,0 +1,69 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.shared.agent;++import org.openremote.manager.shared.event.Event;++/**+ * Write a device resource value, this is a fire-and-forget operation.+ */+public class DeviceResourceWrite extends Event {++ protected String agentId;+ protected String deviceKey;+ protected String deviceResourceKey;+ protected String value;++ public DeviceResourceWrite() {+ }++ public DeviceResourceWrite(String agentId, String deviceKey, String deviceResourceKey, String value) {+ this.agentId = agentId;+ this.deviceKey = deviceKey;+ this.deviceResourceKey = deviceResourceKey;+ this.value = value;+ }++ public String getAgentId() {+ return agentId;+ }++ public String getDeviceKey() {+ return deviceKey;+ }++ public String getDeviceResourceKey() {+ return deviceResourceKey;+ }++ public String getValue() {+ return value;+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "agentId='" + agentId + '\'' ++ ", deviceKey='" + deviceKey + '\'' ++ ", deviceResourceKey='" + deviceResourceKey + '\'' ++ ", value='" + value + '\'' ++ "}";+ }+}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/agent/RefreshInventoryEvent.java b/manager/shared/src/main/java/org/openremote/manager/shared/agent/RefreshInventoryEvent.javaindex 235165b23..fa77a485b 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/agent/RefreshInventoryEvent.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/agent/RefreshInventoryEvent.java@@ -21,6 +21,12 @@ package org.openremote.manager.shared.agent;import org.openremote.manager.shared.event.Event;+/**+ * Tell an agent to delete and re-discover all it's child assets (which are+ * {@link org.openremote.manager.shared.asset.AssetType#DEVICE}). You will+ * receive {@link org.openremote.manager.shared.asset.AssetModifiedEvent}s for+ * any detected changes.+ */public class RefreshInventoryEvent extends Event {protected String agentId;diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/agent/SubscribeDeviceResourceUpdates.java b/manager/shared/src/main/java/org/openremote/manager/shared/agent/SubscribeDeviceResourceUpdates.javanew file mode 100644index 000000000..9681d9c1b--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/agent/SubscribeDeviceResourceUpdates.java@@ -0,0 +1,59 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.shared.agent;++import org.openremote.manager.shared.event.Event;++/**+ * Tell an agent that you are interested in any state changes to readable device+ * resources of a given device. This registration must be repeated or the service+ * will expire the subscription after 60 seconds. While active, any value changes+ * detected on a device resource will be available through+ * {@link DeviceResourceValueEvent}s.+ */+public class SubscribeDeviceResourceUpdates extends Event {++ protected String agentId;+ protected String deviceKey;++ public SubscribeDeviceResourceUpdates() {+ }++ public SubscribeDeviceResourceUpdates(String agentId, String deviceKey) {+ this.agentId = agentId;+ this.deviceKey = deviceKey;+ }++ public String getAgentId() {+ return agentId;+ }++ public String getDeviceKey() {+ return deviceKey;+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() +"{" ++ "agentId='" + agentId + '\'' ++ ", deviceKey='" + deviceKey + '\'' ++ "}";+ }+}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/agent/UnsubscribeDeviceResourceUpdates.java b/manager/shared/src/main/java/org/openremote/manager/shared/agent/UnsubscribeDeviceResourceUpdates.javanew file mode 100644index 000000000..0562c6cd8--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/agent/UnsubscribeDeviceResourceUpdates.java@@ -0,0 +1,56 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.shared.agent;++import org.openremote.manager.shared.event.Event;++/**+ * Tell an agent that you are no longer interested in receiving+ * {@link DeviceResourceValueEvent}s for a given device.+ */+public class UnsubscribeDeviceResourceUpdates extends Event {++ protected String agentId;+ protected String deviceKey;++ public UnsubscribeDeviceResourceUpdates() {+ }++ public UnsubscribeDeviceResourceUpdates(String agentId, String deviceKey) {+ this.agentId = agentId;+ this.deviceKey = deviceKey;+ }++ public String getAgentId() {+ return agentId;+ }++ public String getDeviceKey() {+ return deviceKey;+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() +"{" ++ "assetId='" + agentId + '\'' ++ ", deviceKey='" + deviceKey + '\'' ++ "}";+ }+}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/asset/Asset.java b/manager/shared/src/main/java/org/openremote/manager/shared/asset/Asset.javaindex b32890b85..1ab7d1817 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/asset/Asset.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/asset/Asset.java@@ -210,7 +210,6 @@ public class Asset {", parent ='" + parentId + '\'' +", path ='" + Arrays.toString(path) + '\'' +", coordinates ='" + Arrays.toString(coordinates) + '\'' +- ", attributes='" + (attributes != null ? attributes.toJson() : "null") + '\'' +'}';}}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/connector/ConnectorComponent.java b/manager/shared/src/main/java/org/openremote/manager/shared/connector/ConnectorComponent.javaindex 41f7f9e94..93e3e468f 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/connector/ConnectorComponent.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/connector/ConnectorComponent.java@@ -23,11 +23,53 @@ import org.openremote.manager.shared.agent.Agent;import org.openremote.manager.shared.agent.InventoryModifiedEvent;import org.openremote.manager.shared.attribute.Attributes;+import java.util.Collection;+/*** Connectors to external systems are implemented as Apache Camel components.*/public interface ConnectorComponent {+ String HEADER_DEVICE_KEY = ConnectorComponent.class.getCanonicalName() + ".HEADER_DEVICE_KEY";+ String HEADER_DEVICE_RESOURCE_KEY = ConnectorComponent.class.getCanonicalName() + ".HEADER_DEVICE_RESOURCE_KEY";++ enum Capability {+ /**+ * A producer that reacts to empty "trigger discovery" messages and notifies+ * any {@link #inventory} consumers when discovery of devices or device resources+ * resulted in any inventory changes.+ */+ discovery,++ /**+ * A producer that reacts to inventory update messages ("assign device", etc.), or+ * a consumer that starts {@link InventoryModifiedEvent} exchanges when device or device+ * resource inventory of this connector has been modified.+ */+ inventory,++ /**+ * A producer that can read a device resource value. Device and resource key will+ * be set as headers ({@link #HEADER_DEVICE_KEY}, {@link #HEADER_DEVICE_RESOURCE_KEY}),+ * the value must be returned as the body of the IN message.+ */+ read,++ /**+ * A producer that can write a device resource value. Device and resource key will+ * be set as headers ({@link #HEADER_DEVICE_KEY}, {@link #HEADER_DEVICE_RESOURCE_KEY}),+ * the value will be set as the body of the IN message.+ */+ write,++ /**+ * A consumer that starts exchanges when a device resource value is modified. The device+ * and resource key must be available as headers ({@link #HEADER_DEVICE_KEY},+ * {@link #HEADER_DEVICE_RESOURCE_KEY}), the resource value as body of the IN message.+ */+ listen+ }+/*** Get the unique type descriptor for this connector component*/@@ -39,31 +81,30 @@ public interface ConnectorComponent {String getDisplayName();/**- * Get the settings mask for creating/updating a child asset of the supplied- * parent asset. This is used by clients for user entry of child assets.- *- * If parentAsset is null then child is being provisioned at the root- * (in connector terms this usually means creating agent asset).+ * Get the settings for configuring an {@link Agent} of this component.*/Attributes getConnectorSettings();/**- * Return the inventory endpoint URI where {@link InventoryModifiedEvent}s- * can be received. If null is returned, no inventory actions will be monitored.+ * Consumers supported by this connector.*/- String getInventoryUri(String agentAssetId, Agent agent);+ Collection<Capability> getConsumerCapabilities();/**- * Can this component accept a trigger message for discovery/inventory refresh?+ * Producers supported by this connector.*/- boolean isSupportingDiscoveryTrigger();+ Collection<Capability> getProducerCapabilities();/**- * Return the inventory endpoint URI where a user can send empty messages, which- * should trigger internal discovery of child assets and possible asynchronous- * reaction with {@link InventoryModifiedEvent}s.- * If null is returned, triggering discovery will not be supported.+ * Build a Camel consumer endpoint URI for the given capability and agent configuration. An+ * endpoint URI must be returned if the capability was announced in {@link #getConsumerCapabilities()}.+ * The <code>deviceKey</code> parameter is only available for consumer capability {@link Capability#listen}.*/- String getDiscoveryTriggerUri(String agentAssetId, Agent agent);+ String buildConsumerEndpoint(Capability capability, String agentAssetId, Agent agent, String deviceKey);+ /**+ * Build a Camel producer endpoint URI for the given capability and agent configuration. An+ * endpoint URI must be returned if the capability was announced in {@link #getProducerCapabilities()}.+ */+ String buildProducerEndpoint(Capability capability, String agentAssetId, Agent agent);}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/event/Event.java b/manager/shared/src/main/java/org/openremote/manager/shared/event/Event.javaindex 129a1fd07..75b6e1166 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/event/Event.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/event/Event.java@@ -20,7 +20,7 @@package org.openremote.manager.shared.event;import com.fasterxml.jackson.annotation.*;-import org.openremote.manager.shared.agent.RefreshInventoryEvent;+import org.openremote.manager.shared.agent.*;import org.openremote.manager.shared.asset.AssetModifiedEvent;import org.openremote.manager.shared.asset.SubscribeAssetModified;import org.openremote.manager.shared.asset.UnsubscribeAssetModified;@@ -33,6 +33,11 @@ import org.openremote.manager.shared.util.Util;@JsonSubTypes.Type(value = UnsubscribeAssetModified.class, name = "UNSUBSCRIBE_ASSET_CHANGES"),@JsonSubTypes.Type(value = AssetModifiedEvent.class, name = "ASSET_MODIFIED"),@JsonSubTypes.Type(value = RefreshInventoryEvent.class, name = "REFRESH_INVENTORY"),+ @JsonSubTypes.Type(value = SubscribeDeviceResourceUpdates.class, name = "SUBSCRIBE_DEVICE_RESOURCE_UPDATES"),+ @JsonSubTypes.Type(value = UnsubscribeDeviceResourceUpdates.class, name = "UNSUBSCRIBE_DEVICE_RESOURCE_UPDATES"),+ @JsonSubTypes.Type(value = DeviceResourceValueEvent.class, name = "DEVICE_RESOURCE_UPDATED"),+ @JsonSubTypes.Type(value = DeviceResourceRead.class, name = "DEVICE_RESOURCE_READ"),+ @JsonSubTypes.Type(value = DeviceResourceWrite.class, name = "DEVICE_RESOURCE_WRITE"),/*@JsonSubTypes.Type(value = FlowDeployEvent.class, name = "FLOW_DEPLOY"),@JsonSubTypes.Type(value = FlowDeploymentFailureEvent.class, name = "FLOW_DEPLOYMENT_FAILURE"),diff --git a/test/src/main/groovy/org/openremote/test/BlockingWebsocketEndpoint.groovy b/test/src/main/groovy/org/openremote/test/BlockingWebsocketEndpoint.groovyindex 36a74c988..712db877b 100644--- a/test/src/main/groovy/org/openremote/test/BlockingWebsocketEndpoint.groovy+++ b/test/src/main/groovy/org/openremote/test/BlockingWebsocketEndpoint.groovy@@ -68,7 +68,7 @@ public class BlockingWebsocketEndpoint extends Endpoint {this.startTime = 0}- def awaitMessages() {+ def awaitMessagesAndCloseOnCompletion() {awaitMessages(true)}diff --git a/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovy b/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovyindex 56f7ba7da..35092c9a9 100644--- a/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovy+++ b/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovy@@ -1,23 +1,25 @@package org.openremote.test.controller2-import org.apache.camel.Exchange-import org.apache.camel.Processor-import org.apache.camel.builder.RouteBuilder-import org.openremote.container.message.MessageBrokerService+import org.openremote.manager.client.event.ServerSendEvent+import org.openremote.manager.client.event.bus.EventBusimport org.openremote.manager.server.SampleDataServiceimport org.openremote.manager.server.asset.AssetServiceimport org.openremote.manager.server.event.EventService+import org.openremote.manager.shared.agent.DeviceResourceRead+import org.openremote.manager.shared.agent.DeviceResourceValueEvent+import org.openremote.manager.shared.agent.DeviceResourceWriteimport org.openremote.manager.shared.agent.RefreshInventoryEvent+import org.openremote.manager.shared.agent.SubscribeDeviceResourceUpdates+import org.openremote.manager.shared.agent.UnsubscribeDeviceResourceUpdatesimport org.openremote.manager.shared.asset.Assetimport org.openremote.manager.shared.asset.AssetModifiedEventimport org.openremote.manager.shared.asset.AssetTypeimport org.openremote.manager.shared.asset.SubscribeAssetModifiedimport org.openremote.manager.shared.attribute.AttributeType-import org.openremote.manager.shared.device.DeviceAttributes-import org.openremote.manager.shared.device.DeviceResource+import org.openremote.manager.shared.device.*import org.openremote.test.BlockingWebsocketEndpointimport org.openremote.test.ContainerTrait-import spock.lang.Ignore+import org.openremote.test.EventBusWebsocketEndpointimport spock.lang.Specificationimport spock.util.concurrent.BlockingVariables@@ -39,7 +41,7 @@ class Controller2Test extends Specification implements ContainerTrait {def clientTarget = getClientTarget(createClient(container).build(), serverUri(serverPort), realm)def websocketClient = createWebsocketClient()- when: "we wait a bit for initial state"+ when: "everything has started"sleep(2000)then: "the device assets should be the children of the agent asset"@@ -67,18 +69,18 @@ class Controller2Test extends Specification implements ContainerTrait {def endpoint = new BlockingWebsocketEndpoint(2);def session = connect(websocketClient, endpoint, clientTarget, realm, accessToken, EventService.WEBSOCKET_EVENTS);- and: "we listen to asset modification events"+ and: "listening to asset modification events"session.basicRemote.sendText(container.JSON.writeValueAsString(new SubscribeAssetModified()));- and: "discovery is triggered"+ and: "refreshing the agent's inventory"session.basicRemote.sendText(container.JSON.writeValueAsString(new RefreshInventoryEvent(agentAsset.getId())));- and: "we wait a bit for inventory response"- endpoint.awaitMessages()+ and: "waiting for inventory changes"+ endpoint.awaitMessagesAndCloseOnCompletion()then: "the device assets should be the children of the agent asset"def updatedDeviceAssetInfos = assetService.getChildren(agentAsset.getId())@@ -97,55 +99,102 @@ class Controller2Test extends Specification implements ContainerTrait {stopContainer(container)}-- def "Write actuator and read updated sensor value"() {- given: "a clean result state"- def result = new BlockingVariables(5)-- when: "the server container is started"+ // You might want to GET 192.168.99.100:8083/controller/rest/devices/TestDevice/commands?name=Light1Off+ // to turn off the light whenever this test failed, so you have a clean state to run the test again...+ def "Listen to, write, and read device resource value"() {+ given: "the server container is started"def serverPort = findEphemeralPort()def container = startContainer(defaultConfig(serverPort), defaultServices())- and: "an actuator and a sensor route are started"- String deviceResourceEndpoint = "controller2://192.168.99.100:8083/testdevice/light1switch";- addRoutes(container, new RouteBuilder() {- @Override- void configure() throws Exception {- from("direct:light1switch")- .to(deviceResourceEndpoint);-- from(deviceResourceEndpoint)- .process(new Processor() {- @Override- void process(Exchange exchange) throws Exception {- switch (exchange.getIn().getBody(String.class)) {- case "ON":- result.sensorSwitchedOn = true;- break;- case "OFF":- result.sensorSwitchedoff = true;- break;- default:- throw new IllegalArgumentException("Don't know how to handle: " + exchange.getIn().getBody())- }- }- })- }- })+ and: "an authenticated user"+ def realm = MASTER_REALM;+ def accessToken = authenticate(container, realm, MANAGER_CLIENT_ID, "admin", "admin").token++ and: "a client target"+ def clientTarget = getClientTarget(createClient(container).build(), serverUri(serverPort), realm)+ def websocketClient = createWebsocketClient()++ and: "everything has started"+ sleep(2000)++ and: "an expected result"+ def result = new BlockingVariables(5)- and: "the actuator is switched on"- getMessageProducerTemplate(container).sendBody("direct:light1switch", "ON")+ and: "connecting a client event bus"+ def eventBus = new EventBus()+ def endpoint = new EventBusWebsocketEndpoint(eventBus, container.JSON)+ connect(websocketClient, endpoint, clientTarget, realm, accessToken, EventService.WEBSOCKET_EVENTS);++ and: "preparing to receive device resource updates"+ def resourceUpdatesRegistration = eventBus.register(DeviceResourceValueEvent.class) { event ->+ switch (event.getValue()) {+ case "ON":+ result.lightSwitchedOn = true;+ break;+ case "OFF":+ result.lightSwitchedOff = true;+ break;+ default:+ throw new IllegalArgumentException("Don't know how to handle: " + event)+ }+ }- then: "the sensor value should change"- result.sensorSwitchedOn+ when: "subscribing to device resource updates through an agent"+ def assetService = container.getService(AssetService.class)+ def agentAsset = assetService.get(container.getService(SampleDataService.class).SAMPLE_AGENT_ID)+ eventBus.dispatch(new ServerSendEvent(new SubscribeDeviceResourceUpdates(+ agentAsset.getId(), "testdevice"+ )))++ and: "the device resource value is written"+ eventBus.dispatch(new ServerSendEvent(new DeviceResourceWrite(+ agentAsset.getId(),+ "testdevice",+ "light1switch",+ "ON"+ )))++ then: "the device resource value should change"+ result.lightSwitchedOn++ when: "the device resource value is written again"+ eventBus.dispatch(new ServerSendEvent(new DeviceResourceWrite(+ agentAsset.getId(),+ "testdevice",+ "light1switch",+ "OFF"+ )))++ then: "the device resource value should change again"+ result.lightSwitchedOff++ when: "unsubscribing from device resource updates"+ eventBus.dispatch(new ServerSendEvent(new UnsubscribeDeviceResourceUpdates(+ agentAsset.getId(), "testdevice"+ )))+ eventBus.remove(resourceUpdatesRegistration)++ and: "preparing to receive device resource value with a new handler"+ eventBus.register(DeviceResourceValueEvent.class) { event ->+ switch (event.getValue()) {+ case "off":+ result.receivedReadValue = true;+ break;+ default:+ throw new IllegalArgumentException("Don't know how to handle: " + event)+ }+ }- when: "the actuator is switched off"- getMessageProducerTemplate(container).sendBody("direct:light1switch", "OFF")+ and: "device resource state is read"+ eventBus.dispatch(new ServerSendEvent(new DeviceResourceRead(+ agentAsset.getId(), "testdevice", "light1switch"+ )))- then: "the sensor value should change"- result.sensorSwitchedoff+ then: "the result of that read operation should be received"+ result.receivedReadValuecleanup: "the server should be stopped"+ endpoint.close()stopContainer(container)}}