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 Replay mode for SimulatorProtocol in order to fill values through json
Michael Rademaker98d76ec2960c
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 a0c6e218b..daa57d663 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@@ -19,6 +19,7 @@*/package org.openremote.agent.protocol.simulator;+import com.fasterxml.jackson.core.JsonProcessingException;import org.openremote.agent.protocol.AbstractProtocol;import org.openremote.model.AbstractValueHolder;import org.openremote.model.ValidationFailure;@@ -29,13 +30,22 @@ import org.openremote.model.simulator.SimulatorElement;import org.openremote.model.simulator.SimulatorState;import org.openremote.model.simulator.element.ColorSimulatorElement;import org.openremote.model.simulator.element.NumberSimulatorElement;+import org.openremote.model.simulator.element.ReplaySimulatorElement;import org.openremote.model.simulator.element.SwitchSimulatorElement;import org.openremote.model.syslog.SyslogCategory;+import org.openremote.model.value.ArrayValue;import org.openremote.model.value.Value;import org.openremote.model.value.ValueType;+import java.time.Duration;+import java.time.LocalDateTime;+import java.time.LocalTime;+import java.time.temporal.ChronoField;import java.util.*;+import java.util.concurrent.ScheduledFuture;+import java.util.concurrent.TimeUnit;import java.util.function.Consumer;+import java.util.logging.Level;import java.util.logging.Logger;import java.util.stream.Collectors;@@ -67,7 +77,12 @@ public class SimulatorProtocol extends AbstractProtocol {/*** Producer of send to actuator will have to manually update the sensor by calling {@link #updateSensor)}.*/- MANUAL+ MANUAL,++ /**+ * Will supply value(s) based on the timestamp in the ArrayValue found in {@link #REPLAY_ATTRIBUTE_LINK_DATA}+ */+ REPLAY}/**@@ -120,11 +135,14 @@ public class SimulatorProtocol extends AbstractProtocol {*/public static final String CONFIG_WRITE_DELAY_MILLISECONDS = PROTOCOL_NAME + ":delayMilliseconds";+ public static final String REPLAY_ATTRIBUTE_LINK_DATA = PROTOCOL_NAME + ":replayAttributeLinkData";+protected static final String VERSION = "1.0";final protected Map<AttributeRef, Instance> instances = new HashMap<>();final protected Map<AttributeRef, AttributeRef> attributeInstanceMap = new HashMap<>();final protected Map<AttributeRef, SimulatorElement> elements = new HashMap<>();+ protected final Map<AttributeRef, ScheduledFuture> replayMap = new HashMap<>();protected static final List<MetaItemDescriptor> PROTOCOL_META_ITEM_DESCRIPTORS = Arrays.asList(new MetaItemDescriptorImpl(@@ -144,6 +162,15 @@ public class SimulatorProtocol extends AbstractProtocol {MetaItemDescriptor.PatternFailure.INTEGER_POSITIVE.name(),null,null,+ false, null, null, null),+ new MetaItemDescriptorImpl(+ REPLAY_ATTRIBUTE_LINK_DATA,+ ValueType.ARRAY,+ false,+ null,+ null,+ null,+ null,false, null, null, null));@@ -251,7 +278,21 @@ public class SimulatorProtocol extends AbstractProtocol {LOG.warning("Can't simulate element '" + elementType + "': " + attribute);return;}- if (attribute.getValue().isPresent()) {++ if (elementType.get().equals(ReplaySimulatorElement.ELEMENT_NAME)) {+ ReplaySimulatorElement replaySimulatorElement = (ReplaySimulatorElement) element;+ ArrayValue link = attribute.getMetaItem(REPLAY_ATTRIBUTE_LINK_DATA)+ .flatMap(AbstractValueHolder::getValueAsArray)+ .orElseThrow(() -> new IllegalArgumentException("CONTINUES_ATTRIBUTE_LINK should be of value type ARRAY"));+ element.setValue(link);+ ScheduledFuture updateValueFuture = scheduleReplay(attributeRef, replaySimulatorElement);+ if (updateValueFuture != null) {+ replayMap.put(attributeRef, updateValueFuture);+ } else {+ LOG.warning("Failed to schedule update value for continues simulator element: " + attribute);+ return;+ }+ } else if (attribute.getValue().isPresent()) {element.setValue(attribute.getValue().get());List<ValidationFailure> failures = element.getValidationFailures();if (!failures.isEmpty()) {@@ -272,6 +313,10 @@ public class SimulatorProtocol extends AbstractProtocol {AttributeRef attributeRef = attribute.getReferenceOrThrow();elements.remove(attributeRef);attributeInstanceMap.remove(attributeRef);+ ScheduledFuture updateValueFuture = replayMap.remove(attributeRef);+ if (updateValueFuture != null) {+ updateValueFuture.cancel(true);+ }}@Override@@ -497,11 +542,35 @@ public class SimulatorProtocol extends AbstractProtocol {return new NumberSimulatorElement(attribute.getReferenceOrThrow(), min, max);case ColorSimulatorElement.ELEMENT_NAME:return new ColorSimulatorElement(attribute.getReferenceOrThrow());+ case ReplaySimulatorElement.ELEMENT_NAME:+ return new ReplaySimulatorElement(attribute.getReferenceOrThrow());default:return null;}}+ protected ScheduledFuture scheduleReplay(AttributeRef attributeRef, ReplaySimulatorElement replaySimulatorElement) {+ LOG.fine("Scheduling value update");+ try {+ LocalDateTime now = LocalDateTime.now();+ ReplaySimulatorElement.ReplaySimulatorDatapoint nextDatapoint = replaySimulatorElement.getNextDatapoint(now.get(ChronoField.SECOND_OF_DAY));+ LocalDateTime nextRun = LocalDateTime.of(now.toLocalDate(), LocalTime.ofSecondOfDay(nextDatapoint.timestamp));++ if (now.isAfter(nextRun)) { //now is after so nextRun is next day+ nextRun = nextRun.plusDays(1);+ }+ Duration duration = Duration.between(now, nextRun);++ return executorService.schedule(() -> {+ updateLinkedAttribute(new AttributeState(attributeRef, nextDatapoint.value));+ replayMap.put(attributeRef, scheduleReplay(attributeRef, replaySimulatorElement));+ }, duration.getSeconds(), TimeUnit.SECONDS);+ } catch (JsonProcessingException e) {+ LOG.log(Level.SEVERE, "Exception thrown when scheduling value update: %s", e);+ return null;+ }+ }+public static Optional<String> getElementType(AssetAttribute attribute) {returnattribute.getMetaItem(SIMULATOR_ELEMENT)diff --git a/model/src/main/java/org/openremote/model/simulator/SimulatorElement.java b/model/src/main/java/org/openremote/model/simulator/SimulatorElement.javaindex 56e2d7a00..7fd780a81 100644--- a/model/src/main/java/org/openremote/model/simulator/SimulatorElement.java+++ b/model/src/main/java/org/openremote/model/simulator/SimulatorElement.java@@ -27,8 +27,8 @@ import org.openremote.model.ValidationFailure;import org.openremote.model.ValueHolder;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.attribute.AttributeValueDescriptor;-import org.openremote.model.attribute.AttributeValueType;import org.openremote.model.simulator.element.ColorSimulatorElement;+import org.openremote.model.simulator.element.ReplaySimulatorElement;import org.openremote.model.simulator.element.NumberSimulatorElement;import org.openremote.model.simulator.element.SwitchSimulatorElement;import org.openremote.model.value.ArrayValue;@@ -45,6 +45,7 @@ import java.util.Optional;@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),+ @JsonSubTypes.Type(value = ReplaySimulatorElement.class, name = ReplaySimulatorElement.ELEMENT_NAME),})@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,@@ -60,7 +61,7 @@ public abstract class SimulatorElement implements ValueHolder {protected SimulatorElement() {}- public SimulatorElement(AttributeRef attributeRef, AttributeValueType expectedType) {+ public SimulatorElement(AttributeRef attributeRef, AttributeValueDescriptor expectedType) {this.attributeRef = attributeRef;this.expectedType = expectedType;}diff --git a/model/src/main/java/org/openremote/model/simulator/element/ReplaySimulatorElement.java b/model/src/main/java/org/openremote/model/simulator/element/ReplaySimulatorElement.javanew file mode 100644index 000000000..3d1e87307--- /dev/null+++ b/model/src/main/java/org/openremote/model/simulator/element/ReplaySimulatorElement.java@@ -0,0 +1,60 @@+/*+ * 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.element;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.ObjectMapper;+import org.openremote.model.ModelModule;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeValueType;+import org.openremote.model.simulator.SimulatorElement;+import org.openremote.model.value.Value;++import java.util.Arrays;++public class ReplaySimulatorElement extends SimulatorElement {++ public static final String ELEMENT_NAME = "replay";++ public ReplaySimulatorElement() {+ }++ public ReplaySimulatorElement(AttributeRef attributeRef) {+ super(attributeRef, AttributeValueType.ARRAY);+ }++ public ReplaySimulatorDatapoint getNextDatapoint(long millis) throws JsonProcessingException {+ ReplaySimulatorDatapoint[] datapoints = new ObjectMapper().registerModule(new ModelModule()).readValue(elementValue.toJson(), ReplaySimulatorDatapoint[].class);+ return Arrays.stream(datapoints).filter(replaySimulatorDatapoint -> replaySimulatorDatapoint.timestamp >= millis).findFirst().orElse(datapoints[0]);+ }++ public ReplaySimulatorDatapoint[] getDatapoints() throws JsonProcessingException {+ return new ObjectMapper().readValue(elementValue.toJson(), ReplaySimulatorDatapoint[].class);+ }++ public static class ReplaySimulatorDatapoint {++ /**+ * In seconds+ */+ public long timestamp;+ public Value value;+ }+}