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
Added agent inventory routes
Christian Bauer252ef02c2666
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 4a1dd20e0..e34651c63 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@@ -21,6 +21,7 @@ package org.openremote.agent.controller2;import org.apache.camel.Endpoint;import org.apache.camel.impl.UriEndpointComponent;+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.connector.ConnectorComponent;@@ -50,34 +51,34 @@ public class Controller2Component extends UriEndpointComponent implements Connecstatic {SETTINGS = new Attributes();SETTINGS.put(ConnectorUtil.buildConnectorSetting(- "host",- AttributeType.STRING,- "Host/IP Address",- "The OR Controller network hostname or IP address",- true+ "host",+ AttributeType.STRING,+ "Host/IP Address",+ "The OR Controller network hostname or IP address",+ true));SETTINGS.put(ConnectorUtil.buildConnectorSetting(- "port",- AttributeType.INTEGER,- "Port",- "The OR Controller network port number",- true,- "8868",- null+ "port",+ AttributeType.INTEGER,+ "Port",+ "The OR Controller network port number",+ true,+ "8868",+ null));SETTINGS.put(ConnectorUtil.buildConnectorSetting(- "username",- AttributeType.STRING,- "Username",- "The OR Controller Username",- false+ "username",+ AttributeType.STRING,+ "Username",+ "The OR Controller Username",+ false));SETTINGS.put(ConnectorUtil.buildConnectorSetting(- "password",- AttributeType.STRING,- "Password",- "The OR Controller Password",- false+ "password",+ AttributeType.STRING,+ "Password",+ "The OR Controller Password",+ false));}@@ -123,53 +124,26 @@ public class Controller2Component extends UriEndpointComponent implements Connecreturn DISPLAY_NAME;}- @Override- public ChildAssetSupport getChildSupport(Asset parentAsset) {- return null;- }-- @Override- public boolean supportsChildDiscovery(Asset parentAsset) {- return false;- }-- @Override- public Attributes getChildDiscoverySettings(Asset parentAsset) {- return null;- }-@Overridepublic Attributes getConnectorSettings() {return SETTINGS;}- @Override- public String getChildDiscoveryUri(Asset parentAsset, Attributes discoverySettings) {- return null;- }-- @Override- public boolean supportsMonitoring(Asset asset) {- return false;- }-- @Override- public String getChildInventoryUri(Asset asset) {- return null;- }-- @Override- public String getAssetUri(Asset asset) {- return null;- }+ // TODO These dynamic routes are safe? Should we escape values before we concatenate strings?@Override- public String getAssetMonitorUri(Asset asset) {- return null;+ 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";}@Override- public Asset createAsset(Asset parent, Attributes assetSettings) {- return null;+ 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";}}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 b82e84de2..76f673e1c 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,11 +3,12 @@ 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.agent.InventoryModifiedEvent;import org.openremote.manager.shared.asset.Asset;import java.util.logging.Logger;-import static org.openremote.manager.shared.connector.ConnectorComponent.*;+import static org.openremote.manager.shared.agent.InventoryModifiedEvent.Cause.*;public class Controller2InventoryConsumer extends Controller2Consumer implements DeviceListener {@@ -38,8 +39,7 @@ public class Controller2InventoryConsumer extends Controller2Consumer implementsLOG.fine("Starting new exchange for added device: " + device);Exchange exchange = getEndpoint().createExchange();- exchange.getIn().setHeader(HEADER_DEVICE_ACTION, ACTION_CREATE);- exchange.getIn().setBody(device);+ exchange.getIn().setBody(new InventoryModifiedEvent(device, CREATE));processExchange(exchange);}@@ -52,8 +52,7 @@ public class Controller2InventoryConsumer extends Controller2Consumer implementsLOG.fine("Starting new exchange for removed device: " + device);Exchange exchange = getEndpoint().createExchange();- exchange.getIn().setHeader(HEADER_DEVICE_ACTION, ACTION_DELETE);- exchange.getIn().setBody(device);+ exchange.getIn().setBody(new InventoryModifiedEvent(device, DELETE));processExchange(exchange);}@@ -66,8 +65,7 @@ public class Controller2InventoryConsumer extends Controller2Consumer implementsLOG.fine("Starting new exchange for updated device: " + device);Exchange exchange = getEndpoint().createExchange();- exchange.getIn().setHeader(HEADER_DEVICE_ACTION, ACTION_UPDATE);- exchange.getIn().setBody(device);+ exchange.getIn().setBody(new InventoryModifiedEvent(device, UPDATE));processExchange(exchange);}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/agent/AgentAttributesEditor.java b/manager/client/src/main/java/org/openremote/manager/client/assets/agent/AgentAttributesEditor.javaindex e1a75e8a6..2d4264d33 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/agent/AgentAttributesEditor.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/agent/AgentAttributesEditor.java@@ -23,6 +23,7 @@ import com.google.gwt.text.shared.AbstractRenderer;import org.openremote.manager.client.Environment;import org.openremote.manager.client.widget.*;import org.openremote.manager.shared.Consumer;+import org.openremote.manager.shared.agent.Agent;import org.openremote.manager.shared.attribute.Attribute;import org.openremote.manager.shared.attribute.AttributeType;import org.openremote.manager.shared.attribute.Attributes;@@ -37,6 +38,8 @@ import static org.openremote.manager.shared.connector.Connector.ASSET_ATTRIBUTE_public class AgentAttributesEditor extends AttributesEditor {+ final protected Agent agent;+final protected ConnectorResource connectorResource;final protected ConnectorArrayMapper connectorArrayMapper;@@ -52,6 +55,7 @@ public class AgentAttributesEditor extends AttributesEditor {public AgentAttributesEditor(Environment environment, Container container, Attributes attributes,ConnectorResource connectorResource, ConnectorArrayMapper connectorArrayMapper) {super(environment, container, attributes);+ this.agent = new Agent(attributes);this.connectorResource = connectorResource;this.connectorArrayMapper = connectorArrayMapper;@@ -73,10 +77,10 @@ public class AgentAttributesEditor extends AttributesEditor {Connector connector = getConnector();if (connector != null) {connectorDropDown.setValue(connector);- writeConnectorSettingsToAttributes(connector);- } else if (getConnectorType() != null) {+ agent.writeConnectorSettings(connector);+ } else if (agent.getConnectorType() != null) {notFoundConnector.setName(- getConnectorType() ++ agent.getConnectorType() +" (" + environment.getMessages().connectorNotInstalled() + ")");connectorDropDown.setValue(notFoundConnector);@@ -133,12 +137,12 @@ public class AgentAttributesEditor extends AttributesEditor {protected void onConnectorSelected(Connector connector) {if (connector != null) {- setConnectorType(connector.getType());- writeConnectorSettingsToAttributes(getConnector());+ agent.setConnectorType(connector.getType());+ agent.writeConnectorSettings(getConnector());} else {Connector oldConnector = getConnector();- removeConnectorSettingsFromAttributes(oldConnector);- removeConnectorTypeAttribute();+ agent.removeConnectorSettings(oldConnector);+ agent.removeConnectorType();}refresh();}@@ -153,61 +157,14 @@ public class AgentAttributesEditor extends AttributesEditor {);}- protected Attribute getOrCreateConnectorTypeAttribute() {- if (attributes.hasAttribute(ASSET_ATTRIBUTE_CONNECTOR)) {- return attributes.get(ASSET_ATTRIBUTE_CONNECTOR);- } else {- Attribute attribute = new Attribute(ASSET_ATTRIBUTE_CONNECTOR, AttributeType.STRING);- attributes.put(attribute);- return attribute;- }- }-- protected void removeConnectorTypeAttribute() {- attributes.remove(ASSET_ATTRIBUTE_CONNECTOR);- }-- protected String getConnectorType() {- return getOrCreateConnectorTypeAttribute().getValueAsString();- }-- protected void setConnectorType(String connectorType) {- getOrCreateConnectorTypeAttribute().setValue(connectorType);- }-protected Connector getConnector() {Connector assignedConnector = null;for (Connector connector : availableConnectors) {- if (connector.getType().equals(getConnectorType())) {+ if (connector.getType().equals(agent.getConnectorType())) {assignedConnector = connector;break;}}return assignedConnector;}-- protected void writeConnectorSettingsToAttributes(Connector connector) {- if (connector == null)- return;- for (Attribute setting : connector.getSettings().get()) {- Attribute attribute = attributes.get(setting.getName());- // If the connector setting still has the same type as the agent's attribute, only update metadata- if (attribute != null && attribute.getType().equals(setting.getType())) {- attribute.setMetadata(setting.getMetadata().copy());- } else {- // The agent does not have the connector setting or it's now a different type, replace/create attribute- attribute = new Attribute(setting.getName(), setting.getType());- attribute.setMetadata(setting.getMetadata().copy());- attributes.put(attribute);- }- }- }-- protected void removeConnectorSettingsFromAttributes(Connector connector) {- if (connector == null)- return;- for (Attribute setting : connector.getSettings().get()) {- attributes.remove(setting.getName());- }- }}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetActivity.javaindex d397b7e2f..290f3c183 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetActivity.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetActivity.java@@ -21,19 +21,19 @@ package org.openremote.manager.client.assets.asset;import com.google.gwt.user.client.ui.AcceptsOneWidget;import org.openremote.manager.client.Environment;-import org.openremote.manager.client.assets.agent.ConnectorArrayMapper;import org.openremote.manager.client.assets.AssetMapper;import org.openremote.manager.client.assets.AssetsDashboardPlace;+import org.openremote.manager.client.assets.agent.AgentAttributesEditor;+import org.openremote.manager.client.assets.agent.ConnectorArrayMapper;import org.openremote.manager.client.assets.browser.AssetBrowser;import org.openremote.manager.client.assets.browser.AssetBrowsingActivity;-import org.openremote.manager.client.assets.agent.AgentAttributesEditor;import org.openremote.manager.client.assets.device.DeviceAttributesEditor;-import org.openremote.manager.client.assets.event.AssetsModifiedEvent;import org.openremote.manager.client.event.bus.EventBus;import org.openremote.manager.client.event.bus.EventRegistration;import org.openremote.manager.client.interop.elemental.JsonObjectMapper;import org.openremote.manager.client.widget.AttributesEditor;import org.openremote.manager.shared.asset.Asset;+import org.openremote.manager.shared.asset.AssetModifiedEvent;import org.openremote.manager.shared.asset.AssetResource;import org.openremote.manager.shared.asset.AssetType;import org.openremote.manager.shared.attribute.Attributes;@@ -47,6 +47,7 @@ import java.util.Collection;import java.util.logging.Logger;import static org.openremote.manager.client.http.RequestExceptionHandler.handleRequestException;+import static org.openremote.manager.shared.asset.AssetModifiedEvent.Cause.*;public class AssetActivityextends AssetBrowsingActivity<AssetView, AssetPlace>@@ -215,7 +216,7 @@ public class AssetActivityenvironment.getEventBus().dispatch(new ShowInfoEvent(environment.getMessages().assetUpdated(asset.getName())));- environment.getEventBus().dispatch(new AssetsModifiedEvent(asset, forceRootRefresh));+ environment.getEventBus().dispatch(new AssetModifiedEvent(asset, UPDATE, forceRootRefresh));environment.getPlaceController().goTo(new AssetPlace(assetId));},ex -> handleRequestException(ex, environment)@@ -239,7 +240,7 @@ public class AssetActivityenvironment.getEventBus().dispatch(new ShowInfoEvent(environment.getMessages().assetCreated(asset.getName())));- environment.getEventBus().dispatch(new AssetsModifiedEvent(asset));+ environment.getEventBus().dispatch(new AssetModifiedEvent(asset, CREATE));environment.getPlaceController().goTo(new AssetsDashboardPlace());},ex -> handleRequestException(ex, environment)@@ -265,7 +266,7 @@ public class AssetActivityenvironment.getEventBus().dispatch(new ShowInfoEvent(environment.getMessages().assetDeleted(asset.getName())));- environment.getEventBus().dispatch(new AssetsModifiedEvent(asset));+ environment.getEventBus().dispatch(new AssetModifiedEvent(asset, DELETE));environment.getPlaceController().goTo(new AssetsDashboardPlace());},ex -> handleRequestException(ex, environment)diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowserPresenter.java b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowserPresenter.javaindex 3c0f197a5..a98496500 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowserPresenter.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowserPresenter.java@@ -22,7 +22,7 @@ package org.openremote.manager.client.assets.browser;import com.google.gwt.view.client.HasData;import org.openremote.manager.client.Environment;import org.openremote.manager.client.assets.AssetInfoArrayMapper;-import org.openremote.manager.client.assets.event.AssetsModifiedEvent;+import org.openremote.manager.shared.asset.AssetModifiedEvent;import org.openremote.manager.client.event.bus.EventBus;import org.openremote.manager.client.event.bus.EventListener;import org.openremote.manager.client.event.bus.EventRegistration;@@ -60,7 +60,7 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {this.assetResource = assetResource;this.assetInfoArrayMapper = assetInfoArrayMapper;- environment.getEventBus().register(AssetsModifiedEvent.class, event -> {+ environment.getEventBus().register(AssetModifiedEvent.class, event -> {view.refreshAssets(event.isForceRootRefresh()|| event.getAsset() == nulldiff --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 71eef42be..89a42b1c5 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@@ -19,48 +19,117 @@*/package org.openremote.manager.client.assets.device;+import com.google.gwt.user.client.ui.FlowPanel;+import com.google.gwt.user.client.ui.Label;import org.openremote.manager.client.Environment;import org.openremote.manager.client.widget.*;-import org.openremote.manager.shared.asset.AssetAttributeType;import org.openremote.manager.shared.attribute.Attribute;import org.openremote.manager.shared.attribute.Attributes;+import org.openremote.manager.shared.device.DeviceAttributes;+import org.openremote.manager.shared.device.DeviceResource;++import static com.google.gwt.dom.client.Style.Unit.EM;public class DeviceAttributesEditor extends AttributesEditor {+ final protected DeviceAttributes deviceAttributes;+public DeviceAttributesEditor(Environment environment, Container container, Attributes attributes) {super(environment, container, attributes);+ this.deviceAttributes = new DeviceAttributes(attributes.getJsonObject());}@Overrideprotected FormLabel buildFormLabel(Attribute attribute) {FormLabel formLabel = super.buildFormLabel(attribute);- if (AssetAttributeType.isSensor(attribute)) {- formLabel.setIcon("sign-out");- } else if (AssetAttributeType.isActuator(attribute)) {- formLabel.setIcon("sign-in");- }+ if (DeviceResource.isDeviceResource(attribute)) {+ DeviceResource deviceResource = new DeviceResource(attribute);+ switch (deviceResource.getAccess()) {+ case R:+ formLabel.setText(formLabel.getText() + " (R)");+ break;+ case W:+ formLabel.setText(formLabel.getText() + " (W)");+ break;+ default:+ formLabel.setText(formLabel.getText() + " (RW)");+ }++ } else if (attribute.getName().equals("key")) {+ formLabel.setText(environment.getMessages().deviceKey());+ }return formLabel;}+ @Override+ protected FormGroup createFormGroup(Attribute attribute) {+ FormGroup formGroup = super.createFormGroup(attribute);+ if (DeviceResource.isDeviceResource(attribute)) {+ formGroup.addInfolabel(+ new Label(environment.getMessages().resourceKey())+ );++ DeviceResource deviceResource = new DeviceResource(attribute);++ // TODO These actions don't do anything+ FlowPanel actionPanel = new FlowPanel();+ actionPanel.setStyleName("flex layout horizontal center");++ FormButton readButton = new FormButton();+ FormInputText readOutput = new FormInputText();+ readOutput.getElement().getStyle().setWidth(5, EM);+ readOutput.setReadOnly(true);+ readButton.setText(environment.getMessages().readValue());++ FormButton writeButton = new FormButton();+ FormInputText writeInput = new FormInputText();+ writeInput.getElement().getStyle().setWidth(5, EM);+ writeButton.setText(environment.getMessages().writeValue());++ switch (deviceResource.getAccess()) {+ case R:+ actionPanel.add(readButton);+ actionPanel.add(readOutput);+ break;+ case W:+ actionPanel.add(writeInput);+ actionPanel.add(writeButton);+ break;+ default:+ actionPanel.add(writeInput);+ actionPanel.add(writeButton);+ actionPanel.add(readButton);+ actionPanel.add(readOutput);+ }+ formGroup.getFormField().add(actionPanel);+ }+ return formGroup;+ }++ @Override+ protected boolean isDefaultReadOnly(Attribute attribute) {+ return attribute.getName().equals("key") || super.isDefaultReadOnly(attribute);+ }+@Overrideprotected FormInputText createStringEditor(Style style, Attribute attribute, boolean readOnly) {- return super.createStringEditor(style, attribute, AssetAttributeType.isSensor(attribute));+ return super.createStringEditor(style, attribute, readOnly || DeviceResource.isDeviceResource(attribute));}@Overrideprotected FormInputNumber createIntegerEditor(Style style, Attribute attribute, boolean readOnly) {- return super.createIntegerEditor(style, attribute, AssetAttributeType.isSensor(attribute));+ return super.createIntegerEditor(style, attribute, readOnly || DeviceResource.isDeviceResource(attribute));}@Overrideprotected FormInputText createFloatEditor(Style style, Attribute attribute, boolean readOnly) {- return super.createFloatEditor(style, attribute, AssetAttributeType.isSensor(attribute));+ return super.createFloatEditor(style, attribute, readOnly || DeviceResource.isDeviceResource(attribute));}@Overrideprotected FormCheckBox createBooleanEditor(Style style, Attribute attribute, boolean readOnly) {- return super.createBooleanEditor(style, attribute, AssetAttributeType.isSensor(attribute));+ return super.createBooleanEditor(style, attribute, readOnly || DeviceResource.isDeviceResource(attribute));}}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/event/AssetsModifiedEvent.java b/manager/client/src/main/java/org/openremote/manager/client/assets/event/AssetsModifiedEvent.javadeleted file mode 100644index 787d7af08..000000000--- a/manager/client/src/main/java/org/openremote/manager/client/assets/event/AssetsModifiedEvent.java+++ /dev/null@@ -1,27 +0,0 @@-package org.openremote.manager.client.assets.event;--import org.openremote.manager.shared.asset.Asset;-import org.openremote.manager.shared.event.Event;--public class AssetsModifiedEvent extends Event {-- final protected Asset asset;- final protected boolean forceRootRefresh;-- public AssetsModifiedEvent(Asset asset) {- this(asset, false);- }-- public AssetsModifiedEvent(Asset asset, boolean forceRootRefresh) {- this.asset = asset;- this.forceRootRefresh = forceRootRefresh;- }-- public Asset getAsset() {- return asset;- }-- public boolean isForceRootRefresh() {- return forceRootRefresh;- }-}diff --git a/manager/client/src/main/java/org/openremote/manager/client/i18n/ManagerMessages.java b/manager/client/src/main/java/org/openremote/manager/client/i18n/ManagerMessages.javaindex aee2fb7e4..06317f332 100644--- a/manager/client/src/main/java/org/openremote/manager/client/i18n/ManagerMessages.java+++ b/manager/client/src/main/java/org/openremote/manager/client/i18n/ManagerMessages.java@@ -216,4 +216,12 @@ public interface ManagerMessages extends Messages {String noTypeSelected();String enterCustomAssetType();++ String deviceKey();++ String resourceKey();++ String readValue();++ String writeValue();}diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/AttributesEditor.java b/manager/client/src/main/java/org/openremote/manager/client/widget/AttributesEditor.javaindex 750f1c0ec..1f0ffd4ab 100644--- a/manager/client/src/main/java/org/openremote/manager/client/widget/AttributesEditor.java+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/AttributesEditor.java@@ -79,11 +79,14 @@ public class AttributesEditor {}List<Attribute> attributeList = Arrays.asList(attributes.get());Collections.sort(attributeList, (o1, o2) -> o1.getName().compareTo(o2.getName()));+ int count = 0;for (Attribute attribute : attributeList) {LOG.fine("Building form group for attribute: " + attribute.getName());FormGroup formGroup = createFormGroup(attribute);if (formGroup != null) {+ formGroup.addStyleName((count & 1) == 0 ? "even" : "odd");formGroups.put(attribute, formGroup);+ count++;}}}@@ -131,7 +134,7 @@ public class AttributesEditor {/* ####################################################################### */protected void clearContainer() {- while(container.getPanel().getWidgetCount() > 0) {+ while (container.getPanel().getWidgetCount() > 0) {container.getPanel().remove(0);}}@@ -147,13 +150,13 @@ public class AttributesEditor {formGroup.addFormField(attributeField);if (attribute.getType().equals(AttributeType.STRING)) {- formGroup.getFormField().add(createStringEditor(container.getStyle(), attribute, false));+ formGroup.getFormField().add(createStringEditor(container.getStyle(), attribute, isDefaultReadOnly(attribute)));} else if (attribute.getType().equals(AttributeType.INTEGER)) {- formGroup.getFormField().add(createIntegerEditor(container.getStyle(), attribute, false));+ formGroup.getFormField().add(createIntegerEditor(container.getStyle(), attribute, isDefaultReadOnly(attribute)));} else if (attribute.getType().equals(AttributeType.FLOAT)) {- formGroup.getFormField().add(createFloatEditor(container.getStyle(), attribute, false));+ formGroup.getFormField().add(createFloatEditor(container.getStyle(), attribute, isDefaultReadOnly(attribute)));} else if (attribute.getType().equals(AttributeType.BOOLEAN)) {- formGroup.getFormField().add(createBooleanEditor(container.getStyle(), attribute, false));+ formGroup.getFormField().add(createBooleanEditor(container.getStyle(), attribute, isDefaultReadOnly(attribute)));} else {formGroup.getFormField().add(new Label(environment.getMessages().unsupportedAttributeType(attribute.getType().getValue()))@@ -316,4 +319,8 @@ public class AttributesEditor {}return null;}++ protected boolean isDefaultReadOnly(Attribute attribute) {+ return false;+ }}diff --git a/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties b/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.propertiesindex bd4764904..30bfa7271 100644--- a/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties+++ b/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties@@ -105,4 +105,8 @@ assetTypeLabel[FLOOR] = FloorassetTypeLabel[ROOM] = RoomnoTypeSelected= No type selectedenterCustomAssetType=Please enter a custom asset type (e.g. "urn:mydomain:mytype")+deviceKey= Device key+resourceKey= Resource key+readValue= Read value+writeValue= Write valuediff --git a/manager/client/src/main/webapp/css/theme.html b/manager/client/src/main/webapp/css/theme.htmlindex 631d75935..12f177e7c 100644--- a/manager/client/src/main/webapp/css/theme.html+++ b/manager/client/src/main/webapp/css/theme.html@@ -126,6 +126,19 @@color: var(--theme-red);}+ .or-FormGroup.even {+ background-color: var(--theme-brightgrey);+ }++ .or-FormGroup.odd {+ background-color: var(--theme-white);+ }++ .or-FormGroup.even .or-FormInfoLabel,+ .or-FormGroup.odd .or-FormInfoLabel{+ background-color: var(--theme-white);+ }+.or-FormLabel {color: var(--theme-darkgrey);}@@ -149,6 +162,7 @@.or-FormInputText,.or-FormInputNumber {border-color: var(--theme-darkgrey);+ background: transparent;}.or-FormInputText:focus,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 9502f7da2..027818039 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@@ -21,7 +21,6 @@ package org.openremote.manager.server;import com.vividsolutions.jts.geom.Coordinate;import com.vividsolutions.jts.geom.GeometryFactory;-import elemental.json.Json;import org.apache.log4j.Logger;import org.keycloak.admin.client.resource.*;import org.keycloak.common.enums.SslRequired;@@ -36,12 +35,10 @@ import org.openremote.manager.server.agent.ConnectorService;import org.openremote.manager.server.asset.AssetService;import org.openremote.manager.server.asset.ServerAsset;import org.openremote.manager.server.security.ManagerIdentityService;-import org.openremote.manager.shared.asset.AssetAttributeType;+import org.openremote.manager.shared.agent.Agent;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 org.openremote.manager.shared.attribute.Attribute;+import org.openremote.manager.shared.attribute.Attributes;import rx.Observable;import javax.ws.rs.core.UriBuilder;@@ -50,9 +47,6 @@ 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;public class SampleDataService implements ContainerService {@@ -65,6 +59,8 @@ public class SampleDataService implements ContainerService {public static final String ADMIN_CLI_CLIENT_ID = "admin-cli";public static final String ADMIN_PASSWORD = "admin";+ public String SAMPLE_AGENT_ID = null;+protected Container container;protected PersistenceService persistenceService;protected ManagerIdentityService identityService;@@ -259,155 +255,37 @@ public class SampleDataService implements ContainerService {smartOffice.setType(AssetType.BUILDING);assetService.create(smartOffice);- ServerAsset floor;- ServerAsset floor6 = null;- for (int i = 0; i < 7; i++) {- floor = new ServerAsset(smartOffice);- floor.setName("Floor " + (i + 1));- floor.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));- floor.setType(AssetType.FLOOR);- assetService.create(floor);-- if (i == 5)- floor6 = floor;+ ServerAsset groundfloor = new ServerAsset(smartOffice);+ groundfloor.setName("Ground Floor");+ groundfloor.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));+ groundfloor.setType(AssetType.FLOOR);+ assetService.create(groundfloor);++ ServerAsset lobby = new ServerAsset(groundfloor);+ lobby.setName("Lobby");+ lobby.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));+ lobby.setType(AssetType.ROOM);+ assetService.create(lobby);++ ServerAsset sampleAgentAsset = new ServerAsset(lobby);+ sampleAgentAsset.setName("Light & TV Controller");+ sampleAgentAsset.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));+ sampleAgentAsset.setType(AssetType.AGENT);++ Agent sampleAgent = new Agent(new Attributes());++ sampleAgent.setEnabled(true);+ sampleAgent.setConnectorType("urn:openremote:connector:controller2");+ for (Attribute connectorSetting : Controller2Component.SETTINGS.get()) {+ sampleAgent.getAttributes().put(connectorSetting.copy());}+ sampleAgent.getAttributes().get("host").setValue("192.168.99.100");+ sampleAgent.getAttributes().get("port").setValue(8083);- ServerAsset room;- ServerAsset room3 = null;- for (int i = 0; i < 13; i++) {- room = new ServerAsset(floor6);- room.setName("6.00" + (i + 1));- room.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));-- if (i == 2) {- // This is our sample agent- room.setType(AssetType.AGENT);- Attributes room3Attributes = new Attributes();- room3Attributes.put(- new Attribute(Connector.ASSET_ATTRIBUTE_CONNECTOR, STRING, Json.create("urn:openremote:connector:controller2"))- );- for (Attribute connectorSetting : Controller2Component.SETTINGS.get()) {- room3Attributes.put(connectorSetting.copy());- }- room3Attributes.get("host").setValue("192.168.123.123");- room3Attributes.get("port").setValue(8080);- room.setAttributes(room3Attributes.getJsonObject());- } else {- room.setType(AssetType.ROOM);- }-- assetService.create(room);-- if (i == 2)- room3 = room;- }+ sampleAgentAsset.setAttributes(sampleAgent.getAttributes().getJsonObject());- ServerAsset wallpanel = new ServerAsset(room3);- wallpanel.setName("Wallpanel");- wallpanel.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));- wallpanel.setType(AssetType.DEVICE);- Attributes wallpanelAttributes = new Attributes();- wallpanelAttributes.put(- new Attribute("temperature", AttributeType.FLOAT, Json.create(21.3))- .setMetadata(new Metadata()- .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()- .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()- .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()- .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()- .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());- assetService.create(wallpanel);-- ServerAsset presence = new ServerAsset(room3);- presence.setName("Presence");- presence.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));- presence.setType(AssetType.DEVICE);- Attributes presenceAttributes = new Attributes();- presenceAttributes.put(- new Attribute("presence", AttributeType.BOOLEAN, Json.create(false))- .setMetadata(new Metadata()- .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());- assetService.create(presence);-- ServerAsset windows = new ServerAsset(room3);- windows.setName("Windows");- windows.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));- windows.setType(AssetType.DEVICE);- Attributes windowsAttributes = new Attributes();- windowsAttributes.put(- new Attribute("status", AttributeType.BOOLEAN, Json.create(false))- .setMetadata(new Metadata()- .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());- assetService.create(windows);-- ServerAsset valve = new ServerAsset(room3);- valve.setName("Valve");- valve.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));- valve.setType(AssetType.DEVICE);- Attributes valveAttributes = new Attributes();- valveAttributes.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")))- )- );- 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);-*/+ assetService.create(sampleAgentAsset);+ SAMPLE_AGENT_ID = sampleAgentAsset.getId();}}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.javanew file mode 100644index 000000000..0e6cc5917--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentRoutes.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.apache.camel.builder.RouteBuilder;+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 java.util.logging.Logger;++/**+ * The messaging routes of a running agent instance.+ */+public abstract class AgentRoutes extends RouteBuilder {++ public static String TRIGGER_DISCOVERY_ROUTE(String agentAssetId) {+ return "direct:urn:openremote:agent:triggerDiscovery:" + agentAssetId;+ }++ private static final Logger LOG = Logger.getLogger(AgentRoutes.class.getName());++ 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);+ }++ @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)+ );+ });+ }++ if (triggerDiscoveryUri != null) {+ from(TRIGGER_DISCOVERY_ROUTE(agentAsset.getId()))+ .routeId("Agent Trigger Discovery - " + agentAsset.getId())+ .to(triggerDiscoveryUri);+ }+ }++ public void stop(MessageBrokerContext context) throws Exception {+ if (inventoryUri != null) {+ context.stopRoute("Agent Inventory - " + agentAsset.getId());+ }+ if (triggerDiscoveryUri != null) {+ context.stopRoute("Agent Trigger Discovery - " + agentAsset.getId());+ }+ }++ protected abstract void handleInventoryModified(InventoryModifiedEvent event);+}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 27b5a0ec9..e08298e8d 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,36 +19,89 @@*/package org.openremote.manager.server.agent;+import org.apache.camel.FailedToCreateRouteException;+import org.apache.camel.ProducerTemplate;import org.apache.camel.builder.RouteBuilder;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.persistence.PersistenceService;+import org.openremote.container.persistence.PersistenceEvent;+import org.openremote.manager.server.asset.AssetService;+import org.openremote.manager.server.asset.ServerAsset;+import org.openremote.manager.shared.Function;+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.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.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.logging.Level;import java.util.logging.Logger;-import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_EVENT_HEADER;-import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_EVENT_TOPIC;+import static org.openremote.container.persistence.PersistenceEvent.*;public class AgentService implements ContainerService {private static final Logger LOG = Logger.getLogger(AgentService.class.getName());protected MessageBrokerService messageBrokerService;- protected PersistenceService persistenceService;+ ProducerTemplate producerTemplate;++ protected AssetService assetService;protected ConnectorService connectorService;+ final protected Map<String, AgentRoutes> agentInstanceMap = new LinkedHashMap<>();++ /*+ This is the dynamic routing slip for discovery triggers: We call either the desired agent+ only, or get a list of all agents and trigger all of them.+ */+ final protected Function<String, String> triggerDiscoveryRouting = new Function<String, String>() {+ @Override+ public String apply(String agentAssetId) {+ LOG.fine("Routing trigger discovery message for agent(s): " + agentAssetId);+ List<String> destinations = new ArrayList<>();+ if (agentAssetId != null && agentAssetId.length() > 0) {+ Asset agentAsset = assetService.get(agentAssetId);+ if (agentAsset != null) {+ destinations.add(+ AgentRoutes.TRIGGER_DISCOVERY_ROUTE(agentAssetId)+ );+ }+ } else {+ Asset[] allAgents = assetService.findByType(AssetType.AGENT);+ for (Asset agent : allAgents) {+ destinations.add(+ AgentRoutes.TRIGGER_DISCOVERY_ROUTE(agent.getId())+ );+ }+ }+ LOG.fine("Triggering discovery on agents: " + destinations);+ return Util.toCommaSeparated(+ destinations.toArray(new String[destinations.size()])+ );+ }+ };+@Overridepublic void init(Container container) throws Exception {messageBrokerService = container.getService(MessageBrokerService.class);- persistenceService = container.getService(PersistenceService.class);+ producerTemplate = messageBrokerService.getContext().createProducerTemplate();+ assetService = container.getService(AssetService.class);connectorService = container.getService(ConnectorService.class);messageBrokerService.getContext().addRoutes(new RouteBuilder() {@Overridepublic void configure() throws Exception {++ // If any agent was modified in the database, reconfigure this servicefrom(PERSISTENCE_EVENT_TOPIC).filter(body().isInstanceOf(Asset.class)).filter(exchange -> {@@ -56,11 +109,15 @@ public class AgentService implements ContainerService {return AssetType.AGENT.equals(asset.getWellKnownType());}).process(exchange -> {- LOG.info("### AGENT PERSISTENCE EVENT: " + exchange.getIn().getHeader(PERSISTENCE_EVENT_HEADER));- LOG.info("### AGENT: " + exchange.getIn().getBody());- // TODO: Implement fine-grained life cycle changes- reconfigureAgents();+ PersistenceEvent persistenceEvent = exchange.getIn().getHeader(PERSISTENCE_EVENT_HEADER, PersistenceEvent.class);+ Asset agent = exchange.getIn().getBody(Asset.class);+ reconfigureAgents(persistenceEvent == UPDATE ? agent : null);});++ // Dynamically route discovery trigger messages to agents+ from(Agent.TOPIC_TRIGGER_DISCOVERY)+ .routingSlip(method(triggerDiscoveryRouting))+ .ignoreInvalidEndpoints();}});}@@ -71,7 +128,7 @@ public class AgentService implements ContainerService {@Overridepublic void start(Container container) throws Exception {- // TODO On startup, load all enabled agents and reconfigureAgents();+ reconfigureAgents(null);}@Override@@ -79,8 +136,104 @@ public class AgentService implements ContainerService {}- protected void reconfigureAgents() {- LOG.info("############################### TODO: RECONFIGURE AGENTS");+ protected void reconfigureAgents(Asset updatedAgent) {+ ServerAsset[] agents = assetService.findByType(AssetType.AGENT);++ LOG.fine("Reconfigure agents: " + agents.length);++ synchronized (agentInstanceMap) {+ 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);+ } else if (updatedAgent != null && agentAsset.getId().equals(updatedAgent.getId())) {+ LOG.fine("Agent is enabled and already running, restarting due to update: " + agentAsset.getId());+ stopAgent(agentAsset.getId());+ startAgent(agentAsset);+ }++ // Agent is not enabled anymore but still running+ } else if (agentInstanceMap.containsKey(agentAsset.getId())) {+ LOG.fine("Agent is disabled and still running: " + agentAsset.getId());+ stopAgent(agentAsset.getId());+ }+ }++ for (String agentId : agentInstanceMap.keySet()) {+ boolean found = false;+ for (ServerAsset agent : agents) {+ if (agent.getId().equals(agentId)) {+ found = true;+ break;+ }+ }+ if (!found) {+ LOG.fine("Agent is not present anymore and still running: " + agentId);+ stopAgent(agentId);+ }+ }+ }+ }++ protected void startAgent(Asset agentAsset) {+ LOG.fine("Starting agent: " + agentAsset);++ Agent agent = new Agent(new Attributes(agentAsset.getAttributes()));+ ConnectorComponent connectorComponent = connectorService.getConnectorComponentByType(agent.getConnectorType());+ AgentRoutes agentRoutes = new AgentRoutes(agentAsset, agent, connectorComponent) {+ @Override+ protected void handleInventoryModified(InventoryModifiedEvent event) {+ Asset deviceAsset = event.getDeviceAsset();+ switch (event.getCause()) {+ case CREATE:+ LOG.fine("Creating new child asset of agent '" + agentAsset.getId() + "': " + deviceAsset);+ ServerAsset deviceServerAsset = ServerAsset.map(+ deviceAsset,+ new ServerAsset(),+ agentAsset.getId(),+ agentAsset.getCoordinates()+ );+ assetService.create(deviceServerAsset);+ break;+ default:+ throw new UnsupportedOperationException("TODO Implement UPDATE, DELETE, etc.");+ }+ }+ };++ agentInstanceMap.put(agentAsset.getId(), agentRoutes);++ try {++ MessageBrokerContext context = messageBrokerService.getContext();+ context.addRoutes(agentRoutes);++ } catch (FailedToCreateRouteException 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);+ // TODO: We should mark the agent or fire event, or...+ }}+ protected void stopAgent(String agentId) {+ 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...+ } catch (Exception ex) {+ LOG.log(Level.SEVERE, "Error stopping agent" + agentId, ex);+ // TODO: We should mark the agent or fire event, or...+ }+ }+ }}\ No newline at end of filediff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.javaindex ce44eedca..29fc0d243 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java@@ -19,8 +19,6 @@*/package org.openremote.manager.server.asset;-import com.vividsolutions.jts.geom.Coordinate;-import com.vividsolutions.jts.geom.GeometryFactory;import org.openremote.container.web.WebResource;import org.openremote.manager.shared.asset.Asset;import org.openremote.manager.shared.asset.AssetInfo;@@ -87,22 +85,7 @@ public class AssetResourceImpl extends WebResource implements AssetResource {protected ServerAsset mapToServerAsset(Asset asset, ServerAsset serverAsset) {if (serverAsset == null)throw new WebApplicationException(Response.Status.NOT_FOUND);-- serverAsset.setVersion(asset.getVersion());- serverAsset.setName(asset.getName());- serverAsset.setType(asset.getType());- if (asset.getCoordinates() != null && asset.getCoordinates().length == 2) {- GeometryFactory geometryFactory = new GeometryFactory();- serverAsset.setLocation(geometryFactory.createPoint(new Coordinate(- asset.getCoordinates()[0],- asset.getCoordinates()[1]- )));- } else {- serverAsset.setLocation(null);- }- serverAsset.setParentId(asset.getParentId());- serverAsset.setAttributes(asset.getAttributes());- return serverAsset;+ return ServerAsset.map(asset, serverAsset);}}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 f94d2fb43..2f2c0c96f 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,6 +28,7 @@ import org.openremote.container.persistence.PersistenceService;import org.openremote.container.web.WebService;import org.openremote.manager.shared.asset.Asset;import org.openremote.manager.shared.asset.AssetInfo;+import org.openremote.manager.shared.asset.AssetType;import javax.persistence.EntityManager;import java.sql.PreparedStatement;@@ -93,6 +94,17 @@ public class AssetService implements ContainerService {});}+ public ServerAsset[] findByType(AssetType assetType) {+ return persistenceService.doTransaction(em -> {+ List<ServerAsset> result =+ em.createQuery(+ "select a from Asset a where a.type = :assetType order by a.createdOn asc",+ ServerAsset.class+ ).setParameter("assetType", assetType.getValue()).getResultList();+ return result.toArray(new ServerAsset[result.size()]);+ });+ }+public AssetInfo[] getChildren(String parentId) {return persistenceService.doTransaction(em -> {List<AssetInfo> result =diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java b/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.javaindex 5119055e4..567fb4c18 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java@@ -21,11 +21,11 @@ package org.openremote.manager.server.asset;import com.fasterxml.jackson.annotation.JsonIgnore;import com.vividsolutions.jts.geom.Coordinate;+import com.vividsolutions.jts.geom.GeometryFactory;import com.vividsolutions.jts.geom.Point;import org.openremote.manager.shared.asset.Asset;import javax.persistence.*;-import javax.validation.constraints.NotNull;/*** This can only be used on the server and offers types (such as Hibernate proxying, Geometry)@@ -34,6 +34,39 @@ import javax.validation.constraints.NotNull;@Entity(name = "Asset")public class ServerAsset extends Asset {+ /**+ * Easy conversion between types, we copy all properties (not a deep copy!)+ */+ public static ServerAsset map(Asset asset, ServerAsset serverAsset) {+ return map(asset, serverAsset, null, null);+ }++ public static ServerAsset map(Asset asset, ServerAsset serverAsset, String overrideParentId, double[] overrideLocation) {+ serverAsset.setVersion(asset.getVersion());+ serverAsset.setName(asset.getName());+ serverAsset.setType(asset.getType());++ serverAsset.setParentId(overrideParentId != null ? overrideParentId : asset.getParentId());++ GeometryFactory geometryFactory = new GeometryFactory();++ if (overrideLocation != null) {+ serverAsset.setLocation(geometryFactory.createPoint(new Coordinate(+ overrideLocation[0],+ overrideLocation[1]+ )));+ } else if (asset.getCoordinates() != null && asset.getCoordinates().length == 2) {+ serverAsset.setLocation(geometryFactory.createPoint(new Coordinate(+ asset.getCoordinates()[0],+ asset.getCoordinates()[1]+ )));+ } else {+ serverAsset.setLocation(null);+ }+ serverAsset.setAttributes(asset.getAttributes());+ return serverAsset;+ }+@JoinColumn(name = "PARENT_ID", insertable = false, updatable = false)@ManyToOne(fetch = FetchType.LAZY)@JsonIgnorediff --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/EventPredicate.javanew file mode 100644index 000000000..b2ef7665c--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/event/EventPredicate.java@@ -0,0 +1,39 @@+/*+ * 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.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 {++ final protected Class<T> eventType;++ public EventPredicate(Class<T> eventType) {+ this.eventType = eventType;+ }++ @Override+ public boolean matches(Exchange exchange) {+ return exchange.getIn().getBody() != null+ && eventType.isAssignableFrom(exchange.getIn().getBody().getClass());+ }+}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.javanew file mode 100644index 000000000..b495bdb0f--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/agent/Agent.java@@ -0,0 +1,128 @@+/*+ * 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 elemental.json.Json;+import org.openremote.manager.shared.attribute.*;+import org.openremote.manager.shared.connector.Connector;++import static org.openremote.manager.shared.connector.Connector.ASSET_ATTRIBUTE_CONNECTOR;++/**+ * Runtime instance of an agent {@link org.openremote.manager.shared.asset.Asset}.+ * <p>+ * This is a message routing table that can be dynamically built from {@link Connector} settings.+ * 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}.+ */+public class Agent {++ /**+ * Send messages to this endpoint to trigger discovery of the assets available through an agent. If the+ * message body is empty, all running agent's will execute discovery. If an agent asset identifier is+ * present in the message body, only that agent will execute discovery.+ */+ public static String TOPIC_TRIGGER_DISCOVERY = "seda://urn:openremote:agent:discovery?multipleConsumers=true&waitForTaskToComplete=NEVER";++ final protected Attributes attributes;++ public Agent(Attributes attributes) {+ this.attributes = attributes;+ }++ public Attributes getAttributes() {+ return attributes;+ }++ public boolean isEnabled() {+ return attributes.hasAttribute("enabled") && attributes.get("enabled").getValueAsBoolean();+ }++ public Agent setEnabled(boolean enabled) {+ attributes.put(+ new Attribute("enabled", AttributeType.BOOLEAN, Json.create(enabled))+ .setMetadata(new Metadata()+ .putElement(+ new MetadataElement("label", AttributeType.STRING.getValue(), Json.create("Enabled"))+ )+ .putElement(+ new MetadataElement("description", AttributeType.STRING.getValue(),+ Json.create("Enabled agents will discover devices and manage their inventory automatically")+ )+ )+ )+ );+ return this;+ }++ public Attribute getOrCreateConnectorTypeAttribute() {+ if (attributes.hasAttribute(ASSET_ATTRIBUTE_CONNECTOR)) {+ return attributes.get(ASSET_ATTRIBUTE_CONNECTOR);+ } else {+ Attribute attribute = new Attribute(ASSET_ATTRIBUTE_CONNECTOR, AttributeType.STRING);+ attributes.put(attribute);+ return attribute;+ }+ }++ public String getConnectorType() {+ return getOrCreateConnectorTypeAttribute().getValueAsString();+ }++ public Agent setConnectorType(String connectorType) {+ getOrCreateConnectorTypeAttribute().setValue(connectorType);+ return this;+ }++ public Agent removeConnectorType() {+ attributes.remove(ASSET_ATTRIBUTE_CONNECTOR);+ return this;+ }++ public Agent removeConnectorSettings(Connector connector) {+ if (connector == null)+ return this;+ for (Attribute setting : connector.getSettings().get()) {+ attributes.remove(setting.getName());+ }+ return this;+ }++ public Agent writeConnectorSettings(Connector connector) {+ if (connector == null)+ return this;+ for (Attribute setting : connector.getSettings().get()) {+ Attribute attribute = attributes.get(setting.getName());+ // If the connector setting still has the same type as the agent's attribute, only update metadata+ if (attribute != null && attribute.getType().equals(setting.getType())) {+ attribute.setMetadata(setting.getMetadata().copy());+ } else {+ // The agent does not have the connector setting or it's now a different type, replace/create attribute+ attribute = new Attribute(setting.getName(), setting.getType());+ attribute.setMetadata(setting.getMetadata().copy());+ attributes.put(attribute);+ }+ }+ return this;+ }++}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/agent/InventoryModifiedEvent.java b/manager/shared/src/main/java/org/openremote/manager/shared/agent/InventoryModifiedEvent.javanew file mode 100644index 000000000..63a2ad129--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/agent/InventoryModifiedEvent.java@@ -0,0 +1,48 @@+/*+ * 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.asset.Asset;+import org.openremote.manager.shared.event.Event;++public class InventoryModifiedEvent extends Event {++ public enum Cause {+ CREATE,+ UPDATE,+ DELETE,+ }++ final protected Asset deviceAsset;+ final protected Cause cause;++ public InventoryModifiedEvent(Asset deviceAsset, Cause cause) {+ this.deviceAsset = deviceAsset;+ this.cause = cause;+ }++ public Asset getDeviceAsset() {+ return deviceAsset;+ }++ public Cause getCause() {+ return cause;+ }+}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 430562158..f6b3528d5 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@@ -30,6 +30,20 @@ import java.util.Date;import static org.openremote.manager.shared.Constants.PERSISTENCE_JSON_OBJECT_TYPE;import static org.openremote.manager.shared.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;+/**+ * The main model class of this software.+ *+ * An asset is an identifiable item in a composite relationship with other assets. This tree+ * of assets can managed through a <code>null</code> {@link #parentId} property for root+ * items, and a valid parent identifier for sub-items.+ *+ * Each asset has dynamically typed optional attributes with an underlying+ * {@link elemental.json.Json} object model. Use the {@link Attributes} class to work with+ * this API.+ *+ * The location of an asset is stored as a pair of LNG/LAT coordinates.+ *+ */@MappedSuperclass@Table(name = "ASSET")public class Asset {@@ -161,6 +175,10 @@ public class Asset {this.coordinates = coordinates;}+ public boolean hasCoordinates() {+ return getCoordinates() != null && getCoordinates().length > 0;+ }+@Overridepublic String toString() {return getClass().getSimpleName() + "{" +@@ -173,5 +191,4 @@ public class Asset {", attributes='" + (attributes != null ? attributes.toJson() : "null") + '\'' +'}';}-}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetAttributeType.java b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetAttributeType.javadeleted file mode 100644index 026a498fa..000000000--- a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetAttributeType.java+++ /dev/null@@ -1,67 +0,0 @@-/*- * 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.asset;--import elemental.json.Json;-import elemental.json.JsonString;-import org.openremote.manager.shared.attribute.Attribute;-import org.openremote.manager.shared.attribute.AttributeType;-import org.openremote.manager.shared.attribute.MetadataElement;--/**- * Asset attribute metadata type is an arbitrary string. It should be URI. This enum contains- * the well-known URIs for functionality we want to depend on in our platform.- */-public enum AssetAttributeType {-- SENSOR("urn:openremote:asset:sensor"),- ACTUATOR("urn:openremote:asset:actuator");-- final protected String value;-- AssetAttributeType(String value) {- this.value = value;- }-- public String getValue() {- return value;- }-- public JsonString getJsonValue() {- return Json.create(getValue());- }-- public static boolean isSensor(Attribute attribute) {- MetadataElement metaElementType;- return attribute.hasMetadata()- && (metaElementType = attribute.getMetadata().getElement("type")) != null- && metaElementType.getType().equals(AttributeType.STRING.getValue())- && metaElementType.getValue().equals(AssetAttributeType.SENSOR.getJsonValue());- }-- public static boolean isActuator(Attribute attribute) {- MetadataElement metaElementType;- return attribute.hasMetadata()- && (metaElementType = attribute.getMetadata().getElement("type")) != null- && metaElementType.getType().equals(AttributeType.STRING.getValue())- && metaElementType.getValue().equals(AssetAttributeType.ACTUATOR.getJsonValue());- }--}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetModifiedEvent.java b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetModifiedEvent.javanew file mode 100644index 000000000..4e38cb361--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetModifiedEvent.java@@ -0,0 +1,58 @@+/*+ * 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.asset;++import org.openremote.manager.shared.event.Event;++public class AssetModifiedEvent extends Event {++ public enum Cause {+ CREATE,+ UPDATE,+ DELETE,+ CHILDREN_MODIFIED+ }++ final protected Asset asset;+ final protected Cause cause;+ final protected boolean forceRootRefresh;++ public AssetModifiedEvent(Asset asset, Cause cause) {+ this(asset, cause, false);+ }++ public AssetModifiedEvent(Asset asset, Cause cause, boolean forceRootRefresh) {+ this.asset = asset;+ this.cause = cause;+ this.forceRootRefresh = forceRootRefresh;+ }++ public Asset getAsset() {+ return asset;+ }++ public Cause getCause() {+ return cause;+ }++ public boolean isForceRootRefresh() {+ return forceRootRefresh;+ }+}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 ae4fa263a..39a3eadcd 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@@ -79,6 +79,14 @@ public class Attribute {return jsonObject.hasKey("value") ? jsonObject.get("value").asString() : null;}+ public Boolean getValueAsBoolean() {+ return jsonObject.hasKey("value") && jsonObject.get("value").asBoolean();+ }++ public Double getValueAsDouble() {+ return jsonObject.hasKey("value") ? jsonObject.get("value").asNumber() : null;+ }+public JsonObject getValueAsObject() {return jsonObject.hasKey("value") ? jsonObject.getObject("value") : null;}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/attribute/Attributes.java b/manager/shared/src/main/java/org/openremote/manager/shared/attribute/Attributes.javaindex e4c55d78f..977b4eb07 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/attribute/Attributes.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/attribute/Attributes.java@@ -27,9 +27,15 @@ import elemental.json.JsonObject;import java.util.*;+/**+ * Convenience overlay API for {@link JsonObject}.+ *+ * Modifies the given or an empty object.+ */@JsonSerialize(using = AttributesSerializer.class)@JsonDeserialize(using = AttributesDeserializer.class)public class Attributes {+final protected JsonObject jsonObject;public Attributes() {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 69e43ded5..f5fc1ff97 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,7 +19,8 @@*/package org.openremote.manager.shared.connector;-import org.openremote.manager.shared.asset.Asset;+import org.openremote.manager.shared.agent.Agent;+import org.openremote.manager.shared.agent.InventoryModifiedEvent;import org.openremote.manager.shared.attribute.Attributes;/**@@ -27,18 +28,6 @@ import org.openremote.manager.shared.attribute.Attributes;*/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";- public static final String HEADER_DEVICE_ACTION = ConnectorComponent.class.getCanonicalName() + ".HEADER_DEVICE_ACTION";- public static final String ACTION_CREATE = "CREATE";- public static final String ACTION_READ = "READ";- public static final String ACTION_UPDATE = "UPDATE";- public static final String ACTION_DELETE = "DELETE";- public static final String ACTION_SUBSCRIBE = "SUBSCRIBE";- public static final String ACTION_UNSUBSCRIBE = "UNSUBSCRIBE";- public static final String ACTION_WRITE = "WRITE";-/*** Get the unique type descriptor for this connector component*/@@ -48,36 +37,7 @@ public interface ConnectorComponent {* Get the friendly display name for this connector component*/String getDisplayName();-- /**- * Get CRUD support for child assets of the supplied parent asset. A null- * response indicates that this asset doesn't support child assets (this can- * also be indicated with the appropriate values in the returned {@link ChildAssetSupport}.- *- * If parentAsset is null then response indicates child CRUD support at the- * root (in connector terms this usually means agent asset CRUD).- */- ChildAssetSupport getChildSupport(Asset parentAsset);-- /**- * Indicates whether or not this connector component supports child discovery- * of the supplied parent asset.- *- * If parentAsset is null then response indicates whether child discovery is- * supported at the root (in connector terms this usually means is agent asset- * discovery supported).- */- boolean supportsChildDiscovery(Asset parentAsset);-- /**- * Get the settings mask for discovering child assets of the supplied- * parent asset. This is used by clients for user entry of discovery settings.- *- * If parentAsset is null then child discovery is being requested at the root- * (in connector terms this usually means discovering agent assets).- */- Attributes getChildDiscoverySettings(Asset parentAsset);-+/*** 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.@@ -88,85 +48,17 @@ public interface ConnectorComponent {Attributes getConnectorSettings();/**- * Endpoint URI for performing child asset discovery. If implemented- * when child discovery is required then a route will be created requiring- * a consumer from this endpoint which should generate messages for any- * child assets that the connector discovers based on the supplied parent asset- * and discovery settings.- *- * Messages output by the consumer should contain either a single {@link Asset} object or- * an array of {@link Asset} objects. The outputted assets should have IDs and be linked- * to their parent(s) thus allowing child discovery to return a hierarchy of assets.- *- * Discovery should run as long as this route is running.- */- String getChildDiscoveryUri(Asset parentAsset, Attributes discoverySettings);-- /**- * Indicates whether or not this connector component supports monitoring of the supplied- * asset.- *- * If asset monitoring is supported then {@link #getAssetMonitorUri(Asset)} must- * return the Endpoint URI for the asset monitor.+ * Return the inventory endpoint URI where {@link InventoryModifiedEvent}s+ * can be received. If null is returned, no inventory actions will be monitored.*/- boolean supportsMonitoring(Asset asset);+ String getInventoryUri(String agentAssetId, Agent agent);/**- * Endpoint URI for performing asset CRUD. The capabilities supported by a particular- * connector for this asset are determined by the response from {@link #getChildSupport(Asset)}.- *- * Support for reading devices from the inventory is mandatory, all other capabilities are- * optional and are agent/connector dependent.- *- * The endpoint should support InOut (Request Reply) producers. The action to perform is set- * by the {@link #HEADER_INVENTORY_ACTION} message header.- *- * {@Link #ACTION_CREATE}, {@Link #ACTION_UPDATE}, {@Link #ACTION_DELETE} operations- * should consume a {@link Asset}[]. In the case of {@link #ACTION_DELETE} then only the- * asset ID should be required. The reply message body should contain an integer indicating- * the status of the request (conforming to the HTTP Status code specification).- *- * {@link #ACTION_READ} operations should consume a {@link Asset}[] where only the ID should- * be required, if no assets are supplied then all child assets should be returned.- * The reply message body should contain a {@link Asset}[] of the requested devices.- *+ * 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.*/- String getChildInventoryUri(Asset asset);+ String getDiscoveryTriggerUri(String agentAssetId, Agent agent);- /**- * Endpoint URI for: -- * Reading/Writing from/to assets- * Subscribing/Un-subscribing to asset changes- *- * This endpoint is expected to support the InOut MEP with the- * {@link #HEADER_DEVICE_ACTION} message header indicating the action to- * perform/data to return on messages to be consumed by this endpoint.- *- * {@link #ACTION_SUBSCRIBE}, {@link #ACTION_UNSUBSCRIBE} operations should consume a- * {@link Asset}[] where only the ID(s) should be required. The reply message body- * should contain an integer indicating the status of the request (conforming to the HTTP- * Status code specification). Connectors that support asset subscriptions must return- * a valid endpoint URI from {@link #getAssetMonitorUri(Asset)}.- *- * Assets of a connector can share an endpoint which is indicated by returning the same- * endpoint URI.- */- String getAssetUri(Asset asset);-- /**- * Endpoint URI for consuming asset changes as reported by the connector.- *- * A subscribed asset should be monitored by the connector for any resource value- * changes; these changes should then be output in a message body as {@link Asset}[]- * containing the modified attributes.- *- * If not supported then just return null.- */- String getAssetMonitorUri(Asset asset);-- /**- * Generate the asset represented by the supplied asset settings, the connector is responsible- * for setting the asset ID and asset type as well as any attributes and metadata that are required.- */- Asset createAsset(Asset parent, Attributes assetSettings);}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/connector/ConnectorComponentNG.java b/manager/shared/src/main/java/org/openremote/manager/shared/connector/ConnectorComponentNG.javanew file mode 100644index 000000000..640dfd6ef--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/connector/ConnectorComponentNG.java@@ -0,0 +1,155 @@+/*+ * 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.connector;++import org.openremote.manager.shared.asset.Asset;+import org.openremote.manager.shared.attribute.Attributes;++/**+ * TODO This is a more sophisticated API, we should implement what we can in the Next Generation+ *+ * Connectors to external systems are implemented as Apache Camel components.+ */+public interface ConnectorComponentNG extends ConnectorComponent {++ public static final String HEADER_DISCOVERY_START = ConnectorComponentNG.class.getCanonicalName() + ".HEADER_DISCOVERY_START";+ public static final String HEADER_DISCOVERY_STOP = ConnectorComponentNG.class.getCanonicalName() + ".HEADER_DISCOVERY_STOP";+ public static final String HEADER_INVENTORY_ACTION = ConnectorComponentNG.class.getCanonicalName() + ".HEADER_INVENTORY_ACTION";+ public static final String HEADER_DEVICE_ACTION = ConnectorComponentNG.class.getCanonicalName() + ".HEADER_DEVICE_ACTION";+ public static final String ACTION_CREATE = "CREATE";+ public static final String ACTION_READ = "READ";+ public static final String ACTION_UPDATE = "UPDATE";+ public static final String ACTION_DELETE = "DELETE";+ public static final String ACTION_SUBSCRIBE = "SUBSCRIBE";+ public static final String ACTION_UNSUBSCRIBE = "UNSUBSCRIBE";+ public static final String ACTION_WRITE = "WRITE";++ /**+ * Get CRUD support for child assets of the supplied parent asset. A null+ * response indicates that this asset doesn't support child assets (this can+ * also be indicated with the appropriate values in the returned {@link ChildAssetSupport}.+ *+ * If parentAsset is null then response indicates child CRUD support at the+ * root (in connector terms this usually means agent asset CRUD).+ */+ ChildAssetSupport getChildSupport(Asset parentAsset);++ /**+ * Indicates whether or not this connector component supports child discovery+ * of the supplied parent asset.+ *+ * If parentAsset is null then response indicates whether child discovery is+ * supported at the root (in connector terms this usually means is agent asset+ * discovery supported).+ */+ boolean supportsChildDiscovery(Asset parentAsset);++ /**+ * Get the settings mask for discovering child assets of the supplied+ * parent asset. This is used by clients for user entry of discovery settings.+ *+ * If parentAsset is null then child discovery is being requested at the root+ * (in connector terms this usually means discovering agent assets).+ */+ Attributes getChildDiscoverySettings(Asset parentAsset);++ /**+ * Endpoint URI for performing child asset discovery. If implemented+ * when child discovery is required then a route will be created requiring+ * a consumer from this endpoint which should generate messages for any+ * child assets that the connector discovers based on the supplied parent asset+ * and discovery settings.+ *+ * Messages output by the consumer should contain either a single {@link Asset} object or+ * an array of {@link Asset} objects. The outputted assets should have IDs and be linked+ * to their parent(s) thus allowing child discovery to return a hierarchy of assets.+ *+ * Discovery should run as long as this route is running.+ */+ String getChildDiscoveryUri(Asset parentAsset, Attributes discoverySettings);++ /**+ * Indicates whether or not this connector component supports monitoring of the supplied+ * asset.+ *+ * If asset monitoring is supported then {@link #getAssetMonitorUri(Asset)} must+ * return the Endpoint URI for the asset monitor.+ */+ boolean supportsMonitoring(Asset asset);++ /**+ * Endpoint URI for performing asset CRUD. The capabilities supported by a particular+ * connector for this asset are determined by the response from {@link #getChildSupport(Asset)}.+ *+ * Support for reading devices from the inventory is mandatory, all other capabilities are+ * optional and are agent/connector dependent.+ *+ * The endpoint should support InOut (Request Reply) producers. The action to perform is set+ * by the {@link #HEADER_INVENTORY_ACTION} message header.+ *+ * {@Link #ACTION_CREATE}, {@Link #ACTION_UPDATE}, {@Link #ACTION_DELETE} operations+ * should consume a {@link Asset}[]. In the case of {@link #ACTION_DELETE} then only the+ * asset ID should be required. The reply message body should contain an integer indicating+ * the status of the request (conforming to the HTTP Status code specification).+ *+ * {@link #ACTION_READ} operations should consume a {@link Asset}[] where only the ID should+ * be required, if no assets are supplied then all child assets should be returned.+ * The reply message body should contain a {@link Asset}[] of the requested devices.+ *+ */+ String getChildInventoryUri(Asset asset);++ /**+ * Endpoint URI for: -+ * Reading/Writing from/to assets+ * Subscribing/Un-subscribing to asset changes+ *+ * This endpoint is expected to support the InOut MEP with the+ * {@link #HEADER_DEVICE_ACTION} message header indicating the action to+ * perform/data to return on messages to be consumed by this endpoint.+ *+ * {@link #ACTION_SUBSCRIBE}, {@link #ACTION_UNSUBSCRIBE} operations should consume a+ * {@link Asset}[] where only the ID(s) should be required. The reply message body+ * should contain an integer indicating the status of the request (conforming to the HTTP+ * Status code specification). Connectors that support asset subscriptions must return+ * a valid endpoint URI from {@link #getAssetMonitorUri(Asset)}.+ *+ * Assets of a connector can share an endpoint which is indicated by returning the same+ * endpoint URI.+ */+ String getAssetUri(Asset asset);++ /**+ * Endpoint URI for consuming asset changes as reported by the connector.+ *+ * A subscribed asset should be monitored by the connector for any resource value+ * changes; these changes should then be output in a message body as {@link Asset}[]+ * containing the modified attributes.+ *+ * If not supported then just return null.+ */+ String getAssetMonitorUri(Asset asset);++ /**+ * Generate the asset represented by the supplied asset settings, the connector is responsible+ * for setting the asset ID and asset type as well as any attributes and metadata that are required.+ */+ Asset createAsset(Asset parent, Attributes assetSettings);+}diff --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.javaindex 90da39f7e..1daeb51a1 100644--- 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.java@@ -22,16 +22,14 @@ 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 org.openremote.manager.shared.attribute.*;import java.util.ArrayList;import java.util.List;/*** Device asset attribute handling for representing devices that come from agents.- *+ * <p>* 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 uniquediff --git a/manager/shared/src/main/java/org/openremote/manager/shared/util/StringArrayConverter.java b/manager/shared/src/main/java/org/openremote/manager/shared/util/StringArrayConverter.javaindex f2f95d5c1..4b2796779 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/util/StringArrayConverter.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/util/StringArrayConverter.java@@ -25,22 +25,11 @@ public class StringArrayConverter implements AttributeConverter<String[], String@Overridepublic String convertToDatabaseColumn(String[] attribute) {- if (attribute == null || attribute.length == 0)- return null;- StringBuilder sb = new StringBuilder();- for (String s : attribute) {- sb.append(s).append(",");- }- if (sb.length() > 0) {- sb.deleteCharAt(sb.length()-1);- }- return sb.toString();+ return Util.toCommaSeparated(attribute);}@Overridepublic String[] convertToEntityAttribute(String data) {- if (data == null)- return new String[0];- return data.split(",");+ return Util.fromCommaSeparated(data);}}\ No newline at end of filediff --git a/manager/shared/src/main/java/org/openremote/manager/shared/util/Util.java b/manager/shared/src/main/java/org/openremote/manager/shared/util/Util.javaindex 4b51306b9..51fb01d28 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/util/Util.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/util/Util.java@@ -69,4 +69,24 @@ public class Util {}return null;}++ public static String toCommaSeparated(String... strings) {+ if (strings == null || strings.length == 0)+ return null;+ StringBuilder sb = new StringBuilder();+ for (String s : strings) {+ sb.append(s).append(",");+ }+ if (sb.length() > 0) {+ sb.deleteCharAt(sb.length()-1);+ }+ return sb.toString();+ }++ public static String[] fromCommaSeparated(String commaWords) {+ if (commaWords == null)+ return new String[0];+ return commaWords.split(",");+ }+}diff --git a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovyindex 287e0c32e..7c2899de6 100644--- a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy+++ b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy@@ -21,6 +21,8 @@ package org.openremote.testimport com.fasterxml.jackson.databind.ObjectMapperimport elemental.json.JsonValue+import org.apache.camel.ProducerTemplate+import org.apache.camel.builder.RouteBuilderimport org.glassfish.tyrus.client.ClientManagerimport org.jboss.resteasy.client.jaxrs.ResteasyClientimport org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder@@ -217,6 +219,14 @@ trait ContainerTrait {.getAccessToken(realm, new AuthForm(clientId, username, password));}+ static ProducerTemplate getMessageProducerTemplate(Container container) {+ return container.getService(MessageBrokerService.class).getContext().createProducerTemplate();+ }++ static void addRoutes(Container container, RouteBuilder routeBuilder) {+ container.getService(MessageBrokerService.class).getContext().addRoutes(routeBuilder);+ }+static def WebSocketContainer createWebsocketContainer() {return ClientManager.createClient()};diff --git a/test/src/test/groovy/org/openremote/test/controller2/Controller2Service.java b/test/src/test/groovy/org/openremote/test/controller2/Controller2Service.javadeleted file mode 100644index 9a48f07fa..000000000--- a/test/src/test/groovy/org/openremote/test/controller2/Controller2Service.java+++ /dev/null@@ -1,78 +0,0 @@-package org.openremote.test.controller2;--import org.apache.camel.ProducerTemplate;-import org.apache.camel.builder.RouteBuilder;-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.asset.Asset;--import java.util.ArrayList;-import java.util.List;--import static org.openremote.manager.shared.connector.ConnectorComponent.*;--// TODO This is an example service for testing, replaced later with production code-public class Controller2Service implements ContainerService {-- public List<Asset> addedDevices = new ArrayList<>();- public List<Asset> removedDevices = new ArrayList<>();- public List<Asset> updatedDevices = new ArrayList<>();- public ProducerTemplate messageProducerTemplate;-- @Override- public void init(Container container) throws Exception {- }-- @Override- public void configure(Container container) throws Exception {- MessageBrokerService messageBrokerService = container.getService(MessageBrokerService.class);- MessageBrokerContext context = messageBrokerService.getContext();- messageProducerTemplate = context.createProducerTemplate();-- context.addRoutes(new RouteBuilder() {- @Override- public void configure() throws Exception {- from("controller2://192.168.99.100:8083/inventory")- .routeId("Device Inventory")- .choice()- .when(header(HEADER_DEVICE_ACTION).isEqualTo(ACTION_CREATE))- .process(exchange -> {- addedDevices.add(- exchange.getIn().getBody(Asset.class)- );- }).endChoice()- .when(header(HEADER_DEVICE_ACTION).isEqualTo(ACTION_DELETE))- .process(exchange -> {- removedDevices.add(- exchange.getIn().getBody(Asset.class)- );- }).endChoice()- .when(header(HEADER_DEVICE_ACTION).isEqualTo(ACTION_UPDATE))- .process(exchange -> {- updatedDevices.add(- exchange.getIn().getBody(Asset.class)- );- }).end();-- from("direct:triggerDiscovery")- .routeId("Trigger discovery")- .to("controller2://192.168.99.100:8083/discovery");- }- });- }-- @Override- public void start(Container container) {- }-- @Override- public void stop(Container container) {- }-- public void triggerDiscovery() {- messageProducerTemplate.sendBody("direct:triggerDiscovery", "");- }--}\ No newline at end of filediff --git a/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovy b/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovyindex a7d8193f4..50b6c0135 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,9 @@ import org.apache.camel.Exchangeimport org.apache.camel.Processorimport org.apache.camel.builder.RouteBuilderimport org.openremote.container.message.MessageBrokerService+import org.openremote.manager.server.SampleDataService+import org.openremote.manager.server.asset.AssetService+import org.openremote.manager.shared.agent.Agentimport org.openremote.manager.shared.asset.Assetimport org.openremote.manager.shared.asset.AssetTypeimport org.openremote.manager.shared.attribute.AttributeType@@ -12,54 +15,61 @@ import org.openremote.manager.shared.device.DeviceResourceimport org.openremote.test.ContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.BlockingVariables-import spock.util.concurrent.PollingConditionsclass Controller2Test extends Specification implements ContainerTrait {def "Get Device Inventory"() {- given: "a test controller service"- def controllerService = new Controller2Service()-- and: "a clean result state"- def conditions = new PollingConditions(timeout: 3)-- when: "the server container is started"+ given: "the server container is started"def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices(controllerService))-- and: "discovery is triggered"- controllerService.triggerDiscovery()-- then: "the service should receive the devices from the inventory"- conditions.eventually {- assert controllerService.addedDevices.size() > 0- Asset device = controllerService.addedDevices.get(0)+ def container = startContainer(defaultConfig(serverPort), defaultServices())++ when: "we wait a bit for initial state"+ sleep(2000)++ then: "the device assets should be the children of the agent asset"+ def assetService = container.getService(AssetService.class)+ def agentAsset = assetService.get(container.getService(SampleDataService.class).SAMPLE_AGENT_ID)+ agentAsset != null+ def deviceAssetInfos = assetService.getChildren(agentAsset.getId())+ deviceAssetInfos .size() == 1+ deviceAssetInfos.each {+ Asset device = assetService.get(it.id)assert device.name == "TestDevice"assert device.id != nullassert device.wellKnownType == AssetType.DEVICE- DeviceAttributes attributes = new DeviceAttributes(device.attributes)+ def attributes = new DeviceAttributes(device.attributes)assert attributes.deviceResources.length == 5assert attributes.getDeviceResource("Light1Switch").type == AttributeType.STRINGassert attributes.getDeviceResource("Light1Switch").valueAsString == "light1switch"assert attributes.getDeviceResource("Light1Switch").getResourceType() == AttributeType.BOOLEANassert attributes.getDeviceResource("Light1Switch").getAccess() == DeviceResource.Access.RW++ // Clear database for next condition+ assetService.delete(it.id)}+ when: "discovery is triggered"+ getMessageProducerTemplate(container)+ .sendBody(Agent.TOPIC_TRIGGER_DISCOVERY, "") // Empty body triggers all agents++ and: "we wait a bit for inventory response"+ sleep(2000)++ then: "the device assets should be the children of the agent asset"+ def updatedDeviceAssetInfos = assetService.getChildren(agentAsset.getId())+ updatedDeviceAssetInfos.size() == 1+cleanup: "the server should be stopped"stopContainer(container)}def "Write actuator and read updated sensor value"() {- given: "a test controller service"- def controllerService = new Controller2Service()-- and: "a clean result state"- def conditions = new PollingConditions(timeout: 5)+ given: "a clean result state"def result = new BlockingVariables(5)when: "the server container is started"def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices(controllerService))+ 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";@@ -68,10 +78,10 @@ class Controller2Test extends Specification implements ContainerTrait {@Overridevoid configure() throws Exception {from("direct:light1switch")- .to(deviceResourceEndpoint);+ .to(deviceResourceEndpoint);from(deviceResourceEndpoint)- .process(new Processor() {+ .process(new Processor() {@Overridevoid process(Exchange exchange) throws Exception {switch (exchange.getIn().getBody(String.class)) {