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
Aligned asset/device models
Christian Bauer99c9c1013751
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 50669da00..4a1dd20e0 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@@ -40,9 +40,9 @@ public class Controller2Component extends UriEndpointComponent implements Connecpublic 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 URI>/<resource URI>]|[discovery|inventory])[?username=username&password=secret]";- public static final String HEADER_DEVICE_URI = Controller2Component.class.getCanonicalName() + ".HEADER_DEVICE_URI";- public static final String HEADER_RESOURCE_URI = Controller2Component.class.getCanonicalName() + ".HEADER_RESOURCE_URI";+ 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";protected final Controller2AdapterManager adapterManager;public static final Attributes SETTINGS;@@ -93,7 +93,6 @@ public class Controller2Component extends UriEndpointComponent implements Connec@Overrideprotected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {try {-URI parsedUri = URI.create(uri);// TODO java.net.URI violates latest RFCs http://bugs.java.com/view_bug.do?bug_id=6587184diff --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 6c1ff9da7..7b80efbe3 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@@ -54,8 +54,8 @@ public class Controller2Endpoint extends DefaultEndpoint {@UriParamprotected String password;- protected String deviceUri;- protected String resourceUri;+ protected String deviceKey;+ protected String deviceResourceKey;protected Controller2Adapter adapter;@@ -68,12 +68,12 @@ public class Controller2Endpoint extends DefaultEndpoint {if (!isDiscovery && !isInventory) {if (path.getNameCount() == 2) {- this.deviceUri = path.getName(0).toString();- this.resourceUri = path.getName(1).toString();+ this.deviceKey = path.getName(0).toString();+ this.deviceResourceKey = path.getName(1).toString();}- if (deviceUri == null || deviceUri.length() == 0 || resourceUri ==null || resourceUri.length() ==0) {+ if (deviceKey == null || deviceKey.length() == 0 || deviceResourceKey ==null || deviceResourceKey.length() ==0) {throw new IllegalArgumentException(- "Both device and resource URI message headers must be defined for this endpoint: " + endpointUri+ "Both device and resource key must be defined for this endpoint: " + endpointUri);}}@@ -128,7 +128,7 @@ public class Controller2Endpoint extends DefaultEndpoint {if (isDiscovery) {return new Controller2DiscoveryProducer(this);}- return new Controller2WriteProducer(this, deviceUri, resourceUri);+ return new Controller2WriteProducer(this, deviceKey, deviceResourceKey);}@Override@@ -143,10 +143,10 @@ public class Controller2Endpoint extends DefaultEndpoint {// Read consumer needs specific device and resource so gateway can// deal with providing push notifications whichever way it needs to- if (deviceUri != null && resourceUri != null) {- return new Controller2ReadConsumer(this, processor, deviceUri, resourceUri);+ if (deviceKey != null && deviceResourceKey != null) {+ return new Controller2ReadConsumer(this, processor, deviceKey, deviceResourceKey);} else {- throw new UnsupportedOperationException("Read consumer requires deviceURI and resource URI");+ throw new UnsupportedOperationException("Read consumer requires device and resource keys");}}diff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2InventoryConsumer.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2InventoryConsumer.javaindex d6c0a2da3..b82e84de2 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2InventoryConsumer.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2InventoryConsumer.java@@ -3,14 +3,11 @@ package org.openremote.agent.controller2;import org.apache.camel.Exchange;import org.apache.camel.Processor;import org.openremote.agent.controller2.model.DeviceListener;-import org.openremote.manager.shared.device.Device;+import org.openremote.manager.shared.asset.Asset;import java.util.logging.Logger;-import static org.openremote.manager.shared.connector.ConnectorComponent.ACTION_CREATE;-import static org.openremote.manager.shared.connector.ConnectorComponent.ACTION_DELETE;-import static org.openremote.manager.shared.connector.ConnectorComponent.ACTION_UPDATE;-import static org.openremote.manager.shared.connector.ConnectorComponent.HEADER_DEVICE_ACTION;+import static org.openremote.manager.shared.connector.ConnectorComponent.*;public class Controller2InventoryConsumer extends Controller2Consumer implements DeviceListener {@@ -33,13 +30,13 @@ public class Controller2InventoryConsumer extends Controller2Consumer implements}@Override- public void onDeviceAdded(Device device) {+ public void onDeviceAdded(Asset device) {if (!isStarted() && !isStarting()) {LOG.fine("Received device added event but consumer hasn't been started");return;}- LOG.fine("Starting new exchange for added device '" + device + "'");+ LOG.fine("Starting new exchange for added device: " + device);Exchange exchange = getEndpoint().createExchange();exchange.getIn().setHeader(HEADER_DEVICE_ACTION, ACTION_CREATE);exchange.getIn().setBody(device);@@ -47,13 +44,13 @@ public class Controller2InventoryConsumer extends Controller2Consumer implements}@Override- public void onDeviceRemoved(Device device) {+ public void onDeviceRemoved(Asset device) {if (!isStarted() && !isStarting()) {LOG.fine("Received device removed event but consumer hasn't been started");return;}- LOG.fine("Starting new exchange for removed device '" + device.getUri() + "'");+ LOG.fine("Starting new exchange for removed device: " + device);Exchange exchange = getEndpoint().createExchange();exchange.getIn().setHeader(HEADER_DEVICE_ACTION, ACTION_DELETE);exchange.getIn().setBody(device);@@ -61,13 +58,13 @@ public class Controller2InventoryConsumer extends Controller2Consumer implements}@Override- public void onDeviceUpdated(Device device) {+ public void onDeviceUpdated(Asset device) {if (!isStarted() && !isStarting()) {LOG.fine("Received device updated event but consumer hasn't been started");return;}- LOG.fine("Starting new exchange for updated device '" + device.getUri() + "'");+ LOG.fine("Starting new exchange for updated device: " + device);Exchange exchange = getEndpoint().createExchange();exchange.getIn().setHeader(HEADER_DEVICE_ACTION, ACTION_UPDATE);exchange.getIn().setBody(device);diff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ReadConsumer.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ReadConsumer.javaindex 5ca2f1f1c..67048b493 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ReadConsumer.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/Controller2ReadConsumer.java@@ -28,13 +28,14 @@ import java.util.logging.Logger;public class Controller2ReadConsumer extends Controller2Consumer implements SensorListener {private static final Logger LOG = Logger.getLogger(Controller2ReadConsumer.class.getName());- protected String deviceUri;- protected String resourceUri;- public Controller2ReadConsumer(Controller2Endpoint endpoint, Processor processor, String deviceUri, String resourceUri) {+ protected String deviceKey;+ protected String resourceKey;++ public Controller2ReadConsumer(Controller2Endpoint endpoint, Processor processor, String deviceKey, String resourceKey) {super(endpoint, processor);- this.deviceUri = deviceUri;- this.resourceUri = resourceUri;+ this.deviceKey = deviceKey;+ this.resourceKey = resourceKey;}@Override@@ -50,20 +51,20 @@ public class Controller2ReadConsumer extends Controller2Consumer implements Sens}@Override- public String getDeviceUri() {- return deviceUri;+ public String getDeviceKey() {+ return deviceKey;}@Override- public String getResourceUri() {- return resourceUri;+ public String getDeviceResourceKey() {+ return resourceKey;}@Overridepublic void onUpdate(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 route- LOG.fine("Consuming state change from '" + deviceUri + " : " + resourceUri + "': " + newValue);+ LOG.fine("Consuming state change from '" + deviceKey + " : " + resourceKey + "': " + newValue);Exchange exchange = getEndpoint().createExchange();exchange.getIn().setBody(newValue);try {diff --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 9a03d439c..1641fe364 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@@ -13,13 +13,13 @@ public class Controller2WriteProducer extends DefaultProducer {private static final Logger LOG = Logger.getLogger(Controller2WriteProducer.class.getName());- protected String deviceUri;- protected String resourceUri;+ protected String deviceKey;+ protected String resourceKey;- public Controller2WriteProducer(Endpoint endpoint, String deviceUri, String resourceUri) {+ public Controller2WriteProducer(Endpoint endpoint, String deviceKey, String resourceKey) {super(endpoint);- this.deviceUri = deviceUri;- this.resourceUri = resourceUri;+ this.deviceKey = deviceKey;+ this.resourceKey = resourceKey;}@Override@@ -31,14 +31,14 @@ public class Controller2WriteProducer extends DefaultProducer {public void process(Exchange exchange) throws Exception {// Extract write related headersString deviceUri = exchange.getIn().getHeader(- Controller2Component.HEADER_DEVICE_URI,- this.deviceUri,+ Controller2Component.HEADER_DEVICE_KEY,+ this.deviceKey,String.class);String resourceUri = exchange.getIn().getHeader(- Controller2Component.HEADER_RESOURCE_URI,- this.resourceUri,+ Controller2Component.HEADER_DEVICE_RESOURCE_KEY,+ this.resourceKey,String.class);diff --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 45d943b5f..99f56f655 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@@ -23,10 +23,12 @@ import org.openremote.console.controller.AsyncRegistrationCallback;import org.openremote.console.controller.Controller;import org.openremote.entities.controller.*;import org.openremote.manager.shared.Consumer;+import org.openremote.manager.shared.device.DeviceAttributes;import java.util.*;import java.util.concurrent.CopyOnWriteArrayList;import java.util.concurrent.CountDownLatch;+import java.util.logging.Level;import java.util.logging.Logger;import java.util.stream.Collectors;@@ -37,6 +39,7 @@ public class ControllerState {final protected String controllerUrl;protected volatile boolean initialized = false;+ // TODO: The concurrency control of these data structures should be revisited when we deal with reconnect/refresh of devicesfinal protected Map<String, DeviceMapping> deviceMap = new LinkedHashMap<>();final protected List<SensorListener> sensorListeners = new CopyOnWriteArrayList<>();final protected List<DeviceListener> deviceListeners = new CopyOnWriteArrayList<>();@@ -65,14 +68,19 @@ public class ControllerState {try {deviceMap.clear();updateDeviceMappings(controller, deviceMapping -> {- LOG.fine("Updating device mapping: " + deviceMapping.getGatewayDevice().getName());- deviceMap.put(deviceMapping.getDevice().getUri(), deviceMapping);+ String deviceKey = new DeviceAttributes(deviceMapping.getDeviceAsset().getAttributes()).getKey();+ LOG.fine("Updating device mapping: " + deviceKey);+ deviceMap.put(deviceKey, deviceMapping);});initialized = true;LOG.fine("Controller state initialized");} catch (InterruptedException e) {initialized = false;LOG.severe("Controller state initialization was interrupted");+ } catch (Exception ex) {+ initialized = false;+ // TODO: better error handling+ LOG.log(Level.SEVERE, "Controller state initialization failed", ex);}LOG.fine("Processing sensor listeners: " + sensorListeners.size());@@ -89,8 +97,8 @@ public class ControllerState {}public void addSensorListener(SensorListener listener) {- if (listener != null && (listener.getDeviceUri() == null || listener.getResourceUri() == null)) {- LOG.warning("Ignoring invalid sensor listener (" + controllerUrl + "), missing device or resource URI: " + listener);+ if (listener != null && (listener.getDeviceKey() == null || listener.getDeviceResourceKey() == null)) {+ LOG.warning("Ignoring invalid sensor listener (" + controllerUrl + "), missing device or resource key: " + listener);return;}LOG.fine("Adding sensor listener (" + controllerUrl + "): " + listener);@@ -101,21 +109,21 @@ public class ControllerState {public void removeSensorListener(SensorListener listener) {LOG.fine("Removing sensor listener (" + controllerUrl + "): " + listener);sensorListeners.remove(listener);- if (listener.getDeviceUri() == null) {+ if (listener.getDeviceKey() == null) {return;}// Unregister the handler- DeviceMapping deviceMapping = deviceMap.get(listener.getDeviceUri());+ DeviceMapping deviceMapping = deviceMap.get(listener.getDeviceKey());if (deviceMapping == null) {- LOG.fine("Device URI for sensor listener cannot be found so ignoring");+ LOG.fine("Device key for sensor listener cannot be found so ignoring: " + listener.getDeviceKey());return;}- DeviceResourceMapping resourceMapping = deviceMapping.getResourceMap().get(listener.getResourceUri());+ DeviceResourceMapping resourceMapping = deviceMapping.getResourceMap().get(listener.getDeviceResourceKey());if (resourceMapping == null) {- LOG.fine("Resource URI for sensor listener cannot be found so ignoring");+ LOG.fine("Device resource key for sensor listener cannot be found so ignoring: " + listener.getDeviceResourceKey());return;}@@ -144,20 +152,20 @@ public class ControllerState {deviceListeners.forEach(this::announceDevices);}- public void writeResource(String deviceUri, String resourceUri, Object resourceValue) {- LOG.fine("Writing resource (" + controllerUrl + "): " + deviceUri + "/" + resourceUri + ": " + resourceValue);+ public void writeResource(String deviceKey, String resourceKey, Object resourceValue) {+ LOG.fine("Writing resource (" + controllerUrl + "): " + deviceKey + "/" + resourceKey + ": " + resourceValue);if (!initialized) {LOG.fine("Controller state not initialized, queuing write request");WriteResourceRequest writeRequest = new WriteResourceRequest();- writeRequest.setDeviceUri(deviceUri);- writeRequest.setResourceUri(resourceUri);+ writeRequest.setDeviceKey(deviceKey);+ writeRequest.setResourceKey(resourceKey);writeRequest.setResourceValue(resourceValue);queuedWriteRequests.add(writeRequest);return;}- processWriteRequest(new WriteResourceRequest(deviceUri, resourceUri, resourceValue));+ processWriteRequest(new WriteResourceRequest(deviceKey, resourceKey, resourceValue));}/* ################################################################################## */@@ -224,7 +232,7 @@ public class ControllerState {@Overridepublic void onSuccess(org.openremote.entities.controller.Device gatewayDevice) {LOG.fine("Got device '" + deviceName + "' from the controller");- mapping.setGatewayDevice(gatewayDevice);+ mapping.setDevice(gatewayDevice);latch.countDown();}});@@ -235,9 +243,9 @@ 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// the polling of sensor values - effectively long-lasting HTTP connection for each device!- if (mapping.getGatewayDevice() != null) {+ if (mapping.getDevice() != null) {mapping.setRegistrationHandle(- controller.registerDevice(mapping.getGatewayDevice(), new AsyncRegistrationCallback() {+ controller.registerDevice(mapping.getDevice(), new AsyncRegistrationCallback() {@Overridepublic void onFailure(ControllerResponseCode controllerResponseCode) {LOG.info("Failed to register device '" + deviceName + "' with the controller: " + controllerResponseCode);@@ -261,17 +269,17 @@ public class ControllerState {}protected void processSensorListener(SensorListener listener) {- DeviceMapping deviceMapping = deviceMap.get(listener.getDeviceUri());+ DeviceMapping deviceMapping = deviceMap.get(listener.getDeviceKey());if (deviceMapping == null) {- LOG.fine("Device mapping for sensor listener cannot be found so ignoring, device URI was: " + listener.getDeviceUri());+ LOG.fine("Device mapping for sensor listener cannot be found so ignoring, device key was: " + listener.getDeviceKey());return;}- DeviceResourceMapping resourceMapping = deviceMapping.getResourceMap().get(listener.getResourceUri());+ DeviceResourceMapping resourceMapping = deviceMapping.getResourceMap().get(listener.getDeviceResourceKey());if (resourceMapping == null) {- LOG.fine("Resource for sensor listener cannot be found so ignoring, resource URI was: " + listener.getResourceUri());+ 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());@@ -281,22 +289,22 @@ public class ControllerState {protected void announceDevices(DeviceListener listener) {LOG.fine("Announcing " + deviceMap.size() + " devices on listener: " + listener);deviceMap.values().stream().forEach(deviceMapping -> {- listener.onDeviceAdded(deviceMapping.getDevice());+ listener.onDeviceAdded(deviceMapping.getDeviceAsset());});}protected void processWriteRequest(WriteResourceRequest request) {- DeviceMapping deviceMapping = deviceMap.get(request.getDeviceUri());+ DeviceMapping deviceMapping = deviceMap.get(request.getDeviceKey());if (deviceMapping == null) {- LOG.info("Request to write to unknown device URI '" + request.getDeviceUri() + "' will be ignored");+ LOG.info("Request to write to unknown device key '" + request.getDeviceKey() + "' will be ignored");return;}- DeviceResourceMapping resourceMapping = deviceMapping.getResourceMap().get(request.getResourceUri());+ DeviceResourceMapping resourceMapping = deviceMapping.getResourceMap().get(request.getResourceKey());if (resourceMapping == null) {- LOG.info("Request to write to unknown resource URI '" + request.getResourceUri() + "' will be ignored");+ LOG.info("Request to write to unknown resource key '" + request.getResourceKey() + "' will be ignored");return;}@@ -322,24 +330,24 @@ public class ControllerState {}if (sendCommand == null) {- LOG.info("Unable to determine the command to send for " + request.getResourceValue() + " : " + request.getResourceUri());+ LOG.info("Unable to determine the command to send for " + request.getResourceValue() + " : " + request.getResourceKey());return;}- LOG.fine("Sending command on '" + deviceMapping.getGatewayDevice().getName() + "': " + sendCommand);+ LOG.fine("Sending command on '" + deviceMapping.getDevice().getName() + "': " + sendCommand);// TODO: Callback handling? Should maybe just log something...- deviceMapping.getGatewayDevice().sendCommand(+ deviceMapping.getDevice().sendCommand(sendCommand,(resourceValue != null ? resourceValue.toString() : null),new AsyncControllerCallback<CommandResponse>() {@Overridepublic void onFailure(ControllerResponseCode controllerResponseCode) {-+ // TODO Components should offer a route for logging, so we can store (error) events}@Overridepublic void onSuccess(CommandResponse commandResponse) {-+ // TODO Components should offer a route for logging, so we can store (succes) events}});diff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/DeviceListener.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/DeviceListener.javaindex 728ea5599..8a65d18fd 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/DeviceListener.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/DeviceListener.java@@ -19,7 +19,7 @@*/package org.openremote.agent.controller2.model;-import org.openremote.manager.shared.device.Device;+import org.openremote.manager.shared.asset.Asset;/*** Used by IOT connectors to announce changes to devices.@@ -28,9 +28,11 @@ import org.openremote.manager.shared.device.Device;*/public interface DeviceListener {- void onDeviceAdded(Device device);+ void onDeviceAdded(Asset device);- void onDeviceRemoved(Device device);+ // TODO Not used, implement!+ void onDeviceRemoved(Asset device);- void onDeviceUpdated(Device device);+ // TODO Not used, implement!+ void onDeviceUpdated(Asset device);}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 8db908a33..a8013762d 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@@ -23,9 +23,12 @@ import org.openremote.console.controller.Controller;import org.openremote.console.controller.DeviceRegistrationHandle;import org.openremote.container.util.IdentifierUtil;import org.openremote.entities.controller.Command;+import org.openremote.entities.controller.Device;import org.openremote.entities.controller.Sensor;+import org.openremote.manager.shared.asset.Asset;+import org.openremote.manager.shared.asset.AssetType;import org.openremote.manager.shared.attribute.AttributeType;-import org.openremote.manager.shared.device.Device;+import org.openremote.manager.shared.device.DeviceAttributes;import org.openremote.manager.shared.device.DeviceResource;import java.nio.charset.Charset;@@ -37,19 +40,11 @@ import java.util.stream.Stream;*/public class DeviceMapping {- protected org.openremote.entities.controller.Device gatewayDevice;protected Device device;+ protected Asset deviceAsset;protected DeviceRegistrationHandle registrationHandle;protected Map<String, DeviceResourceMapping> resourceMap = new HashMap<>();- public org.openremote.entities.controller.Device getGatewayDevice() {- return gatewayDevice;- }-- public void setGatewayDevice(org.openremote.entities.controller.Device gatewayDevice) {- this.gatewayDevice = gatewayDevice;- }-public Device getDevice() {return device;}@@ -58,6 +53,10 @@ public class DeviceMapping {this.device = device;}+ public Asset getDeviceAsset() {+ return deviceAsset;+ }+public DeviceRegistrationHandle getRegistrationHandle() {return registrationHandle;}@@ -70,42 +69,41 @@ public class DeviceMapping {return resourceMap;}- public void setResourceMap(Map<String, DeviceResourceMapping> resourceMap) {- this.resourceMap = resourceMap;- }-public void update(List<Controller.WidgetCommandInfo> widgetCommandInfos) {- setDevice(null);- org.openremote.entities.controller.Device gatewayDevice = getGatewayDevice();+ deviceAsset = null;+ Device device = getDevice();++ if (device != null) {++ // TODO Take first command protocol as the device type?+ // String deviceProtocol = device.getCommands().get(0).getProtocol().toUpperCase();++ deviceAsset = new Asset(device.getName(), AssetType.DEVICE);- if (gatewayDevice != null) {- Device device = new Device();- setDevice(device);// TODO: Stable device identifier generation?- device.setId(+ deviceAsset.setId(IdentifierUtil.getEncodedHash(- gatewayDevice.getName().toLowerCase(Locale.ROOT).getBytes(Charset.forName("utf-8"))+ device.getName().toLowerCase(Locale.ROOT).getBytes(Charset.forName("utf-8"))));- device.setUri(gatewayDevice.getName());- device.setName(gatewayDevice.getName());- if (gatewayDevice.getCommands() == null || gatewayDevice.getCommands().size() == 0) {+ DeviceAttributes deviceAttributes = new DeviceAttributes(deviceAsset.getAttributes());+ deviceAttributes.setKey(device.getName().toLowerCase(Locale.ROOT));++ if (device.getCommands() == null || device.getCommands().size() == 0) {return;}- // Get Device type// TODO: Controller API needs to provide Make & model info for the device- // Take first command protocol as the device type- device.setType(gatewayDevice.getCommands().get(0).getProtocol().toUpperCase());+ //deviceAttributes.setMakeAndModel();+// Get Device resources and capabilities- List<DeviceResource> resources = new ArrayList<>();List<Integer> assignedCommands = new ArrayList<>();// Go through sensors - any used by slider and switch// widgets can be RW resources- for (Sensor sensor : gatewayDevice.getSensors()) {+ for (Sensor sensor : device.getSensors()) {Command sensorCommand = sensor.getCommand();assignedCommands.add(sensorCommand.getId());Controller.WidgetCommandInfo matchingWidgetInfo =@@ -114,19 +112,43 @@ public class DeviceMapping {.findFirst().orElseGet(() -> null);- DeviceResource dr = new DeviceResource(sensor.getName());- dr.setUri(sensor.getName().toLowerCase(Locale.ROOT));+ AttributeType resourceType;+ DeviceResource.Access access;+ switch (sensor.getType()) {+ case SWITCH:+ resourceType = AttributeType.BOOLEAN;+ access = matchingWidgetInfo != null ? DeviceResource.Access.RW : DeviceResource.Access.R;+ break;+ case RANGE:+ case LEVEL:+ resourceType = AttributeType.INTEGER;+ access = matchingWidgetInfo != null ? DeviceResource.Access.RW : DeviceResource.Access.R;+ break;+ default:+ resourceType = AttributeType.STRING;+ access = DeviceResource.Access.R;+ break;+ }++ DeviceResource deviceResource = new DeviceResource(+ sensor.getName(),+ sensor.getName().toLowerCase(Locale.ROOT),+ resourceType,+ access+ );+DeviceResourceMapping resourceMapping = new DeviceResourceMapping();- resourceMapping.setResource(dr);+ resourceMapping.setResource(deviceResource);resourceMapping.setGatewaySensor(sensor);- resources.add(dr);- getResourceMap().put(dr.getUri(), resourceMapping);+ getResourceMap().put(deviceResource.getValueAsString(), resourceMapping);++ deviceAttributes.put(deviceResource);if (matchingWidgetInfo != null) {if (matchingWidgetInfo.getCommandId1() > 0) {assignedCommands.add(matchingWidgetInfo.getCommandId1());resourceMapping.setSendCommand1(- gatewayDevice.getCommands().stream()+ device.getCommands().stream().filter(command -> command.getId() == matchingWidgetInfo.getCommandId1()).findFirst().orElseGet(() -> null)@@ -134,7 +156,7 @@ public class DeviceMapping {}if (matchingWidgetInfo.getCommandId2() > 0) {resourceMapping.setSendCommand2(- gatewayDevice.getCommands().stream()+ device.getCommands().stream().filter(command -> command.getId() == matchingWidgetInfo.getCommandId2()).findFirst().orElseGet(() -> null)@@ -142,42 +164,32 @@ public class DeviceMapping {assignedCommands.add(matchingWidgetInfo.getCommandId2());}}-- switch (sensor.getType()) {- case SWITCH:- dr.setType(AttributeType.BOOLEAN);- dr.setAccess(matchingWidgetInfo != null ? DeviceResource.Access.RW : DeviceResource.Access.R);- break;- case RANGE:- case LEVEL:- dr.setType(AttributeType.INTEGER);- dr.setAccess(matchingWidgetInfo != null ? DeviceResource.Access.RW : DeviceResource.Access.R);- break;- default:- dr.setType(AttributeType.STRING);- dr.setAccess(DeviceResource.Access.R);- break;- }}// Add any commands not already covered as write resources// Assume they are W resources with null data type- Stream<Command> unassignedCommands = gatewayDevice.getCommands().stream().filter(command -> !assignedCommands.contains(command.getId()));+ Stream<Command> unassignedCommands = device.getCommands().stream().filter(+ command -> !assignedCommands.contains(command.getId())+ );+ // TODO: All commands are of string type?unassignedCommands.forEach(command -> {- DeviceResource dr = new DeviceResource(command.getName());- dr.setUri(command.getName().toLowerCase(Locale.ROOT));- dr.setType(null);- dr.setAccess(DeviceResource.Access.W);+ DeviceResource deviceResource = new DeviceResource(+ command.getName(),+ command.getName().toLowerCase(Locale.ROOT),+ AttributeType.STRING,+ DeviceResource.Access.W+ );DeviceResourceMapping resourceMapping = new DeviceResourceMapping();- resourceMapping.setResource(dr);+ resourceMapping.setResource(deviceResource);resourceMapping.setSendCommand1(command);- resources.add(dr);- getResourceMap().put(dr.getUri(), resourceMapping);+ getResourceMap().put(deviceResource.getValueAsString(), resourceMapping);++ deviceAttributes.put(deviceResource);});- device.setResources(resources.toArray(new DeviceResource[resources.size()]));+ deviceAsset.setAttributes(deviceAttributes.getJsonObject());}}}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 495662b83..176e54dad 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@@ -21,9 +21,9 @@ package org.openremote.agent.controller2.model;public interface SensorListener {- String getDeviceUri();+ String getDeviceKey();- String getResourceUri();+ String getDeviceResourceKey();void onUpdate(Object obj);}diff --git a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/WriteResourceRequest.java b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/WriteResourceRequest.javaindex bfb9062d1..6a5a65963 100644--- a/connector/controller2/src/main/java/org/openremote/agent/controller2/model/WriteResourceRequest.java+++ b/connector/controller2/src/main/java/org/openremote/agent/controller2/model/WriteResourceRequest.java@@ -24,33 +24,33 @@ package org.openremote.agent.controller2.model;*/public class WriteResourceRequest {- protected String deviceUri;- protected String resourceUri;+ protected String deviceKey;+ protected String resourceKey;protected Object resourceValue;public WriteResourceRequest() {}- public WriteResourceRequest(String deviceUri, String resourceUri, Object resourceValue) {- this.deviceUri = deviceUri;- this.resourceUri = resourceUri;+ public WriteResourceRequest(String deviceKey, String resourceKey, Object resourceValue) {+ this.deviceKey = deviceKey;+ this.resourceKey = resourceKey;this.resourceValue = resourceValue;}- public String getDeviceUri() {- return deviceUri;+ public String getDeviceKey() {+ return deviceKey;}- public void setDeviceUri(String deviceUri) {- this.deviceUri = deviceUri;+ public void setDeviceKey(String deviceKey) {+ this.deviceKey = deviceKey;}- public String getResourceUri() {- return resourceUri;+ public String getResourceKey() {+ return resourceKey;}- public void setResourceUri(String resourceUri) {- this.resourceUri = resourceUri;+ public void setResourceKey(String resourceKey) {+ this.resourceKey = resourceKey;}public Object getResourceValue() {diff --git a/manager/server/src/main/java/org/openremote/manager/server/SampleDataService.java b/manager/server/src/main/java/org/openremote/manager/server/SampleDataService.javaindex c9fe2aa60..9502f7da2 100644--- a/manager/server/src/main/java/org/openremote/manager/server/SampleDataService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/SampleDataService.java@@ -40,6 +40,8 @@ import org.openremote.manager.shared.asset.AssetAttributeType;import org.openremote.manager.shared.asset.AssetType;import org.openremote.manager.shared.attribute.*;import org.openremote.manager.shared.connector.Connector;+import org.openremote.manager.shared.device.DeviceAttributes;+import org.openremote.manager.shared.device.DeviceResource;import rx.Observable;import javax.ws.rs.core.UriBuilder;@@ -48,6 +50,8 @@ import java.util.Arrays;import java.util.List;import static org.openremote.manager.shared.Constants.*;+import static org.openremote.manager.shared.attribute.AttributeType.BOOLEAN;+import static org.openremote.manager.shared.attribute.AttributeType.INTEGER;import static org.openremote.manager.shared.attribute.AttributeType.STRING;import static rx.Observable.fromCallable;@@ -306,31 +310,31 @@ public class SampleDataService implements ContainerService {wallpanelAttributes.put(new Attribute("temperature", AttributeType.FLOAT, Json.create(21.3)).setMetadata(new Metadata()- .addElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.SENSOR.getJsonValue()))- .addElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Actual Temperature")))- .addElement(new MetadataElement("scale", "urn:openremote:scale", Json.create("celcius")))+ .putElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.SENSOR.getJsonValue()))+ .putElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Actual Temperature")))+ .putElement(new MetadataElement("scale", "urn:openremote:scale", Json.create("celcius")))),new Attribute("setpointSensor", AttributeType.FLOAT, Json.create(22.5)).setMetadata(new Metadata()- .addElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.SENSOR.getJsonValue()))- .addElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Setpoint Temperature")))- .addElement(new MetadataElement("scale", "urn:openremote:scale", Json.create("celcius")))+ .putElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.SENSOR.getJsonValue()))+ .putElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Setpoint Temperature")))+ .putElement(new MetadataElement("scale", "urn:openremote:scale", Json.create("celcius")))),new Attribute("setpointActuator", AttributeType.FLOAT, Json.create(22.5)).setMetadata(new Metadata()- .addElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.ACTUATOR.getJsonValue()))- .addElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Setpoint Control")))- .addElement(new MetadataElement("scale", "urn:openremote:scale", Json.create("celcius")))+ .putElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.ACTUATOR.getJsonValue()))+ .putElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Setpoint Control")))+ .putElement(new MetadataElement("scale", "urn:openremote:scale", Json.create("celcius")))),new Attribute("statusSensor", AttributeType.BOOLEAN, Json.create(true)).setMetadata(new Metadata()- .addElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.SENSOR.getJsonValue()))- .addElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("On/Off Status")))+ .putElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.SENSOR.getJsonValue()))+ .putElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("On/Off Status")))),new Attribute("statusActuator", AttributeType.BOOLEAN, Json.create(true)).setMetadata(new Metadata()- .addElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.ACTUATOR.getJsonValue()))- .addElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("On/Off Control")))+ .putElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.ACTUATOR.getJsonValue()))+ .putElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("On/Off Control")))));wallpanel.setAttributes(wallpanelAttributes.getJsonObject());@@ -344,8 +348,8 @@ public class SampleDataService implements ContainerService {presenceAttributes.put(new Attribute("presence", AttributeType.BOOLEAN, Json.create(false)).setMetadata(new Metadata()- .addElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.SENSOR.getJsonValue()))- .addElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Presence Detected")))+ .putElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.SENSOR.getJsonValue()))+ .putElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Presence Detected")))));presence.setAttributes(presenceAttributes.getJsonObject());@@ -359,8 +363,8 @@ public class SampleDataService implements ContainerService {windowsAttributes.put(new Attribute("status", AttributeType.BOOLEAN, Json.create(false)).setMetadata(new Metadata()- .addElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.SENSOR.getJsonValue()))- .addElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Windows Open")))+ .putElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.SENSOR.getJsonValue()))+ .putElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Windows Open")))));windows.setAttributes(windowsAttributes.getJsonObject());@@ -374,11 +378,36 @@ public class SampleDataService implements ContainerService {valveAttributes.put(new Attribute("status", AttributeType.BOOLEAN, Json.create(true)).setMetadata(new Metadata()- .addElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.SENSOR.getJsonValue()))- .addElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Valve Open")))+ .putElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.SENSOR.getJsonValue()))+ .putElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Valve Open")))));valve.setAttributes(valveAttributes.getJsonObject());assetService.create(valve);++/* TODO Update sample data+ ServerAsset lightSwitch = new ServerAsset(room3);+ lightSwitch.setName("Light Switch");+ lightSwitch.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));+ lightSwitch.setType(AssetType.DEVICE);+ DeviceAttributes lightSwitchAttributes = new DeviceAttributes();++ lightSwitchAttributes.put(+ new DeviceResource("Light1Switch", "light1switch", BOOLEAN, DeviceResource.Access.RW),+ new DeviceResource("Light1Slider", "light1slider", INTEGER, DeviceResource.Access.RW),+ new DeviceResource("Light1BrightnessSet", "light1brightnessset", INTEGER, DeviceResource.Access.W)+ );++ lightSwitchAttributes.put(+ new Attribute("status", AttributeType.BOOLEAN, Json.create(true))+ .setMetadata(new Metadata()+ .putElement(new MetadataElement("type", AttributeType.STRING.getValue(), AssetAttributeType.SENSOR.getJsonValue()))+ .putElement(new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Valve Open")))+ )+ );+ lightSwitch.setAttributes(lightSwitchAttributes.getJsonObject());+ assetService.create(lightSwitch);+*/+}}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 4a2f8588f..430562158 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@@ -20,6 +20,7 @@package org.openremote.manager.shared.asset;import elemental.json.JsonObject;+import org.openremote.manager.shared.attribute.Attributes;import javax.persistence.*;import javax.validation.constraints.NotNull;@@ -76,6 +77,10 @@ public class Asset {this.type = type;}+ public Asset(String name, AssetType type) {+ this(name, type.getValue());+ }+public Asset(Asset parent) {this.parentId = parent.getId();}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/attribute/Attribute.java b/manager/shared/src/main/java/org/openremote/manager/shared/attribute/Attribute.javaindex b6f7a739a..ae4fa263a 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/attribute/Attribute.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/attribute/Attribute.java@@ -20,6 +20,7 @@package org.openremote.manager.shared.attribute;import elemental.json.Json;+import elemental.json.JsonArray;import elemental.json.JsonObject;import elemental.json.JsonValue;@@ -82,6 +83,10 @@ public class Attribute {return jsonObject.hasKey("value") ? jsonObject.getObject("value") : null;}+ public JsonArray getValueAsArray() {+ return jsonObject.hasKey("value") ? jsonObject.getArray("value") : null;+ }+public Attribute setValue(JsonValue value) {jsonObject.put("value", value);return this;diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/attribute/AttributeType.java b/manager/shared/src/main/java/org/openremote/manager/shared/attribute/AttributeType.javaindex 67337b1e0..1508a5a3a 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/attribute/AttributeType.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/attribute/AttributeType.java@@ -51,6 +51,14 @@ public enum AttributeType {return jsonType;}+ public static boolean isValid(String value) {+ for (AttributeType attributeType : values()) {+ if (attributeType.getValue().equals(value))+ return true;+ }+ return false;+ }+public static AttributeType fromValue(String value) {AttributeType[] values = AttributeType.values();for (AttributeType v : values) {diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/attribute/Metadata.java b/manager/shared/src/main/java/org/openremote/manager/shared/attribute/Metadata.javaindex adb6db442..17a90f0ac 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/attribute/Metadata.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/attribute/Metadata.java@@ -61,11 +61,17 @@ public class Metadata {return jsonObject.hasKey(name);}- public Metadata addElement(MetadataElement element) {+ public Metadata putElement(MetadataElement element) {jsonObject.put(element.getName(), element.getJsonObject());return this;}+ public Metadata removeElement(String name) {+ if (jsonObject.hasKey(name))+ jsonObject.remove(name);+ return this;+ }+public Metadata copy() {return new Metadata(Json.parse(getJsonObject().toJson()));}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 576544db6..69e43ded5 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@@ -19,14 +19,14 @@*/package org.openremote.manager.shared.connector;-import com.fasterxml.jackson.annotation.JsonProperty;-import com.fasterxml.jackson.databind.annotation.JsonSerialize;import org.openremote.manager.shared.asset.Asset;import org.openremote.manager.shared.attribute.Attributes;-import org.openremote.manager.shared.agent.AgentStatus;-import org.openremote.manager.shared.device.Device;+/**+ * Connectors to external systems are implemented as Apache Camel components.+ */public interface ConnectorComponent {+public static final String HEADER_DISCOVERY_START = ConnectorComponent.class.getCanonicalName() + ".HEADER_DISCOVERY_START";public static final String HEADER_DISCOVERY_STOP = ConnectorComponent.class.getCanonicalName() + ".HEADER_DISCOVERY_STOP";public static final String HEADER_INVENTORY_ACTION = ConnectorComponent.class.getCanonicalName() + ".HEADER_INVENTORY_ACTION";diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/connector/ConnectorUtil.java b/manager/shared/src/main/java/org/openremote/manager/shared/connector/ConnectorUtil.javaindex fec9a59b0..04d9c54ee 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/connector/ConnectorUtil.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/connector/ConnectorUtil.java@@ -37,7 +37,7 @@ public class ConnectorUtil {attribute.setMetadata(new Metadata(Json.createObject()));if (displayName != null && displayName.length() > 0) {- attribute.getMetadata().addElement(+ attribute.getMetadata().putElement(new MetadataElement("label", Json.createObject()).setType(AttributeType.STRING.getValue()).setValue(Json.create(displayName))@@ -45,7 +45,7 @@ public class ConnectorUtil {}if (description != null && description.length() > 0) {- attribute.getMetadata().addElement(+ attribute.getMetadata().putElement(new MetadataElement("description", Json.createObject()).setType(AttributeType.STRING.getValue()).setValue(Json.create(description))@@ -53,7 +53,7 @@ public class ConnectorUtil {}if (defaultValue != null && defaultValue.length() > 0) {- attribute.getMetadata().addElement(+ attribute.getMetadata().putElement(new MetadataElement("defaultValue", Json.createObject()).setType(type.getValue()).setValue(Json.create(defaultValue))@@ -61,7 +61,7 @@ public class ConnectorUtil {}if (defaultValueNote != null && defaultValueNote.length() > 0) {- attribute.getMetadata().addElement(+ attribute.getMetadata().putElement(new MetadataElement("defaultValueNote", Json.createObject()).setType(AttributeType.STRING.getValue()).setValue(Json.create(defaultValueNote))@@ -69,7 +69,7 @@ public class ConnectorUtil {}if (required) {- attribute.getMetadata().addElement(+ attribute.getMetadata().putElement(new MetadataElement("required", Json.createObject()).setType(AttributeType.BOOLEAN.getValue()).setValue(Json.create(true))diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/Capability.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/Capability.javaindex 8748807c0..1cf1913be 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/Capability.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/Capability.java@@ -1,10 +1,7 @@package org.openremote.manager.shared.device;-import org.openremote.manager.shared.attribute.Attribute;import org.openremote.manager.shared.attribute.Attributes;-import java.util.Map;-/*** Analogous to an Object in LWM2M; note the mandatory field* has been removed to make the device object model flexible.@@ -17,6 +14,7 @@ import java.util.Map;* 3 = DeviceInfo* 3311 = Light Control*/+// TODO Not usedpublic class Capability implements CapabilityDefinition {protected String type;protected String name;diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityDefinition.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityDefinition.javaindex 504a6d5c7..8bf8ef961 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityDefinition.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityDefinition.java@@ -2,6 +2,7 @@ package org.openremote.manager.shared.device;import org.openremote.manager.shared.attribute.Attributes;+// TODO Not usedpublic interface CapabilityDefinition {String getType();diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityRef.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityRef.javaindex ae097b82f..ecaed06ac 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityRef.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityRef.java@@ -5,7 +5,9 @@ import org.openremote.manager.shared.attribute.Attribute;import org.openremote.manager.shared.attribute.AttributeType;import org.openremote.manager.shared.attribute.Attributes;+// TODO Not usedpublic class CapabilityRef extends Attribute {+protected Attributes resources;public CapabilityRef(JsonObject jsonObject) {diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/Device.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/Device.javadeleted file mode 100644index f87507178..000000000--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/Device.java+++ /dev/null@@ -1,130 +0,0 @@-package org.openremote.manager.shared.device;--import com.fasterxml.jackson.annotation.JsonIgnoreType;-import com.fasterxml.jackson.annotation.JsonProperty;-import elemental.json.Json;-import elemental.json.JsonArray;-import elemental.json.JsonObject;-import org.openremote.manager.shared.asset.Asset;-import org.openremote.manager.shared.asset.AssetType;--/**- * Device asset for representing devices that come from Agents.- * A Device requires a URI (unique within the scope of the connector) and- * one or more DeviceResource objects.- *- * The resources define the functionality of the device and provide the URIs- * for each item of functionality.- *- * The capabilities allow a device to expose defined 'capabilities' such as- * LightControl and these capabilities provide contextual information for UI- * and mapping purposes.- *- */-@JsonIgnoreType-public class Device extends Asset {- protected static final String URI_KEY = "uri";- protected static final String RESOURCES_KEY = "resources";- protected static final String CAPABILITIES_KEY = "capabilities";-- public Device() {- setType(AssetType.DEVICE);- }-- @Override- public void setType(String type) {- }-- @JsonProperty- public String getUri() {- if (attributes == null) {- return null;- }-- return attributes.getString(URI_KEY);- }-- @JsonProperty- public void setUri(String uri) {- if (attributes == null) {- attributes = Json.createObject();- }-- attributes.put(URI_KEY, uri);- }-- @JsonProperty- public DeviceResource[] getResources()- {- if (attributes == null || !attributes.hasKey(RESOURCES_KEY)) {- return null;- }-- JsonArray resourcesArr = attributes.getArray(RESOURCES_KEY);- DeviceResource[] resources = new DeviceResource[resourcesArr.length()];-- for (int i = 0; i < resourcesArr.length(); i++) {- JsonObject resourceObj = resourcesArr.getObject(i);- resources[i] = new DeviceResource(resourceObj);- }-- return resources;- }-- @JsonProperty- public void setResources(DeviceResource[] resources){- if (attributes == null) {- attributes = Json.createObject();- }-- if (resources == null || resources.length == 0) {- attributes.remove(RESOURCES_KEY);- return;- }-- JsonArray resourcesArr = Json.createArray();-- for (int i = 0; i < resources.length; i++) {- resourcesArr.set(i, Json.parse(resources[i].toString()));- }-- attributes.put(RESOURCES_KEY, resourcesArr);- }-- @JsonProperty- public CapabilityRef[] getCapabilities() {- if (attributes == null || !attributes.hasKey(CAPABILITIES_KEY)) {- return null;- }-- JsonArray capabilitiesArr = attributes.getArray(CAPABILITIES_KEY);- CapabilityRef[] capabilities = new CapabilityRef[capabilitiesArr.length()];-- for (int i = 0; i < capabilitiesArr.length(); i++) {- JsonObject capabilityObj = capabilitiesArr.getObject(i);- capabilities[i] = new CapabilityRef(capabilityObj);- }-- return capabilities;- }-- @JsonProperty- public void setCapabilities(CapabilityRef[] capabilities){- if (attributes == null) {- attributes = Json.createObject();- }-- if (capabilities == null || capabilities.length == 0) {- attributes.remove(CAPABILITIES_KEY);- return;- }-- JsonArray capabilitiesArr = Json.createArray();-- for (int i = 0; i < capabilities.length; i++) {- capabilitiesArr.set(i, Json.parse(capabilities[i].toString()));- }-- attributes.put(CAPABILITIES_KEY, capabilitiesArr);- }-}\ No newline at end of filediff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceAttributes.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceAttributes.javanew file mode 100644index 000000000..90da39f7e--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceAttributes.java@@ -0,0 +1,124 @@+/*+ * 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.device;++import com.fasterxml.jackson.annotation.JsonIgnoreType;+import elemental.json.Json;+import elemental.json.JsonObject;+import org.openremote.manager.shared.attribute.Attribute;+import org.openremote.manager.shared.attribute.AttributeType;+import org.openremote.manager.shared.attribute.Attributes;++import java.util.ArrayList;+import java.util.List;++/**+ * Device asset attribute handling for representing devices that come from agents.+ *+ * A device asset requires a key (typically unique within the scope of the+ * {@link org.openremote.manager.shared.connector.ConnectorComponent}) and+ * zero or many device resources (which also have a key, typically unique+ * within the scope of the device). Both keys are used when an agent builds+ * messaging routes which integrate the connector component. Semantics and scope+ * of the keys are defined by each connector component and can be internal to+ * the connector component.+ * <p>+ * The resources define the functionality of the device and provide access+ * for each item of functionality.+ * <p>+ * TODO: The capabilities allow a device to expose defined device and device resource+ * metadata. A capability such as <em>LightControl</em> would be 'well-known'+ * by software that wants to control lighting. Capabilities provide contextual+ * information for UI and mapping purposes.+ * <p>+ * TODO: Implement resource refs+ */+@JsonIgnoreType // TODO This must be enabled (and fixed before it's usable) if any of serialized classes uses this type+public class DeviceAttributes extends Attributes {++ protected static final String KEY = "key";++ public DeviceAttributes() {+ super();+ }++ public DeviceAttributes(JsonObject jsonObject) {+ super(jsonObject);+ }++ public String getKey() {+ return hasAttribute(KEY) ? get(KEY).getValueAsString() : null;+ }++ public void setKey(String key) {+ put(new Attribute(KEY, AttributeType.STRING, Json.create(key)));+ }++ public DeviceResource[] getDeviceResources() {+ Attribute[] attributes = super.get();+ List<DeviceResource> list = new ArrayList<>();+ for (Attribute attribute : attributes) {+ if (DeviceResource.isDeviceResource(attribute)) {+ list.add(new DeviceResource(attribute));+ }+ }+ return list.toArray(new DeviceResource[list.size()]);+ }++ public DeviceResource getDeviceResource(String name) {+ Attribute attribute = super.get(name);+ if (attribute == null || !DeviceResource.isDeviceResource(attribute))+ return null;+ return new DeviceResource(attribute);+ }+++ /* TODO Implement capabilities, distinguish from device resources with attribute metadata+ public CapabilityRef[] getCapabilities() {+ if (!hasAttribute(RESOURCES))+ return null;++ JsonArray capabilitiesArr = get(CAPABILITIES).getValueAsArray();+ CapabilityRef[] capabilities = new CapabilityRef[capabilitiesArr.length()];++ for (int i = 0; i < capabilitiesArr.length(); i++) {+ JsonObject capabilityObj = capabilitiesArr.getObject(i);+ capabilities[i] = new CapabilityRef(capabilityObj);+ }++ return capabilities;+ }++ public void setCapabilities(CapabilityRef... capabilities) {+ if (capabilities == null || capabilities.length == 0) {+ remove(CAPABILITIES);+ return;+ }++ JsonArray capabilitiesArr = Json.createArray();++ for (int i = 0; i < capabilities.length; i++) {+ capabilitiesArr.set(i, Json.parse(capabilities[i].toString()));+ }++ put(new Attribute(CAPABILITIES, AttributeType.OBJECT_ARRAY, capabilitiesArr));+ }+ */+}\ No newline at end of filediff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResource.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResource.javaindex 36e4612bd..d273f8b72 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResource.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResource.java@@ -1,85 +1,129 @@+/*+ * 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.device;import elemental.json.Json;import elemental.json.JsonObject;import org.openremote.manager.shared.attribute.Attribute;import org.openremote.manager.shared.attribute.AttributeType;-+import org.openremote.manager.shared.attribute.Metadata;+import org.openremote.manager.shared.attribute.MetadataElement;++/**+ * An attribute of an asset that represents a device resource.+ *+ * The value of the attribute is the key of the device resource. Metadata is used+ * to express:+ *+ * <ul>+ * <li>access read only, write only, or read-write</li>+ * <li>the type of the value you read and write from this resource</li>+ * <li>if the resource is passive (polling necessary) or capable of actively pushing values</li>+ * <li>if the resource value is a constant and can be cached forever</li>+ * </ul>+ */public class DeviceResource extends Attribute {+ public static final String DEVICE_RESOURCE = "deviceResource";+ public static final String DEVICE_RESOURCE_TYPE = "urn:openremote:device:resource:type";+ public static final String ACCESS = "access";+ public static final String ACCESS_TYPE = "urn:openremote:device:resource:access";+ public static final String PASSIVE = "passive";+ public static final String CONSTANT = "constant";+public enum Access {R,W,RW}- public DeviceResource(String name) {- super(name);+ public static boolean isDeviceResource(Attribute attribute) {+ // The given attribute must satisfy the API of this class+ return attribute.hasMetadataElement(DEVICE_RESOURCE)+ && attribute.getMetadata().getElement(DEVICE_RESOURCE).getType().equals(DEVICE_RESOURCE_TYPE)+ && AttributeType.isValid(attribute.getMetadata().getElement(DEVICE_RESOURCE).getValue().asString())+ && attribute.hasMetadataElement(ACCESS)+ && attribute.getMetadata().getElement(ACCESS).getType().equals(ACCESS_TYPE);}- public DeviceResource(JsonObject jsonObject) {- super(jsonObject.get("name"), jsonObject);+ public DeviceResource(Attribute attribute) {+ super(attribute.getName(), attribute.getJsonObject());}- public DeviceResource(String name, String description, AttributeType type, Access access, String units) {- super(name, type);- jsonObject.put("name", name);- setAccess(access);- setUnits(units);- setDescription(description);+ public DeviceResource(String name, JsonObject jsonObject) {+ super(name, jsonObject);}- public String getDescription() {- return jsonObject.get("description").asString();+ public DeviceResource(String name, String key, AttributeType resourceType, Access access) {+ super(name, AttributeType.STRING, Json.create(key));+ setMetadata(new Metadata()+ .putElement(+ new MetadataElement(DEVICE_RESOURCE, DEVICE_RESOURCE_TYPE, Json.create(resourceType.getValue()))+ )+ .putElement(+ new MetadataElement(ACCESS, ACCESS_TYPE, Json.create(access.name()))+ )+ );}- public DeviceResource setDescription(String description) {- jsonObject.put("description", Json.create(description));- return this;+ public AttributeType getResourceType() {+ return getMetadata().hasElement(DEVICE_RESOURCE)+ && AttributeType.isValid(getMetadata().getElement(DEVICE_RESOURCE).getValue().asString())+ ? AttributeType.fromValue(getMetadata().getElement(DEVICE_RESOURCE).getValue().asString())+ : null;}public Access getAccess() {- return jsonObject.hasKey("access") ? Access.valueOf(jsonObject.get("access").asString()) : null;- }-- public DeviceResource setAccess(Access access) {- jsonObject.put("access", Json.create(access.toString()));- return this;- }-- public String getUnits() {- return jsonObject.get("units").asString();- }-- public DeviceResource setUnits(String units) {- jsonObject.put("units", Json.create(units));- return this;- }-- public String getUri() {- return jsonObject.get("uri").asString();- }-- public DeviceResource setUri(String uri) {- jsonObject.put("uri", Json.create(uri));- return this;+ return getMetadata().hasElement(ACCESS)+ ? Access.valueOf(getMetadata().getElement(ACCESS).getValue().asString())+ : null;}public boolean isPassive() {- return jsonObject.getBoolean("passive");+ return getMetadata().hasElement(PASSIVE) && getMetadata().getElement(PASSIVE).getValue().asBoolean();}public DeviceResource setPassive(boolean passive) {- jsonObject.put("passive", Json.create(passive));+ if (passive) {+ getMetadata().putElement(+ new MetadataElement(PASSIVE, AttributeType.BOOLEAN.getValue(), Json.create(true))+ );+ } else {+ getMetadata().removeElement(PASSIVE);+ }return this;}public boolean isConstant() {- return jsonObject.get("constant").asBoolean();+ return getMetadata().hasElement(CONSTANT) && getMetadata().getElement(CONSTANT).getValue().asBoolean();}public DeviceResource setConstant(boolean constant) {- jsonObject.put("constant", Json.create(constant));+ if (constant) {+ getMetadata().putElement(+ new MetadataElement(CONSTANT, AttributeType.BOOLEAN.getValue(), Json.create(true))+ );+ } else {+ getMetadata().removeElement(CONSTANT);+ }return this;}+}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResourceRef.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResourceRef.javaindex 96ef6fba0..5eef7afff 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResourceRef.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResourceRef.java@@ -1,5 +1,6 @@package org.openremote.manager.shared.device;+// TODO Not usedpublic class DeviceResourceRef {protected String deviceUri;protected String resourceUri;diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/ResourceRef.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/ResourceRef.javaindex c691e49d2..47dbfcf59 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/ResourceRef.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/ResourceRef.java@@ -1,6 +1,8 @@package org.openremote.manager.shared.device;+// TODO Not usedpublic class ResourceRef {+protected String uri;protected String valueConverter;diff --git a/test/src/test/groovy/org/openremote/test/controller2/Controller2Service.java b/test/src/test/groovy/org/openremote/test/controller2/Controller2Service.javaindex fc068372c..9a48f07fa 100644--- a/test/src/test/groovy/org/openremote/test/controller2/Controller2Service.java+++ b/test/src/test/groovy/org/openremote/test/controller2/Controller2Service.java@@ -2,12 +2,11 @@ package org.openremote.test.controller2;import org.apache.camel.ProducerTemplate;import org.apache.camel.builder.RouteBuilder;-import org.openremote.agent.controller2.Controller2Component;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.manager.shared.device.Device;+import org.openremote.manager.shared.asset.Asset;import java.util.ArrayList;import java.util.List;@@ -17,9 +16,9 @@ import static org.openremote.manager.shared.connector.ConnectorComponent.*;// TODO This is an example service for testing, replaced later with production codepublic class Controller2Service implements ContainerService {- public List<Device> addedDevices = new ArrayList<>();- public List<Device> removedDevices = new ArrayList<>();- public List<Device> updatedDevices = new ArrayList<>();+ public List<Asset> addedDevices = new ArrayList<>();+ public List<Asset> removedDevices = new ArrayList<>();+ public List<Asset> updatedDevices = new ArrayList<>();public ProducerTemplate messageProducerTemplate;@Override@@ -40,18 +39,21 @@ public class Controller2Service implements ContainerService {.choice().when(header(HEADER_DEVICE_ACTION).isEqualTo(ACTION_CREATE)).process(exchange -> {- Device device = exchange.getIn().getBody(Device.class);- addedDevices.add(device);+ addedDevices.add(+ exchange.getIn().getBody(Asset.class)+ );}).endChoice().when(header(HEADER_DEVICE_ACTION).isEqualTo(ACTION_DELETE)).process(exchange -> {- Device device = exchange.getIn().getBody(Device.class);- removedDevices.add(device);+ removedDevices.add(+ exchange.getIn().getBody(Asset.class)+ );}).endChoice().when(header(HEADER_DEVICE_ACTION).isEqualTo(ACTION_UPDATE)).process(exchange -> {- Device device = exchange.getIn().getBody(Device.class);- updatedDevices.add(device);+ updatedDevices.add(+ exchange.getIn().getBody(Asset.class)+ );}).end();from("direct:triggerDiscovery")diff --git a/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovy b/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovyindex 734a742e0..a7d8193f4 100644--- a/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovy+++ b/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovy@@ -4,6 +4,11 @@ import org.apache.camel.Exchangeimport org.apache.camel.Processorimport org.apache.camel.builder.RouteBuilderimport org.openremote.container.message.MessageBrokerService+import org.openremote.manager.shared.asset.Asset+import org.openremote.manager.shared.asset.AssetType+import org.openremote.manager.shared.attribute.AttributeType+import org.openremote.manager.shared.device.DeviceAttributes+import org.openremote.manager.shared.device.DeviceResourceimport org.openremote.test.ContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.BlockingVariables@@ -28,6 +33,16 @@ class Controller2Test extends Specification implements ContainerTrait {then: "the service should receive the devices from the inventory"conditions.eventually {assert controllerService.addedDevices.size() > 0+ Asset device = controllerService.addedDevices.get(0)+ assert device.name == "TestDevice"+ assert device.id != null+ assert device.wellKnownType == AssetType.DEVICE+ DeviceAttributes attributes = new DeviceAttributes(device.attributes)+ assert attributes.deviceResources.length == 5+ assert attributes.getDeviceResource("Light1Switch").type == AttributeType.STRING+ assert attributes.getDeviceResource("Light1Switch").valueAsString == "light1switch"+ assert attributes.getDeviceResource("Light1Switch").getResourceType() == AttributeType.BOOLEAN+ assert attributes.getDeviceResource("Light1Switch").getAccess() == DeviceResource.Access.RW}cleanup: "the server should be stopped"@@ -47,7 +62,7 @@ class Controller2Test extends Specification implements ContainerTrait {def container = startContainer(defaultConfig(serverPort), defaultServices(controllerService))and: "an actuator and a sensor route are started"- String deviceResourceEndpoint = "controller2://192.168.99.100:8083/TestDevice/light1switch";+ String deviceResourceEndpoint = "controller2://192.168.99.100:8083/testdevice/light1switch";def messageBrokerContext = container.getService(MessageBrokerService.class).context;messageBrokerContext.addRoutes(new RouteBuilder() {@Override