100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Work on simulator
Christian Bauerda8547598471
diff --git a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.javaindex 150fa4886..3b953cba8 100644--- a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java@@ -21,10 +21,10 @@ package org.openremote.agent.protocol.simulator;import org.openremote.agent.protocol.AbstractProtocol;import org.openremote.agent.protocol.ConnectionStatus;-import org.openremote.agent.protocol.simulator.element.ColorSimulatorElement;-import org.openremote.agent.protocol.simulator.element.NumberSimulatorElement;+import org.openremote.model.simulator.element.ColorSimulatorElement;+import org.openremote.model.simulator.element.NumberSimulatorElement;import org.openremote.model.simulator.SimulatorElement;-import org.openremote.agent.protocol.simulator.element.SwitchSimulatorElement;+import org.openremote.model.simulator.element.SwitchSimulatorElement;import org.openremote.model.AbstractValueHolder;import org.openremote.model.ValidationFailure;import org.openremote.model.asset.AssetAttribute;@@ -32,10 +32,10 @@ import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.attribute.AttributeState;import org.openremote.model.simulator.SimulatorState;-import org.openremote.model.util.Pair;import org.openremote.model.value.Value;import java.util.*;+import java.util.function.Consumer;import java.util.logging.Logger;import java.util.stream.Collectors;@@ -119,6 +119,9 @@ public class SimulatorProtocol extends AbstractProtocol {static final protected Map<AttributeRef, AttributeRef> attributeInstanceMap = new HashMap<>();static final protected Map<AttributeRef, SimulatorElement> elements = new HashMap<>();+ // TODO This is not nice, find a better way how the protocol can talk to the service (through message bus?)+ protected Consumer<AttributeRef> protocolConfigurationValuesChangedHandler;+@Overridepublic String getProtocolName() {return PROTOCOL_NAME;@@ -188,8 +191,10 @@ public class SimulatorProtocol extends AbstractProtocol {return;}if (attribute.getValue().isPresent()) {- List<ValidationFailure> failures = element.setValue(attribute.getValue().get());+ element.setValue(attribute.getValue().get());+ List<ValidationFailure> failures = element.getValidationFailures();if (!failures.isEmpty()) {+ element.clearValue();LOG.warning("Failed to initialize simulator element, initial value validation failures " + failures + ": " + attribute);return;}@@ -215,7 +220,19 @@ public class SimulatorProtocol extends AbstractProtocol {@Overrideprotected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration) {- putValue(event.getAttributeState());+ if (putValue(event.getAttributeState())) {+ // Notify listener when write was successful+ if (protocolConfigurationValuesChangedHandler != null)+ protocolConfigurationValuesChangedHandler.accept(protocolConfiguration.getReferenceOrThrow());+ }+ }++ public Consumer<AttributeRef> getProtocolConfigurationValuesChangedHandler() {+ return protocolConfigurationValuesChangedHandler;+ }++ public void setValuesChangedHandler(Consumer<AttributeRef> protocolConfigurationValuesChangedHandler) {+ this.protocolConfigurationValuesChangedHandler = protocolConfigurationValuesChangedHandler;}/**@@ -280,34 +297,34 @@ public class SimulatorProtocol extends AbstractProtocol {/*** Call this to simulate a send to actuator.*/- public void putValue(String entityId, String attributeName, Value value) {- putValue(new AttributeState(new AttributeRef(entityId, attributeName), value));+ public boolean putValue(String entityId, String attributeName, Value value) {+ return putValue(new AttributeState(new AttributeRef(entityId, attributeName), value));}/*** Call this to simulate a send to actuator.*/- protected void putValue(AttributeRef attributeRef, Value value) {- putValue(new AttributeState(attributeRef, value));+ protected boolean putValue(AttributeRef attributeRef, Value value) {+ return putValue(new AttributeState(attributeRef, value));}/*** Call this to simulate a send to actuator.*/- public void putValue(AttributeEvent event) {- putValue(event.getAttributeState());+ public boolean putValue(AttributeEvent event) {+ return putValue(event.getAttributeState());}/*** Call this to simulate a send to actuator.*/- public void putValue(AttributeState attributeState) {+ public boolean putValue(AttributeState attributeState) {AttributeRef attributeRef = attributeState.getAttributeRef();AttributeRef instanceRef = attributeInstanceMap.get(attributeRef);if (instanceRef == null) {LOG.warning("Attribute is not referenced by an instance:" + attributeRef);- return;+ return false;}Instance instance;@@ -317,34 +334,37 @@ public class SimulatorProtocol extends AbstractProtocol {if (instance == null) {LOG.warning("No instance found by name '" + instanceRef + "'");- return;+ return false;}if (!instance.isEnabled()) {LOG.fine("Simulator protocol configuration is disabled so cannot process request");- return;+ return false;}LOG.info("Put simulator value: " + attributeState);SimulatorElement element = elements.get(attributeRef);if (element == null) {LOG.warning("No simulated element for: " + attributeRef);- return;+ return false;}- List<ValidationFailure> failures = element.setValue(attributeState.getCurrentValue().orElse(null));+ Optional<Value> oldValue = element.getValue();+ element.setValue(attributeState.getCurrentValue().orElse(null));+ List<ValidationFailure> failures =element.getValidationFailures();if (!failures.isEmpty()) {- if (!failures.isEmpty()) {- LOG.warning("Failed to update simulator element, state validation failures " + failures + ": " + attributeRef);- return;- }- return;+ // Reset to old value+ oldValue.ifPresent(element::setValue);+ LOG.warning("Failed to update simulator element, state validation failures " + failures + ": " + attributeRef);+ return false;}}if (instance.getMode() != Mode.MANUAL) {updateSensor(attributeRef, instance.getMode() == Mode.WRITE_THROUGH_IMMEDIATE ? 0 : instance.getDelayMilliseconds());}++ return true;}/**@@ -360,28 +380,51 @@ public class SimulatorProtocol extends AbstractProtocol {public Optional<Value> getValue(AttributeRef attributeRef) {synchronized (instances) {SimulatorElement element = elements.get(attributeRef);- return element != null ? Optional.ofNullable(element.getValue()) : Optional.empty();+ return element != null ? element.getValue() : Optional.empty();}}+ public List<SimulatorElement> getLinkedElements(AttributeRef protocolConfigurationRef) {+ List<AttributeRef> linkedAttributes = attributeInstanceMap.entrySet().stream()+ .filter(entry -> entry.getValue().equals(protocolConfigurationRef))+ .map(Map.Entry::getKey)+ .collect(Collectors.toList());+ List<SimulatorElement> linkedElements = new ArrayList<>();+ for (AttributeRef linkedAttribute : linkedAttributes) {+ if (elements.containsKey(linkedAttribute)) {+ linkedElements.add(elements.get(linkedAttribute));+ }+ }+ return linkedElements;+ }+/**- * Get attributes linked to the given protocol configuration and their {@link SimulatorElement}s.+ * Read a state snapshot.*/public Optional<SimulatorState> getSimulatorState(AttributeRef protocolConfigurationRef) {synchronized (instances) {+ LOG.info("Getting simulator state for protocol configuration: " + protocolConfigurationRef);if (!instances.containsKey(protocolConfigurationRef))return Optional.empty();- List<AttributeRef> linkedAttributes = attributeInstanceMap.entrySet().stream()- .filter(entry -> entry.getValue().equals(protocolConfigurationRef))- .map(Map.Entry::getKey)- .collect(Collectors.toList());- List<SimulatorElement> result = new ArrayList<>();- for (AttributeRef linkedAttribute : linkedAttributes) {- if (elements.containsKey(linkedAttribute)) {- result.add(elements.get(linkedAttribute));- }+ List<SimulatorElement> linkedElements = getLinkedElements(protocolConfigurationRef);+ return Optional.of(new SimulatorState(protocolConfigurationRef, linkedElements.toArray(new SimulatorElement[linkedElements.size()])));+ }+ }++ /**+ * Write a state snapshot.+ */+ public void updateSimulatorState(SimulatorState simulatorState) {+ synchronized (instances) {+ AttributeRef protocolConfigurationRef = simulatorState.getProtocolConfigurationRef();+ if (!instances.containsKey(protocolConfigurationRef)) {+ LOG.info("Ignoring simulator update, no instance for protocol configuration: " + protocolConfigurationRef);+ return;+ }+ // Merge from updated simulator state onto existing elements, setting their values+ for (SimulatorElement updatedElement : simulatorState.getElements()) {+ putValue(updatedElement.getAttributeRef(), updatedElement.getValue().orElse(null));}- return Optional.of(new SimulatorState(result.toArray(new SimulatorElement[result.size()])));}}diff --git a/manager/client/src/main/java/org/openremote/manager/client/Environment.java b/manager/client/src/main/java/org/openremote/manager/client/Environment.javaindex 8fdb799cc..d5fd0b49e 100644--- a/manager/client/src/main/java/org/openremote/manager/client/Environment.java+++ b/manager/client/src/main/java/org/openremote/manager/client/Environment.java@@ -25,27 +25,16 @@ import org.openremote.manager.client.i18n.ManagerMessages;import org.openremote.manager.client.service.EventService;import org.openremote.manager.client.service.RequestService;import org.openremote.manager.client.service.SecurityService;-import org.openremote.manager.client.simulator.Simulator;import org.openremote.manager.client.style.WidgetStyle;import org.openremote.model.event.bus.EventBus;-import javax.inject.Provider;-/*** Bundle all typically needed dependencies of activities/presenters, so* only one thing can be injected into constructors.*/public interface Environment {- /**- * Various managed components with dependent lifecycle.- */- interface Factory {- Provider<Simulator> getSimulatorProvider();- }-- static Environment create(Factory factory,- SecurityService securityService,+ static Environment create(SecurityService securityService,RequestService requestService,EventService eventService,PlaceController placeController,@@ -55,11 +44,6 @@ public interface Environment {WidgetStyle widgetStyle) {return new Environment() {- @Override- public Factory getFactory() {- return factory;- }-@Overridepublic SecurityService getSecurityService() {return securityService;@@ -123,7 +107,4 @@ public interface Environment {ManagerMessages getMessages();WidgetStyle getWidgetStyle();-- Factory getFactory();-}diff --git a/manager/client/src/main/java/org/openremote/manager/client/ManagerModule.java b/manager/client/src/main/java/org/openremote/manager/client/ManagerModule.javaindex 9d46464a0..122a4ae1e 100644--- a/manager/client/src/main/java/org/openremote/manager/client/ManagerModule.java+++ b/manager/client/src/main/java/org/openremote/manager/client/ManagerModule.java@@ -23,7 +23,6 @@ import com.google.gwt.inject.client.AbstractGinModule;import com.google.gwt.place.shared.PlaceController;import com.google.gwt.place.shared.PlaceHistoryHandler;import com.google.gwt.place.shared.PlaceHistoryMapper;-import com.google.inject.Provider;import com.google.inject.Provides;import com.google.inject.Singleton;import org.openremote.manager.client.event.*;@@ -34,7 +33,6 @@ import org.openremote.manager.client.map.MapAssetPlace;import org.openremote.manager.client.mvp.AppActivityManager;import org.openremote.manager.client.mvp.AppPlaceController;import org.openremote.manager.client.service.*;-import org.openremote.manager.client.simulator.Simulator;import org.openremote.manager.client.style.WidgetStyle;import org.openremote.manager.shared.security.Tenant;import org.openremote.manager.shared.security.TenantResource;@@ -65,15 +63,8 @@ public class ManagerModule extends AbstractGinModule {PlaceHistoryMapper placeHistoryMapper,EventBus eventBus,ManagerMessages managerMessages,- WidgetStyle widgetStyle,- Provider<Simulator> simulatorProvider) {+ WidgetStyle widgetStyle) {return Environment.create(- new Environment.Factory() {- @Override- public Provider<Simulator> getSimulatorProvider() {- return simulatorProvider;- }- },securityService,requestService,eventService,diff --git a/manager/client/src/main/java/org/openremote/manager/client/app/AppControllerImpl.java b/manager/client/src/main/java/org/openremote/manager/client/app/AppControllerImpl.javaindex d1beba158..bb6a783f5 100644--- a/manager/client/src/main/java/org/openremote/manager/client/app/AppControllerImpl.java+++ b/manager/client/src/main/java/org/openremote/manager/client/app/AppControllerImpl.java@@ -85,11 +85,9 @@ public class AppControllerImpl implements AppController, AppView.Presenter {environment.getEventBus().register(SubscriptionFailureEvent.class,- event -> {- environment.getEventBus().dispatch(new ShowFailureEvent(- environment.getMessages().subscriptionFailed(event.getEventType()), 5000- ));- }+ event -> environment.getEventBus().dispatch(new ShowFailureEvent(+ environment.getMessages().subscriptionFailed(event.getEventType()), 5000+ )));}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.javaindex b0afd1ff4..b188d98ef 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java@@ -33,10 +33,12 @@ import org.openremote.model.asset.ReadAssetAttributesEvent;import org.openremote.model.asset.agent.ProtocolConfiguration;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeExecuteStatus;+import org.openremote.model.attribute.AttributeRef;import org.openremote.model.attribute.AttributeState;import org.openremote.model.datapoint.DatapointInterval;import org.openremote.model.datapoint.NumberDatapoint;import org.openremote.model.event.bus.EventRegistration;+import org.openremote.model.simulator.SimulatorState;import org.openremote.model.value.ValueType;import java.util.ArrayList;@@ -59,6 +61,7 @@ public abstract class AttributesBrowserfinal protected Asset asset;final protected List<FormButton> readButtons = new ArrayList<>();+ final protected List<AttributeRef> activeSimulators = new ArrayList<>();protected FormGroup liveUpdatesGroup;protected EventRegistration<AttributeEvent> eventRegistration;@@ -284,10 +287,8 @@ public abstract class AttributesBrowserformField.add(editor);// "Blink" the editor so users know there might be a new value- editor.asWidget().addStyleName(environment.getWidgetStyle().HighlightBackground());- Browser.getWindow().setTimeout(() -> editor- .asWidget()- .removeStyleName(environment.getWidgetStyle().HighlightBackground()), 250);+ formGroup.addStyleName(environment.getWidgetStyle().HighlightBackground());+ Browser.getWindow().setTimeout(() -> formGroup.removeStyleName(environment.getWidgetStyle().HighlightBackground()), 250);// Refresh charts, jump to current time so the new value is visibleFormGroup attributeFormGroup = attributeGroups.get(attribute);@@ -316,12 +317,38 @@ public abstract class AttributesBrowser}protected Simulator createSimulator(AssetAttribute attribute) {+ AttributeRef protocolConfigurationRef = attribute.getReferenceOrThrow();return environment.getSecurityService().isSuperUser() && ProtocolConfiguration.isProtocolConfiguration(attribute)? ProtocolConfiguration.getProtocolName(attribute).filter(name -> name.equals(Constants.PROTOCOL_NAMESPACE + ":simulator"))- .map(name ->environment.getFactory().getSimulatorProvider().get()).orElse(null) : null;+ .map(name -> new Simulator(+ environment,+ protocolConfigurationRef+ ,+ () -> {+ activeSimulators.add(protocolConfigurationRef);+ updateSimulatorSubscription();+ },+ () -> {+ activeSimulators.remove(protocolConfigurationRef);+ updateSimulatorSubscription();+ }+ )).orElse(null) : null;+ }++ protected void updateSimulatorSubscription() {+ if (activeSimulators.size() > 0) {+ environment.getEventService().subscribe(+ SimulatorState.class, new SimulatorState.ConfigurationFilter(+ activeSimulators.toArray(new AttributeRef[activeSimulators.size()])+ )+ );+ } else {+ environment.getEventService().unsubscribe(SimulatorState.class);+ }}+/* ####################################################################### */abstract protected void getNumberDatapoints(AssetAttribute assetAttribute,diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.javaindex b8d12e36c..67f90904a 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java@@ -115,12 +115,12 @@ public class AttributesEditorpublic boolean addAttribute(String name, AttributeType type) {if (getAttributes().stream().anyMatch(isAttributeNameEqualTo(name))) {- showValidationError(environment.getMessages().duplicateAttributeName());+ showValidationError(environment, environment.getMessages().duplicateAttributeName());return false;}if (!ATTRIBUTE_NAME_VALIDATOR.test(name)) {- showValidationError(environment.getMessages().invalidAttributeName());+ showValidationError(environment, environment.getMessages().invalidAttributeName());return false;}@@ -137,7 +137,7 @@ public class AttributesEditorList<ValidationFailure> failures = attribute.getValidationFailures();if (!failures.isEmpty()) {for (ValidationFailure failure : failures) {- showValidationError(attribute.getLabelOrName().orElse(null), failure);+ showValidationError(environment, attribute.getLabelOrName().orElse(null), failure);}return false;}@@ -257,7 +257,7 @@ public class AttributesEditoritemNameEditorGroup.setError(true);itemValueEditorGroup.setError(true);for (ValidationFailure failure : failures) {- showValidationError(item.getName().orElse(null), failure);+ showValidationError(environment, item.getName().orElse(null), failure);}}});@@ -280,7 +280,7 @@ public class AttributesEditorif (!failures.isEmpty()) {formGroup.setError(true);for (ValidationFailure failure : failures) {- showValidationError(item.getName().orElse(null), failure);+ showValidationError(environment, item.getName().orElse(null), failure);}}// Validation failure of meta item marks the attribute form extension as error statediff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.javaindex 2f51cb706..af8d06e8c 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java@@ -114,7 +114,7 @@ public abstract class AttributesView<isValid = false;}if (!isValid) {- showValidationError(environment.getMessages().invalidAssetAttributes());+ showValidationError(environment, environment.getMessages().invalidAssetAttributes());}return isValid;}@@ -132,7 +132,7 @@ public abstract class AttributesView<attributeGroups.get(attribute).setError(true);if (showValidationFailureMessage) {for (ValidationFailure failure : failures) {- showValidationError(attribute.getLabelOrName().orElse(null), failure);+ showValidationError(environment, attribute.getLabelOrName().orElse(null), failure);}}return false;@@ -265,7 +265,7 @@ public abstract class AttributesView<Consumer<List<ValidationFailure>> validationResultConsumer = failures -> {for (ValidationFailure failure : failures) {- showValidationError(attribute.getLabelOrName().orElse(null), failure);+ showValidationError(environment, attribute.getLabelOrName().orElse(null), failure);}};@@ -356,18 +356,4 @@ public abstract class AttributesView<environment.getEventBus().dispatch(new ShowSuccessEvent(text));}- protected void showValidationError(String error) {- environment.getEventBus().dispatch(new ShowFailureEvent(error, 5000));- }-- public void showValidationError(String fieldLabel, ValidationFailure validationFailure) {- StringBuilder error = new StringBuilder();- if (fieldLabel != null)- error.append(environment.getMessages().validationFailedFor(fieldLabel));- else- error.append(environment.getMessages().validationFailed());- if (validationFailure != null)- error.append(": ").append(environment.getMessages().validationFailure(validationFailure.name()));- showValidationError(error.toString());- }}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 d3da22666..0794490aa 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@@ -147,6 +147,8 @@ public interface ManagerMessages extends Messages {String unsupportedMetaItemType(String name);+ String unsupportedValueType(String name);+String emptyMetaItem();String loadingAssets();@@ -392,4 +394,11 @@ public interface ManagerMessages extends Messages {String noAttributes();String simulator();++ String invalidValues();++ String writeSimulatorState();++ String simulatorStateSubmitted();+}diff --git a/manager/client/src/main/java/org/openremote/manager/client/simulator/Simulator.java b/manager/client/src/main/java/org/openremote/manager/client/simulator/Simulator.javaindex 93299bf24..027bc2a15 100644--- a/manager/client/src/main/java/org/openremote/manager/client/simulator/Simulator.java+++ b/manager/client/src/main/java/org/openremote/manager/client/simulator/Simulator.java@@ -19,21 +19,181 @@*/package org.openremote.manager.client.simulator;+import com.google.gwt.dom.client.Style;import com.google.gwt.user.client.ui.FlowPanel;import com.google.gwt.user.client.ui.IsWidget;-import com.google.gwt.user.client.ui.Label;-import com.google.inject.Inject;+import com.google.gwt.user.client.ui.Widget;+import elemental.client.Browser;import org.openremote.manager.client.Environment;+import org.openremote.manager.client.event.ShowSuccessEvent;+import org.openremote.manager.client.widget.*;+import org.openremote.model.ValidationFailure;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.event.bus.EventRegistration;+import org.openremote.model.simulator.RequestSimulatorState;+import org.openremote.model.simulator.SimulatorElement;+import org.openremote.model.simulator.SimulatorState;+import org.openremote.model.value.ValueType;-public class Simulator extends FlowPanel implements IsWidget{+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.function.Consumer;++import static org.openremote.manager.client.widget.ValueEditors.*;++public class Simulator extends FlowPanel implements IsWidget {final protected Environment environment;- @Inject- public Simulator(Environment environment) {+ final protected AttributeRef protocolConfiguration;+ final protected Runnable onCreate;+ final protected Runnable onClose;+ protected EventRegistration<SimulatorState> eventRegistration;+ protected SimulatorState simulatorState;+ protected Map<AttributeRef, FormGroup> formGroups = new HashMap<>();++ public Simulator(Environment environment, AttributeRef protocolConfiguration, Runnable onCreate, Runnable onClose) {this.environment = environment;+ this.protocolConfiguration = protocolConfiguration;+ this.onCreate = onCreate;+ this.onClose = onClose;+setStyleName("layout vertical center or-Simulator");- add(new Label("TODO Use ValueEditors and a new SimulatorResource on server to implement " + environment.getMessages().simulator()));+ addAttachHandler(event -> {+ if (event.isAttached()) {+ createSimulator();+ } else {+ destroySimulator();+ }+ });+ }++ protected void createSimulator() {+ eventRegistration = environment.getEventBus().register(SimulatorState.class, simulatorState -> {+ if (!simulatorState.getProtocolConfigurationRef().equals(protocolConfiguration))+ return;+ this.simulatorState = simulatorState;+ writeView();+ });+ environment.getEventService().dispatch(new RequestSimulatorState(protocolConfiguration));+ onCreate.run();+ }++ protected void destroySimulator() {+ clear();+ if (eventRegistration != null) {+ environment.getEventBus().remove(eventRegistration);+ }+ onClose.run();+ }++ protected void writeView() {+ clear();+ formGroups.clear();++ for (SimulatorElement element : simulatorState.getElements()) {+ FormGroup formGroup = new FormGroup();++ formGroup.getElement().getStyle().setWidth(80, Style.Unit.PCT);++ String elementName = simulatorState.getElementName(element);+ FormLabel formLabel = new FormLabel(elementName);+ formLabel.addStyleName("larger");+ formGroup.addFormLabel(formLabel);++ FormField formField = new FormField();+ formGroup.addFormField(formField);++ Consumer<List<ValidationFailure>> validationResultConsumer =+ failures -> {+ for (ValidationFailure failure : failures) {+ showValidationError(environment, elementName, failure);+ }+ };++ IsWidget editor;+ ValueType valueType = element.getExpectedType().getValueType();+ if (valueType.equals(ValueType.STRING)) {+ String currentValue = element.getValue().map(Object::toString).orElse(null);+ editor = createStringEditor(+ element, currentValue, null, false, "or-SimulatorElement", formGroup, false, validationResultConsumer+ );+ } else if (valueType.equals(ValueType.NUMBER)) {+ String currentValue = element.getValue().map(Object::toString).orElse(null);+ editor = createNumberEditor(+ element, currentValue, null, false, "or-SimulatorElement", formGroup, false, validationResultConsumer+ );+ } else if (valueType.equals(ValueType.BOOLEAN)) {+ Boolean currentValue = element.getValueAsBoolean().orElse(null);+ editor = createBooleanEditor(+ element, currentValue, null, false, "or-SimulatorElement", formGroup, false, validationResultConsumer+ );+ // TODO Support JSON editors+ } else {+ editor= new FormOutputText(+ environment.getMessages().unsupportedValueType(valueType.name())+ );+ }+ formField.add(editor);++ formGroups.put(element.getAttributeRef(), formGroup);+ add(formGroup);+ }++ FormGroup submitGroup = new FormGroup();+ submitGroup.getElement().getStyle().setWidth(80, Style.Unit.PCT);++ FormField submitField = new FormField();+ submitGroup.addFormField(submitField);++ FormButton writeButton = new FormButton(environment.getMessages().writeSimulatorState());+ writeButton.setPrimary(true);+ writeButton.addClickHandler(event -> {+ if (validateElements()) {+ environment.getEventService().dispatch(simulatorState);+ environment.getEventBus().dispatch(+ new ShowSuccessEvent(environment.getMessages().simulatorStateSubmitted())+ );+ }+ });+ submitField.add(writeButton);++ add(submitGroup);++ // "Blink" the editor so users know there might be a new value+ for (FormGroup formGroup : formGroups.values()) {+ formGroup.addStyleName(environment.getWidgetStyle().HighlightBackground());+ }+ Browser.getWindow().setTimeout(() -> {+ for (FormGroup formGroup : formGroups.values())+ formGroup.removeStyleName(environment.getWidgetStyle().HighlightBackground());+ }, 250);+ }++ protected boolean validateElements() {+ boolean isValid = true;+ for (SimulatorElement element : simulatorState.getElements()) {+ if (!validateElement(element))+ isValid = false;+ }+ if (!isValid) {+ showValidationError(environment, environment.getMessages().invalidValues());+ }+ return isValid;+ }++ public boolean validateElement(SimulatorElement element) {+ // If there is already an error displayed, don't do other validation+ FormGroup formGroup = formGroups.get(element.getAttributeRef());+ if (formGroup.isError()) {+ return false;+ }+ List<ValidationFailure> failures = element.getValidationFailures();+ if (!failures.isEmpty()) {+ formGroups.get(element.getAttributeRef()).setError(true);+ }+ return true;}}diff --git a/manager/client/src/main/java/org/openremote/manager/client/toast/Toast.java b/manager/client/src/main/java/org/openremote/manager/client/toast/Toast.javaindex 292a95d54..8e29a77a1 100644--- a/manager/client/src/main/java/org/openremote/manager/client/toast/Toast.java+++ b/manager/client/src/main/java/org/openremote/manager/client/toast/Toast.java@@ -65,4 +65,9 @@ public class Toast {public boolean isExpired() {return !isDurableFailure() && (getTimestamp() + getMaxAgeMillis()) <= System.currentTimeMillis();}++ public boolean equalsForUser(Toast that) {+ return getType().equals(that.getType()) && getText().equals(that.getText()) && getMaxAgeMillis() == that.getMaxAgeMillis();+ }+}diff --git a/manager/client/src/main/java/org/openremote/manager/client/toast/Toasts.java b/manager/client/src/main/java/org/openremote/manager/client/toast/Toasts.javaindex 894300426..f021be9f5 100644--- a/manager/client/src/main/java/org/openremote/manager/client/toast/Toasts.java+++ b/manager/client/src/main/java/org/openremote/manager/client/toast/Toasts.java@@ -71,6 +71,13 @@ public class Toasts extends Timer {if (toast == null)return;synchronized (toasts) {++ // If it's the same toast content, only show it once+ for (Toast existing : toasts) {+ if (existing.equalsForUser(toast))+ return;+ }+toasts.add(toast);if (!isRunning())scheduleRepeating(100);diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/ValueEditors.java b/manager/client/src/main/java/org/openremote/manager/client/widget/ValueEditors.javaindex f35a2d429..d64cde140 100644--- a/manager/client/src/main/java/org/openremote/manager/client/widget/ValueEditors.java+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/ValueEditors.java@@ -22,11 +22,13 @@ package org.openremote.manager.client.widget;import com.google.gwt.i18n.client.DateTimeFormat;import com.google.gwt.user.client.ui.FlowPanel;import com.google.gwt.user.client.ui.IsWidget;+import org.openremote.manager.client.Environment;import org.openremote.manager.client.app.dialog.JsonEditor;-import org.openremote.model.AbstractValueHolder;+import org.openremote.manager.client.event.ShowFailureEvent;import org.openremote.model.AbstractValueTimestampHolder;import org.openremote.model.Constants;import org.openremote.model.ValidationFailure;+import org.openremote.model.ValueHolder;import org.openremote.model.value.ArrayValue;import org.openremote.model.value.ObjectValue;import org.openremote.model.value.Value;@@ -48,17 +50,17 @@ public final class ValueEditors {}/**- * Maps a {@link FormGroup} which is typically one editor line to an {@link AbstractValueHolder} and+ * Maps a {@link FormGroup} which is typically one editor line to an {@link ValueHolder} and* encapsulates the raw value that should be set on the value holder and the consumer of validation failure* results. If there are no validation failures, the update was successful.*/private static class ValueUpdate<T> {final FormGroup formGroup;- final AbstractValueHolder valueHolder;+ final ValueHolder valueHolder;final Consumer<List<ValidationFailure>> resultConsumer;final T rawValue;- public ValueUpdate(FormGroup formGroup, AbstractValueHolder valueHolder, Consumer<List<ValidationFailure>> resultConsumer, T rawValue) {+ public ValueUpdate(FormGroup formGroup, ValueHolder valueHolder, Consumer<List<ValidationFailure>> resultConsumer, T rawValue) {this.formGroup = formGroup;this.valueHolder = valueHolder;this.resultConsumer = resultConsumer;@@ -147,7 +149,7 @@ public final class ValueEditors {}}- public static IsWidget createStringEditor(AbstractValueHolder valueHolder,+ public static IsWidget createStringEditor(ValueHolder valueHolder,String currentValue,String defaultValue,boolean readOnly,@@ -159,7 +161,7 @@ public final class ValueEditors {? rawValue -> STRING_UPDATER.accept(new ValueUpdate<>(formGroup, valueHolder, validationResultConsumer, rawValue)): null;FlowPanel panel = new FlowPanel();- panel.setStyleName("flex layout horizontal center or-StringValueEditor");+ panel.setStyleName("flex layout horizontal center or-ValueEditor or-StringValueEditor");IsWidget widget = ValueEditors.createStringEditorWidget(styleName, currentValue, defaultValue, updateConsumer);FlowPanel widgetWrapper = new FlowPanel();widgetWrapper.setStyleName("flex layout horizontal center");@@ -174,7 +176,7 @@ public final class ValueEditors {}- public static IsWidget createNumberEditor(AbstractValueHolder valueHolder,+ public static IsWidget createNumberEditor(ValueHolder valueHolder,String currentValue,String defaultValue,boolean readOnly,@@ -188,7 +190,7 @@ public final class ValueEditors {: null;FlowPanel panel = new FlowPanel();- panel.setStyleName("flex layout horizontal center or-NumberValueEditor");+ panel.setStyleName("flex layout horizontal center or-ValueEditor or-NumberValueEditor");IsWidget widget = ValueEditors.createStringEditorWidget(styleName, currentValue, defaultValue, updateConsumer);FlowPanel widgetWrapper = new FlowPanel();widgetWrapper.setStyleName("flex layout horizontal center");@@ -202,7 +204,7 @@ public final class ValueEditors {return () -> panel;}- public static IsWidget createBooleanEditor(AbstractValueHolder valueHolder,+ public static IsWidget createBooleanEditor(ValueHolder valueHolder,Boolean currentValue,Boolean defaultValue,boolean readOnly,@@ -215,7 +217,7 @@ public final class ValueEditors {: null;FlowPanel panel = new FlowPanel();- panel.setStyleName("flex layout horizontal center or-BooleanValueEditor");+ panel.setStyleName("flex layout horizontal center or-ValueEditor or-BooleanValueEditor");IsWidget widget = ValueEditors.createBooleanEditorWidget(styleName, currentValue, defaultValue, updateConsumer);FlowPanel widgetWrapper = new FlowPanel();widgetWrapper.setStyleName("flex layout horizontal center");@@ -229,7 +231,7 @@ public final class ValueEditors {return () -> panel;}- public static IsWidget createObjectEditor(AbstractValueHolder valueHolder,+ public static IsWidget createObjectEditor(ValueHolder valueHolder,ObjectValue currentValue,Supplier<Value> resetSupplier,boolean readOnly,@@ -243,7 +245,7 @@ public final class ValueEditors {? rawValue -> VALUE_UPDATER.accept(new ValueUpdate<>(formGroup, valueHolder, validationResultConsumer, rawValue)): null;FlowPanel panel = new FlowPanel();- panel.setStyleName("flex layout horizontal center or-ObjectValueEditor");+ panel.setStyleName("flex layout horizontal center or-ValueEditor or-ObjectValueEditor");IsWidget widget = createJsonEditorWidget(jsonEditor, label, title, currentValue, updateConsumer, resetSupplier);@@ -259,7 +261,7 @@ public final class ValueEditors {return () -> panel;}- public static IsWidget createArrayEditor(AbstractValueHolder valueHolder,+ public static IsWidget createArrayEditor(ValueHolder valueHolder,ArrayValue currentValue,Supplier<Value> resetSupplier,boolean readOnly,@@ -274,7 +276,7 @@ public final class ValueEditors {: null;FlowPanel panel = new FlowPanel();- panel.setStyleName("flex layout horizontal center or-ArrayValueEditor");+ panel.setStyleName("flex layout horizontal center or-ValueEditor or-ArrayValueEditor");IsWidget widget = createJsonEditorWidget(jsonEditor, label, title, currentValue, updateConsumer, resetSupplier);@@ -290,6 +292,21 @@ public final class ValueEditors {return () -> panel;}+ public static void showValidationError(Environment environment, String error) {+ environment.getEventBus().dispatch(new ShowFailureEvent(error, 5000));+ }++ public static void showValidationError(Environment environment, String fieldLabel, ValidationFailure validationFailure) {+ StringBuilder error = new StringBuilder();+ if (fieldLabel != null)+ error.append(environment.getMessages().validationFailedFor(fieldLabel));+ else+ error.append(environment.getMessages().validationFailed());+ if (validationFailure != null)+ error.append(": ").append(environment.getMessages().validationFailure(validationFailure.name()));+ showValidationError(environment, error.toString());+ }+private static IsWidget createStringEditorWidget(String styleName,String currentValue,String defaultValue,@@ -304,11 +321,11 @@ public final class ValueEditors {input.setValue("-");}if (updateConsumer != null) {- input.addValueChangeHandler(- event -> updateConsumer.accept(- event.getValue() == null || event.getValue().length() == 0 ? null : event.getValue()- )- );+ // Both keyup and change (e.g. after pasting) must be used+ input.addKeyUpHandler(event ->+ updateConsumer.accept(input.getValue() == null || input.getValue().length() == 0 ? null : input.getValue()));+ input.addValueChangeHandler(event ->+ updateConsumer.accept(event.getValue() == null || event.getValue().length() == 0 ? null : event.getValue()));} else {input.setReadOnly(true);}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 54244e597..73608ae2e 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@@ -71,6 +71,7 @@ sessionTimedOut=Your session timed out. Please close or reload this browser winddescription=DescriptionunsupportedAttributeType=Not implemented attribute type: {0}unsupportedMetaItemType=Not implemented meta item type : {0}+unsupportedValueType=Not implemented value type: {0}loadingAssets=Loading assets...assetName=Asset nameupdateAsset=Save asset@@ -255,4 +256,7 @@ eventsRemoved=All events removed.settingsSaved=Settings saved.noAttributes=Asset has no attributes.simulator=Simulator+invalidValues=Invalid values, please correct.+writeSimulatorState=Write simulator state+simulatorStateSubmitted=Simulator state submitted to server.diff --git a/manager/client/src/main/webapp/css/style.html b/manager/client/src/main/webapp/css/style.htmlindex 53e9624f0..508e5f531 100644--- a/manager/client/src/main/webapp/css/style.html+++ b/manager/client/src/main/webapp/css/style.html@@ -600,4 +600,8 @@height: 30em;}+ .or-SimulatorElement {+ width: 100%;+ }+</style>\ No newline at end of filediff --git a/manager/client/src/main/webapp/css/theme.html b/manager/client/src/main/webapp/css/theme.htmlindex 79deacad2..4d5451b43 100644--- a/manager/client/src/main/webapp/css/theme.html+++ b/manager/client/src/main/webapp/css/theme.html@@ -390,13 +390,13 @@border-color: var(--theme-lightgrey);}- .or-HighlightBackground {+ .or-HighlightBackground .or-ValueEditor {background-color: var(--theme-lightgreen);border-color: transparent;color: white;}- .or-HighlightBackground .or-FormControl {+ .or-HighlightBackground .or-ValueEditor .or-FormControl {color: var(--theme-white);border-color: transparent;}diff --git a/manager/server/src/main/java/org/openremote/manager/server/Main.java b/manager/server/src/main/java/org/openremote/manager/server/Main.javaindex 5b57f22a7..48d820402 100644--- a/manager/server/src/main/java/org/openremote/manager/server/Main.java+++ b/manager/server/src/main/java/org/openremote/manager/server/Main.java@@ -41,6 +41,7 @@ import org.openremote.manager.server.rules.RulesetStorageService;import org.openremote.manager.server.security.ManagerIdentityService;import org.openremote.manager.server.setup.SetupService;import org.openremote.manager.server.concurrent.ManagerExecutorService;+import org.openremote.manager.server.simulator.SimulatorService;import org.openremote.manager.server.web.ManagerWebService;import java.util.ArrayList;@@ -72,6 +73,7 @@ public class Main {ServiceLoader.load(Protocol.class).forEach(this::add);addAll(Arrays.asList(new AgentService(),+ new SimulatorService(),new MapService(),new NotificationService(),new MessageBrokerService(),diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.javaindex 996465707..4e3e79fb9 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java@@ -57,6 +57,7 @@ import static org.openremote.manager.server.event.ClientEventService.getSessionKpublic class AssetStorageService extends RouteBuilder implements ContainerService, Consumer<AssetState> {private static final Logger LOG = Logger.getLogger(AssetStorageService.class.getName());+protected TimerService timerService;protected PersistenceService persistenceService;protected ManagerIdentityService managerIdentityService;diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.javaindex 62440ba22..9b687d8ae 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java@@ -21,10 +21,9 @@ package org.openremote.manager.server.setup.builtin;import com.vividsolutions.jts.geom.Coordinate;import org.openremote.agent.protocol.simulator.SimulatorProtocol;-import org.openremote.agent.protocol.simulator.element.ColorSimulatorElement;-import org.openremote.agent.protocol.simulator.element.NumberSimulatorElement;-import org.openremote.agent.protocol.simulator.element.SwitchSimulatorElement;-import org.openremote.agent.protocol.upnp.UpnpProtocol;+import org.openremote.model.simulator.element.ColorSimulatorElement;+import org.openremote.model.simulator.element.NumberSimulatorElement;+import org.openremote.model.simulator.element.SwitchSimulatorElement;import org.openremote.container.Container;import org.openremote.manager.server.asset.ServerAsset;import org.openremote.manager.server.setup.AbstractManagerSetup;diff --git a/manager/server/src/main/java/org/openremote/manager/server/simulator/SimulatorResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/simulator/SimulatorResourceImpl.javadeleted file mode 100644index da56f4f91..000000000--- a/manager/server/src/main/java/org/openremote/manager/server/simulator/SimulatorResourceImpl.java+++ /dev/null@@ -1,61 +0,0 @@-/*- * Copyright 2017, 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.simulator;--import org.openremote.agent.protocol.simulator.SimulatorProtocol;-import org.openremote.manager.server.asset.AssetStorageService;-import org.openremote.manager.server.security.ManagerIdentityService;-import org.openremote.manager.server.web.ManagerWebResource;-import org.openremote.manager.shared.http.RequestParams;-import org.openremote.manager.shared.simulator.SimulatorResource;-import org.openremote.model.simulator.SimulatorState;-import org.openremote.model.attribute.AttributeRef;--public class SimulatorResourceImpl extends ManagerWebResource implements SimulatorResource {-- final protected SimulatorProtocol simulatorProtocol;- final protected AssetStorageService assetStorageService;-- public SimulatorResourceImpl(ManagerIdentityService identityService,- SimulatorProtocol simulatorProtocol,- AssetStorageService assetStorageService) {- super(identityService);- this.simulatorProtocol = simulatorProtocol;- this.assetStorageService = assetStorageService;- }-- @Override- public SimulatorState getSimulatorState(RequestParams requestParams, String agentId, String protocolConfiguration) {- SimulatorState simulatorState =- simulatorProtocol.getSimulatorState(new AttributeRef(agentId, protocolConfiguration)).orElse(null);-- simulatorState.updateAttributeDetails(- assetStorageService.findNames()- );--- return simulatorState;- }-- @Override- public void updateSimulatorState(RequestParams requestParams, AttributeRef protocolConfigurationRef, SimulatorState simulatorState) {-- }-}diff --git a/manager/server/src/main/java/org/openremote/manager/server/simulator/SimulatorService.java b/manager/server/src/main/java/org/openremote/manager/server/simulator/SimulatorService.javanew file mode 100644index 000000000..4131de3ec--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/simulator/SimulatorService.java@@ -0,0 +1,153 @@+/*+ * 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.simulator;++import org.apache.camel.builder.RouteBuilder;+import org.openremote.agent.protocol.simulator.SimulatorProtocol;+import org.openremote.container.Container;+import org.openremote.container.ContainerService;+import org.openremote.container.message.MessageBrokerSetupService;+import org.openremote.container.security.AuthContext;+import org.openremote.manager.server.asset.AssetStorageService;+import org.openremote.manager.server.event.ClientEventService;+import org.openremote.manager.server.security.ManagerIdentityService;+import org.openremote.model.Constants;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.simulator.RequestSimulatorState;+import org.openremote.model.simulator.SimulatorState;++import java.util.List;+import java.util.logging.Logger;++import static org.openremote.manager.server.event.ClientEventService.CLIENT_EVENT_TOPIC;+import static org.openremote.manager.server.event.ClientEventService.getSessionKey;++/**+ * Connects the client/UI to the {@link SimulatorProtocol}.+ */+public class SimulatorService extends RouteBuilder implements ContainerService {++ private static final Logger LOG = Logger.getLogger(SimulatorService.class.getName());++ protected ManagerIdentityService managerIdentityService;+ protected AssetStorageService assetStorageService;+ protected ClientEventService clientEventService;+ protected SimulatorProtocol simulatorProtocol;++ @Override+ public void init(Container container) throws Exception {+ managerIdentityService = container.getService(ManagerIdentityService.class);+ assetStorageService = container.getService(AssetStorageService.class);+ clientEventService = container.getService(ClientEventService.class);+ simulatorProtocol = container.getService(SimulatorProtocol.class);++ clientEventService.addSubscriptionAuthorizer((auth, subscription) -> {+ if (!subscription.isEventType(SimulatorState.class))+ return false;++ // Superuser can get all+ if (auth.isSuperUser())+ return true;++ // TODO Should realm admins be able to work with simulators in their tenant?++ return false;+ });++ container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);++ // When a protocol instance has its values updated through linked attribute writes, publish a snapshot to all sessions+ simulatorProtocol.setValuesChangedHandler(+ protocolConfiguration -> publishSimulatorState(null, protocolConfiguration)+ );+ }++ @Override+ public void start(Container container) throws Exception {++ }++ @Override+ public void stop(Container container) throws Exception {++ }++ @Override+ public void configure() throws Exception {+ from(CLIENT_EVENT_TOPIC)+ .routeId("FromClientSimulatorRequests")+ .filter(body().isInstanceOf(RequestSimulatorState.class))+ .process(exchange -> {+ RequestSimulatorState event = exchange.getIn().getBody(RequestSimulatorState.class);+ LOG.fine("Handling from client: " + event);++ String sessionKey = getSessionKey(exchange);+ AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);++ // Superuser can get all+ if (!authContext.isSuperUser())+ return;++ // TODO Should realm admins be able to work with simulators in their tenant?++ for (AttributeRef protocolConfiguration : event.getConfigurations()) {+ publishSimulatorState(sessionKey, protocolConfiguration);+ }+ });++ from(CLIENT_EVENT_TOPIC)+ .routeId("FromClientSimulatorState")+ .filter(body().isInstanceOf(SimulatorState.class))+ .process(exchange -> {+ SimulatorState event = exchange.getIn().getBody(SimulatorState.class);+ LOG.fine("Handling from client: " + event);++ AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);++ // Superuser can get all+ if (!authContext.isSuperUser())+ return;++ // TODO Should realm admins be able to work with simulators in their tenant?++ simulatorProtocol.updateSimulatorState(event);+ });+ }++ protected void publishSimulatorState(String sessionKey, AttributeRef protocolConfiguration) {+ LOG.fine("Attempting to publish simulator state: " + protocolConfiguration);+ simulatorProtocol.getSimulatorState(protocolConfiguration).ifPresent(simulatorState -> {+ // We need asset names instead of identifiers for user-friendly display+ simulatorState.updateAssetNames(assetIdAndNames -> {+ String[] assetIds = assetIdAndNames.keySet().toArray(new String[0]);+ List<String> assetNames = assetStorageService.findNames(assetIds);+ for (int i = 0; i < assetIds.length; i++) {+ String assetId = assetIds[i];+ assetIdAndNames.put(assetId, assetNames.get(i));+ }+ });+ if (sessionKey != null) {+ clientEventService.sendToSession(sessionKey, simulatorState);+ } else {+ clientEventService.publishEvent(simulatorState);+ }+ });+ }+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebService.java b/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebService.javaindex b74ccc0d6..ee45ba31b 100644--- a/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebService.java@@ -21,12 +21,9 @@ package org.openremote.manager.server.web;import io.undertow.server.HttpHandler;import io.undertow.servlet.api.DeploymentInfo;-import org.openremote.agent.protocol.simulator.SimulatorProtocol;import org.openremote.container.Container;import org.openremote.container.security.IdentityService;import org.openremote.container.web.WebService;-import org.openremote.manager.server.security.ManagerIdentityService;-import org.openremote.manager.server.simulator.SimulatorResourceImpl;import org.openremote.model.Constants;import javax.ws.rs.core.UriBuilder;@@ -86,16 +83,6 @@ public class ManagerWebService extends WebService {CONSOLE_PATH, ManagerFileServlet.wrapHandler(consoleHandler, CONSOLE_PATTERN));- if (container.hasService(SimulatorProtocol.class)) {- LOG.info("Enabling simulator web resource");- container.getService(WebService.class).getApiSingletons().add(- new SimulatorResourceImpl(- container.getService(ManagerIdentityService.class),- container.getService(SimulatorProtocol.class)- )- );- }-super.init(container);}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/simulator/SimulatorResource.java b/manager/shared/src/main/java/org/openremote/manager/shared/simulator/SimulatorResource.javadeleted file mode 100644index cd53c92d0..000000000--- a/manager/shared/src/main/java/org/openremote/manager/shared/simulator/SimulatorResource.java+++ /dev/null@@ -1,52 +0,0 @@-/*- * Copyright 2017, 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.simulator;--import jsinterop.annotations.JsType;-import org.openremote.manager.shared.http.RequestParams;-import org.openremote.manager.shared.http.SuccessStatusCode;-import org.openremote.model.attribute.AttributeRef;-import org.openremote.model.simulator.SimulatorState;--import javax.annotation.security.RolesAllowed;-import javax.ws.rs.*;--import static javax.ws.rs.core.MediaType.APPLICATION_JSON;--@Path("simulator")-@JsType(isNative = true)-public interface SimulatorResource {-- @Path("{agentId}/{protocolConfiguration}")- @GET- @Produces(APPLICATION_JSON)- @SuccessStatusCode(200)- //@RolesAllowed({"read:admin", "write:admin"})- SimulatorState getSimulatorState(@BeanParam RequestParams requestParams,- @PathParam("agentId") String agentId,- @PathParam("protocolConfiguration") String protocolConfiguration);-- @PUT- @Produces(APPLICATION_JSON)- @SuccessStatusCode(200)- @RolesAllowed({"read:admin", "write:admin"})- void updateSimulatorState(@BeanParam RequestParams requestParams, AttributeRef protocolConfigurationRef, SimulatorState simulatorState);--}diff --git a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovyindex fd67d9aa7..5ac78f038 100644--- a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy+++ b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy@@ -26,6 +26,7 @@ import org.openremote.manager.server.rules.RulesServiceimport org.openremote.manager.server.rules.RulesetStorageServiceimport org.openremote.manager.server.security.ManagerIdentityServiceimport org.openremote.manager.server.setup.SetupService+import org.openremote.manager.server.simulator.SimulatorServiceimport org.openremote.manager.server.web.ManagerWebServiceimport java.util.concurrent.TimeUnit@@ -67,6 +68,7 @@ trait ManagerContainerTrait extends ContainerTrait {new AssetProcessingService(),*Lists.newArrayList(ServiceLoader.load(Protocol.class)),new AgentService(),+ new SimulatorService(),new MapService(),new NotificationService(),new MessageBrokerService(),diff --git a/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovyindex eef83de89..bae4f8e72 100644--- a/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy@@ -18,6 +18,7 @@ import org.openremote.manager.client.event.ShowFailureEventimport org.openremote.manager.client.event.ShowSuccessEventimport org.openremote.manager.client.event.WillGoToPlaceEventimport org.openremote.manager.client.i18n.ManagerMessages+import org.openremote.manager.client.service.EventServiceimport org.openremote.manager.client.service.RequestServiceImplimport org.openremote.manager.client.style.WidgetStyleimport org.openremote.manager.server.security.ManagerIdentityService@@ -27,7 +28,6 @@ import org.openremote.manager.shared.security.TenantResourceimport org.openremote.manager.shared.validation.ConstraintViolationReportimport org.openremote.model.event.Eventimport org.openremote.model.event.bus.EventListener-import org.openremote.manager.client.service.EventServiceimport org.openremote.test.ClientObjectMapperimport org.openremote.test.ClientSecurityServiceimport org.openremote.test.GwtClientTrait@@ -134,7 +134,6 @@ class AdminTenantsActivityTest extends Specification implements ManagerContainerand: "An activity management configuration"def environment = Environment.create(- Mock(Environment.Factory),securityService,requestService,Mock(EventService),diff --git a/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovyindex 229dc6dbc..e23d84333 100644--- a/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy@@ -11,19 +11,19 @@ import org.openremote.manager.client.admin.*import org.openremote.manager.client.admin.navigation.AdminNavigationimport org.openremote.manager.client.admin.navigation.AdminNavigationPresenterimport org.openremote.manager.client.admin.users.*-import org.openremote.manager.server.security.ManagerIdentityServiceimport org.openremote.manager.client.event.GoToPlaceEventimport org.openremote.manager.client.event.ShowSuccessEventimport org.openremote.manager.client.event.WillGoToPlaceEventimport org.openremote.manager.client.i18n.ManagerMessages+import org.openremote.manager.client.service.EventServiceimport org.openremote.manager.client.service.RequestServiceImplimport org.openremote.manager.client.style.WidgetStyle+import org.openremote.manager.server.security.ManagerIdentityServiceimport org.openremote.manager.shared.http.EntityReaderimport org.openremote.manager.shared.security.*import org.openremote.manager.shared.validation.ConstraintViolationReportimport org.openremote.model.event.Eventimport org.openremote.model.event.bus.EventListener-import org.openremote.manager.client.service.EventServiceimport org.openremote.test.ClientObjectMapperimport org.openremote.test.ClientSecurityServiceimport org.openremote.test.GwtClientTrait@@ -154,7 +154,6 @@ class AdminUsersActivityTest extends Specification implements ManagerContainerTrand: "An activity management configuration"def environment = Environment.create(- Mock(Environment.Factory),securityService,requestService,Mock(EventService),diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovyindex 154acd0d8..ab361dcc8 100644--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy@@ -1,11 +1,11 @@package org.openremote.test.assetsimport com.google.gwt.junit.GWTMockUtilities-import org.openremote.manager.client.ManagerHistoryMapperimport com.google.gwt.place.shared.WithTokenizersimport com.google.gwt.user.client.ui.Widgetimport com.google.gwt.view.client.HasDataimport org.openremote.manager.client.Environment+import org.openremote.manager.client.ManagerHistoryMapperimport org.openremote.manager.client.admin.TenantArrayMapperimport org.openremote.manager.client.assets.AssetArrayMapperimport org.openremote.manager.client.assets.AssetMapper@@ -103,7 +103,6 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContainedef placeController = createPlaceController(securityService, eventBus)def placeHistoryMapper = createPlaceHistoryMapper(ManagerHistoryMapper.getAnnotation(WithTokenizers.class))def environment = Environment.create(- Mock(Environment.Factory),securityService,requestService,clientEventService,@@ -276,7 +275,6 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContainedef placeController = createPlaceController(securityService, eventBus)def placeHistoryMapper = createPlaceHistoryMapper(ManagerHistoryMapper.getAnnotation(WithTokenizers.class))def environment = Environment.create(- Mock(Environment.Factory),securityService,requestService,clientEventService,@@ -455,7 +453,6 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContainedef placeController = createPlaceController(securityService, eventBus)def placeHistoryMapper = createPlaceHistoryMapper(ManagerHistoryMapper.getAnnotation(WithTokenizers.class))def environment = Environment.create(- Mock(Environment.Factory),securityService,requestService,clientEventService,diff --git a/model/src/main/java/org/openremote/model/AbstractValueHolder.java b/model/src/main/java/org/openremote/model/AbstractValueHolder.javaindex 7ccdc9a62..133cc132d 100644--- a/model/src/main/java/org/openremote/model/AbstractValueHolder.java+++ b/model/src/main/java/org/openremote/model/AbstractValueHolder.java@@ -34,7 +34,7 @@ import java.util.Optional;* {@link ObjectValue} that has a <code>value</code> field that accepts any* {@link Value}.*/-public abstract class AbstractValueHolder {+public abstract class AbstractValueHolder implements ValueHolder {protected static final String VALUE_FIELD_NAME = "value";diff --git a/model/src/main/java/org/openremote/model/ValueHolder.java b/model/src/main/java/org/openremote/model/ValueHolder.javanew file mode 100644index 000000000..b77479d8b--- /dev/null+++ b/model/src/main/java/org/openremote/model/ValueHolder.java@@ -0,0 +1,61 @@+/*+ * Copyright 2017, 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.model;++import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;++import java.util.List;+import java.util.Optional;++/**+ * Holds a {@link Value}.+ */+public interface ValueHolder {++ void clearValue();++ Optional<Value> getValue();++ Optional<String> getValueAsString();++ Optional<Double> getValueAsNumber();++ Optional<Integer> getValueAsInteger();++ Optional<Boolean> getValueAsBoolean();++ Optional<ObjectValue> getValueAsObject();++ Optional<ArrayValue> getValueAsArray();++ void setValue(Value value);++ void setValue(Value... values);++ void setValue(String string);++ void setValue(Double number);++ void setValue(Boolean b);++ List<ValidationFailure> getValidationFailures();+}diff --git a/model/src/main/java/org/openremote/model/event/shared/EventFilter.java b/model/src/main/java/org/openremote/model/event/shared/EventFilter.javaindex fb3ecb110..cd621a1f5 100644--- a/model/src/main/java/org/openremote/model/event/shared/EventFilter.java+++ b/model/src/main/java/org/openremote/model/event/shared/EventFilter.java@@ -24,6 +24,7 @@ import com.fasterxml.jackson.annotation.JsonSubTypes;import com.fasterxml.jackson.annotation.JsonTypeInfo;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.asset.AssetTreeModifiedEvent;+import org.openremote.model.simulator.SimulatorState;import org.openremote.model.syslog.SyslogEvent;/**@@ -32,7 +33,8 @@ import org.openremote.model.syslog.SyslogEvent;@JsonSubTypes({@JsonSubTypes.Type(value = SyslogEvent.LevelCategoryFilter.class, name = SyslogEvent.LevelCategoryFilter.FILTER_TYPE),@JsonSubTypes.Type(value = AttributeEvent.EntityIdFilter.class, name = AttributeEvent.EntityIdFilter.FILTER_TYPE),- @JsonSubTypes.Type(value = AssetTreeModifiedEvent.TenantFilter.class, name = AssetTreeModifiedEvent.TenantFilter.FILTER_TYPE)+ @JsonSubTypes.Type(value = AssetTreeModifiedEvent.TenantFilter.class, name = AssetTreeModifiedEvent.TenantFilter.FILTER_TYPE),+ @JsonSubTypes.Type(value = SimulatorState.ConfigurationFilter.class, name = SimulatorState.ConfigurationFilter.FILTER_TYPE)})@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,diff --git a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.javaindex 197ea0720..296d3ef05 100644--- a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java+++ b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java@@ -26,6 +26,8 @@ import org.openremote.model.asset.AssetTreeModifiedEvent;import org.openremote.model.asset.ReadAssetAttributesEvent;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.event.Event;+import org.openremote.model.simulator.RequestSimulatorState;+import org.openremote.model.simulator.SimulatorState;import org.openremote.model.syslog.SyslogEvent;/**@@ -36,7 +38,9 @@ import org.openremote.model.syslog.SyslogEvent;@JsonSubTypes.Type(value = SyslogEvent.class, name = "syslog"),@JsonSubTypes.Type(value = AttributeEvent.class, name = "attribute"),@JsonSubTypes.Type(value = ReadAssetAttributesEvent.class, name = "read-asset-attributes"),- @JsonSubTypes.Type(value = AssetTreeModifiedEvent.class, name = "asset-tree-modified")+ @JsonSubTypes.Type(value = AssetTreeModifiedEvent.class, name = "asset-tree-modified"),+ @JsonSubTypes.Type(value = SimulatorState.class, name = "simulator-state"),+ @JsonSubTypes.Type(value = RequestSimulatorState.class, name = "request-simulator-state")})@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,diff --git a/model/src/main/java/org/openremote/model/simulator/RequestSimulatorState.java b/model/src/main/java/org/openremote/model/simulator/RequestSimulatorState.javanew file mode 100644index 000000000..01882bd98--- /dev/null+++ b/model/src/main/java/org/openremote/model/simulator/RequestSimulatorState.java@@ -0,0 +1,57 @@+/*+ * Copyright 2017, 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.model.simulator;++import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.event.shared.SharedEvent;++import java.util.Arrays;++/**+ * A client sends this event to the server to request {@link SimulatorState}, expecting+ * the server to answer "soon". If the server decides that the client doesn't have the+ * right permissions, or if anything else is not in order (e.g. the protocol configuration+ * doesn't exist), the server might not react at all.+ * <p>+ * If no attribute names and only an asset identifier are provided, all attributes+ * of the asset, accessible by the client, will be read/returned.+ */+public class RequestSimulatorState extends SharedEvent {++ protected AttributeRef[] configurations;++ protected RequestSimulatorState() {+ }++ public RequestSimulatorState(AttributeRef... configurations) {+ this.configurations = configurations;+ }++ public AttributeRef[] getConfigurations() {+ return configurations;+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "simulatorConfigurations=" + Arrays.toString(configurations) ++ '}';+ }+}diff --git a/model/src/main/java/org/openremote/model/simulator/SimulatorElement.java b/model/src/main/java/org/openremote/model/simulator/SimulatorElement.javaindex 0c43a7aab..9c8d0115c 100644--- a/model/src/main/java/org/openremote/model/simulator/SimulatorElement.java+++ b/model/src/main/java/org/openremote/model/simulator/SimulatorElement.java@@ -19,19 +19,44 @@*/package org.openremote.model.simulator;+import com.fasterxml.jackson.annotation.JsonSubTypes;+import com.fasterxml.jackson.annotation.JsonTypeInfo;import org.openremote.model.ValidationFailure;+import org.openremote.model.ValueHolder;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.attribute.AttributeType;+import org.openremote.model.simulator.element.ColorSimulatorElement;+import org.openremote.model.simulator.element.NumberSimulatorElement;+import org.openremote.model.simulator.element.SwitchSimulatorElement;+import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.ObjectValue;import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import java.util.ArrayList;import java.util.List;+import java.util.Optional;-public abstract class SimulatorElement {+@JsonSubTypes({+ // Events used on client and server (serializable)+ @JsonSubTypes.Type(value = NumberSimulatorElement.class, name = NumberSimulatorElement.ELEMENT_NAME),+ @JsonSubTypes.Type(value = SwitchSimulatorElement.class, name = SwitchSimulatorElement.ELEMENT_NAME),+ @JsonSubTypes.Type(value = ColorSimulatorElement.class, name = ColorSimulatorElement.ELEMENT_NAME),+})+@JsonTypeInfo(+ use = JsonTypeInfo.Id.NAME,+ include = JsonTypeInfo.As.PROPERTY,+ property = "elementType"+)+public abstract class SimulatorElement implements ValueHolder {- final protected AttributeRef attributeRef;- final protected AttributeType expectedType;- protected Value value = null;+ public AttributeRef attributeRef;+ public AttributeType expectedType;+ // TODO GWT jackson doesn't like fields with the same name as getters in the hierarchy+ public Value elementValue = null;++ protected SimulatorElement() {+ }public SimulatorElement(AttributeRef attributeRef, AttributeType expectedType) {this.attributeRef = attributeRef;@@ -46,33 +71,84 @@ public abstract class SimulatorElement {return expectedType;}- public Value getValue() {- return value;+ @Override+ public Optional<Value> getValue() {+ return Optional.ofNullable(elementValue);}- public List<ValidationFailure> setValue(Value value) {- List<ValidationFailure> failures = new ArrayList<>();- if (value != null) {- failures.addAll(getValidationFailures(value));- if (failures.isEmpty()) {- this.value = value;- }- } else {- this.value = null;- }- return failures;+ @Override+ public void setValue(Value value) {+ this.elementValue = value;+ }++ @Override+ public void clearValue() {+ this.elementValue = null;+ }++ @Override+ public Optional<String> getValueAsString() {+ return Values.getString(elementValue);+ }++ @Override+ public Optional<Double> getValueAsNumber() {+ return Values.getNumber(elementValue);+ }++ @Override+ public Optional<Integer> getValueAsInteger() {+ return Values.getNumber(elementValue).map(Double::intValue);+ }++ @Override+ public Optional<Boolean> getValueAsBoolean() {+ return Values.getBoolean(elementValue);+ }++ @Override+ public Optional<ObjectValue> getValueAsObject() {+ return Values.getObject(elementValue);}- protected List<ValidationFailure> getValidationFailures(Value value) {+ @Override+ public Optional<ArrayValue> getValueAsArray() {+ return Values.getArray(elementValue);+ }++ @Override+ public void setValue(Value... values) {+ this.elementValue = Values.createArray().addAll(values);+ }++ @Override+ public void setValue(String string) {+ this.elementValue = Values.create(string);+ }++ @Override+ public void setValue(Double number) {+ this.elementValue = Values.create(number);+ }++ @Override+ public void setValue(Boolean b) {+ this.elementValue = Values.create(b);+ }++ @Override+ public List<ValidationFailure> getValidationFailures() {List<ValidationFailure> failures = new ArrayList<>();- expectedType.isValidValue(value).ifPresent(failures::add);+ if (elementValue != null) {+ expectedType.isValidValue(elementValue).ifPresent(failures::add);+ }return failures;}@Overridepublic String toString() {return getClass().getSimpleName() + "{" +- "value=" + (getValue() != null ? getValue().toJson() : "null") ++ "value=" + elementValue +"}";}}diff --git a/model/src/main/java/org/openremote/model/simulator/SimulatorState.java b/model/src/main/java/org/openremote/model/simulator/SimulatorState.javaindex 5786ea542..5b3304190 100644--- a/model/src/main/java/org/openremote/model/simulator/SimulatorState.java+++ b/model/src/main/java/org/openremote/model/simulator/SimulatorState.java@@ -20,68 +20,97 @@package org.openremote.model.simulator;import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.event.shared.EventFilter;+import org.openremote.model.event.shared.SharedEvent;+import java.util.Arrays;import java.util.HashMap;import java.util.Map;+import java.util.function.Consumer;-public class SimulatorState {+/**+ * A snapshot of {@link SimulatorElement}s and their values.+ */+public class SimulatorState extends SharedEvent {++ public static class ConfigurationFilter extends EventFilter<SimulatorState> {- public class SimulatedAssetAttribute {+ public static final String FILTER_TYPE = "simulator-state-configuration";- final protected String assetName;- final protected String attributeName;+ protected AttributeRef[] configurations;- public SimulatedAssetAttribute(String assetName, String attributeName) {- this.assetName = assetName;- this.attributeName = attributeName;+ public ConfigurationFilter() {}- public String getAssetName() {- return assetName;+ public ConfigurationFilter(AttributeRef... configurations) {+ this.configurations = configurations;}- public String getAttributeName() {- return attributeName;+ public AttributeRef[] getConfigurations() {+ return configurations;}@Override- public boolean equals(Object o) {- if (this == o) return true;- if (o == null || getClass() != o.getClass()) return false;-- SimulatedAssetAttribute that = (SimulatedAssetAttribute) o;+ public String getFilterType() {+ return FILTER_TYPE;+ }- if (!assetName.equals(that.assetName)) return false;- return attributeName.equals(that.attributeName);+ @Override+ public boolean apply(SimulatorState event) {+ return event.getProtocolConfigurationRef() != null+ && Arrays.asList(getConfigurations()).contains(event.getProtocolConfigurationRef());}@Override- public int hashCode() {- int result = assetName.hashCode();- result = 31 * result + attributeName.hashCode();- return result;+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "configurations='" + Arrays.toString(configurations) + '\'' ++ '}';}}- protected Map<AttributeRef, SimulatedAssetAttribute> attributeDetails = new HashMap<>();+ // This map can be populated to complete the simulator state with user-friendly names for each simulated AttributeRef+ protected Map<String, String> assetIdAndName = new HashMap<>();++ protected AttributeRef protocolConfigurationRef;protected SimulatorElement[] elements = new SimulatorElement[0];protected SimulatorState() {}- public SimulatorState(SimulatorElement... elements) {+ public SimulatorState(AttributeRef protocolConfigurationRef, SimulatorElement... elements) {+ this.protocolConfigurationRef = protocolConfigurationRef;this.elements = elements;}+ public AttributeRef getProtocolConfigurationRef() {+ return protocolConfigurationRef;+ }+public SimulatorElement[] getElements() {return elements;}- public void setAttributeDetails(Map<AttributeRef, SimulatedAssetAttribute> attributeDetails) {- this.attributeDetails = attributeDetails;+ public void updateAssetNames(Consumer<Map<String, String>> updater) {+ clearAssetNames();+ for (SimulatorElement element : elements) {+ assetIdAndName.put(element.getAttributeRef().getEntityId(), null);+ }+ updater.accept(assetIdAndName);+ }++ public void clearAssetNames() {+ this.assetIdAndName.clear();}- public void clearAttributeDetails() {- this.attributeDetails.clear();+ public Map<String, String> getAssetIdAndName() {+ return assetIdAndName;}++ public String getElementName(SimulatorElement element) {+ AttributeRef ref = element.getAttributeRef();+ return (assetIdAndName.containsKey(ref.getEntityId()) ? assetIdAndName.get(ref.getEntityId()) : ref.getEntityId())+ + ":" + ref.getAttributeName();+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/simulator/element/ColorSimulatorElement.java b/model/src/main/java/org/openremote/model/simulator/element/ColorSimulatorElement.javasimilarity index 92%rename from agent/src/main/java/org/openremote/agent/protocol/simulator/element/ColorSimulatorElement.javarename to model/src/main/java/org/openremote/model/simulator/element/ColorSimulatorElement.javaindex 71da6cbb3..9779820d8 100644--- a/agent/src/main/java/org/openremote/agent/protocol/simulator/element/ColorSimulatorElement.java+++ b/model/src/main/java/org/openremote/model/simulator/element/ColorSimulatorElement.java@@ -17,7 +17,7 @@* You should have received a copy of the GNU Affero General Public License* along with this program. If not, see <http://www.gnu.org/licenses/>.*/-package org.openremote.agent.protocol.simulator.element;+package org.openremote.model.simulator.element;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.attribute.AttributeType;@@ -27,6 +27,9 @@ public class ColorSimulatorElement extends SimulatorElement {public static final String ELEMENT_NAME = "color";+ protected ColorSimulatorElement() {+ }+public ColorSimulatorElement(AttributeRef attributeRef) {super(attributeRef, AttributeType.COLOR_RGB);}diff --git a/agent/src/main/java/org/openremote/agent/protocol/simulator/element/NumberSimulatorElement.java b/model/src/main/java/org/openremote/model/simulator/element/NumberSimulatorElement.javasimilarity index 77%rename from agent/src/main/java/org/openremote/agent/protocol/simulator/element/NumberSimulatorElement.javarename to model/src/main/java/org/openremote/model/simulator/element/NumberSimulatorElement.javaindex 13d5f536b..80874e71c 100644--- a/agent/src/main/java/org/openremote/agent/protocol/simulator/element/NumberSimulatorElement.java+++ b/model/src/main/java/org/openremote/model/simulator/element/NumberSimulatorElement.java@@ -17,13 +17,12 @@* You should have received a copy of the GNU Affero General Public License* along with this program. If not, see <http://www.gnu.org/licenses/>.*/-package org.openremote.agent.protocol.simulator.element;+package org.openremote.model.simulator.element;import org.openremote.model.ValidationFailure;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.attribute.AttributeType;import org.openremote.model.simulator.SimulatorElement;-import org.openremote.model.value.Value;import org.openremote.model.value.Values;import java.util.List;@@ -37,8 +36,11 @@ public class NumberSimulatorElement extends SimulatorElement {public static final String ELEMENT_NAME = "number";public static final String ELEMENT_NAME_RANGE = "range";- final protected Integer min;- final protected Integer max;+ protected Integer min;+ protected Integer max;++ protected NumberSimulatorElement() {+ }public NumberSimulatorElement(AttributeRef attributeRef) {this(attributeRef, null, null);@@ -59,11 +61,13 @@ public class NumberSimulatorElement extends SimulatorElement {}@Override- protected List<ValidationFailure> getValidationFailures(Value value) {- List<ValidationFailure> failures = super.getValidationFailures(value);- if ((getMin() != null && Values.getNumber(value).filter(v -> v < getMin()).isPresent())- && (getMax() != null && Values.getNumber(value).filter(v -> v > getMax()).isPresent())) {- failures.add(ValueValidationFailure.NUMBER_OUT_OF_RANGE);+ public List<ValidationFailure> getValidationFailures() {+ List<ValidationFailure> failures = super.getValidationFailures();+ if (elementValue != null) {+ if ((getMin() != null && Values.getNumber(elementValue).filter(v -> v < getMin()).isPresent())+ && (getMax() != null && Values.getNumber(elementValue).filter(v -> v > getMax()).isPresent())) {+ failures.add(ValueValidationFailure.NUMBER_OUT_OF_RANGE);+ }}return failures;}diff --git a/agent/src/main/java/org/openremote/agent/protocol/simulator/element/SwitchSimulatorElement.java b/model/src/main/java/org/openremote/model/simulator/element/SwitchSimulatorElement.javasimilarity index 92%rename from agent/src/main/java/org/openremote/agent/protocol/simulator/element/SwitchSimulatorElement.javarename to model/src/main/java/org/openremote/model/simulator/element/SwitchSimulatorElement.javaindex 23fcb0902..91c89e539 100644--- a/agent/src/main/java/org/openremote/agent/protocol/simulator/element/SwitchSimulatorElement.java+++ b/model/src/main/java/org/openremote/model/simulator/element/SwitchSimulatorElement.java@@ -17,7 +17,7 @@* You should have received a copy of the GNU Affero General Public License* along with this program. If not, see <http://www.gnu.org/licenses/>.*/-package org.openremote.agent.protocol.simulator.element;+package org.openremote.model.simulator.element;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.attribute.AttributeType;@@ -27,6 +27,9 @@ public class SwitchSimulatorElement extends SimulatorElement {public static final String ELEMENT_NAME = "switch";+ protected SwitchSimulatorElement() {+ }+public SwitchSimulatorElement(AttributeRef attributeRef) {super(attributeRef, AttributeType.BOOLEAN);}