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
Always add a schedule to the simulator agent (#2572)
Koen4c3b04c86b1c
diff --git a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgentLink.javaindex 5411939cc..00459fee4 100644--- a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgentLink.java+++ b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgentLink.java@@ -19,10 +19,16 @@*/package org.openremote.agent.protocol.simulator;+import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonProperty;import org.openremote.model.asset.agent.AgentLink;import org.openremote.model.simulator.SimulatorReplayDatapoint;import org.openremote.model.util.JSONSchemaUtil.*;+import java.time.LocalDate;+import java.time.LocalDateTime;+import java.time.ZoneId;+import java.util.Arrays;import java.util.Optional;import java.util.TimeZone;@@ -35,10 +41,6 @@ public class SimulatorAgentLink extends AgentLink<SimulatorAgentLink> {" immediately as determined by the schedule. Datapoints scheduled after the replay loop are ignored.")protected SimulatorReplayDatapoint[] replayData;- @JsonSchemaDescription("The timezone the Simulator should follow to replay the dataset.")- @JsonSchemaFormat("timezone")- protected TimeZone timezone;-@JsonSchemaTitle("Schedule")@JsonSchemaDescription("Overwrites the possible dataset length and when it is replayed." +" The dataset can be scheduled to stop based on the UNTIL rule part" +@@ -49,12 +51,37 @@ public class SimulatorAgentLink extends AgentLink<SimulatorAgentLink> {@JsonSchemaFormat("simulator-schedule")protected SimulatorProtocol.Schedule schedule;+ @JsonSchemaDescription("The timezone the Simulator should follow to replay the dataset.")+ @JsonSchemaFormat("timezone")+ protected TimeZone timezone;+// For Hydratorsprotected SimulatorAgentLink() {}public SimulatorAgentLink(String id) {+ this(id, null, null, null);+ }++ @JsonCreator+ public SimulatorAgentLink(+ @JsonProperty("id") String id,+ @JsonProperty("replayData") SimulatorReplayDatapoint[] replayData,+ @JsonProperty("schedule") SimulatorProtocol.Schedule schedule,+ @JsonProperty("timezone") TimeZone timezone+ ){super(id);++ this.replayData = replayData;+ this.schedule = schedule;+ this.timezone = timezone;++ if (schedule == null) {+ LocalDateTime start = LocalDate.now(ZoneId.of("UTC")).atStartOfDay();+ LocalDateTime end = getReplayData()+ .flatMap(this::getLastReplayDatapointSeconds).map(start::plusSeconds).orElse(start.plusDays(1));+ this.schedule = new SimulatorProtocol.Schedule(start, end, null);+ }}public Optional<SimulatorReplayDatapoint[]> getReplayData() {@@ -66,8 +93,8 @@ public class SimulatorAgentLink extends AgentLink<SimulatorAgentLink> {return this;}- public Optional<SimulatorProtocol.Schedule> getSchedule() {- return Optional.ofNullable(schedule);+ public SimulatorProtocol.Schedule getSchedule() {+ return schedule;}public SimulatorAgentLink setSchedule(SimulatorProtocol.Schedule schedule) {@@ -83,4 +110,16 @@ public class SimulatorAgentLink extends AgentLink<SimulatorAgentLink> {this.timezone = timezone;return this;}++ /**+ * Resolves the timestamp seconds of the last (max) {@link SimulatorReplayDatapoint}.+ * @param rd The {@link SimulatorReplayDatapoint}s to find the latest timestamp of.+ * @return The last (max) {@link SimulatorReplayDatapoint#timestamp} seconds.+ * If the resolved time is 0 an empty value is returned instead.+ */+ private Optional<Long> getLastReplayDatapointSeconds(SimulatorReplayDatapoint[] rd) {+ long time = Arrays.stream(rd).map(d -> d.timestamp).reduce(0L, Long::max);+ if (time == 0) return Optional.empty();+ return Optional.of(time);+ }}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 b36a168f9..f62ea4275 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@@ -59,7 +59,6 @@ import static org.openremote.model.value.MetaItemType.HAS_PREDICTED_DATA_POINTS;public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, SimulatorAgentLink> {- private static final long DEFAULT_REPLAY_LOOP_DURATION = 86400_000;private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, SimulatorProtocol.class);public static final String PROTOCOL_DISPLAY_NAME = "Simulator";@@ -106,8 +105,7 @@ public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, SimulatoAttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());predictedDatapointWindowMap.put(attributeRef, PredictedDatapointWindow.BOTH);- Long duration = this.agent.getAgentLink(attribute).getSchedule()- .flatMap(Schedule::calculateDuration).orElse(null);+ Long duration = this.agent.getAgentLink(attribute).getSchedule().calculateDuration().orElse(null);// Sorting so we can assume positioningSimulatorReplayDatapoint[] sorted = Arrays.stream(simulatorReplayDatapoints)@@ -189,15 +187,14 @@ public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, SimulatoLOG.finest("Scheduling linked attribute replay update");- Optional<Schedule> schedule = agentLink.getSchedule();+ Schedule schedule = agentLink.getSchedule();TimeZone timezone = agentLink.getTimezone().orElse(TimeZone.getTimeZone("UTC"));long nowUTC = timerService.getNow().toEpochMilli(); // UTClong tzOffset = timezone.getOffset(nowUTC);long now = nowUTC + tzOffset;- long timeSinceOccurrenceStart = schedule.map(s -> now - s.tryAdvanceActive(now, tzOffset))- .orElse(now % DEFAULT_REPLAY_LOOP_DURATION); // Remainder since 00:00+ long timeSinceOccurrenceStart = now - schedule.tryAdvanceActive(now, tzOffset);// Find datapoint with timestamp after the current occurrenceSimulatorReplayDatapoint nextDatapoint = Arrays.stream(simulatorReplayDatapoints)@@ -210,8 +207,8 @@ public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, Simulatoreturn null;}- OptionalLong nextRun = Schedule.getDelay(nextDatapoint.timestamp, timeSinceOccurrenceStart, schedule.orElse(null));- if (nextRun.isEmpty() || nextRun.getAsLong() < 0 || (schedule.isPresent() && schedule.get().isAfterScheduleEnd(now))) {+ OptionalLong nextRun = schedule.getDelay(nextDatapoint.timestamp, timeSinceOccurrenceStart);+ if (nextRun.isEmpty() || nextRun.getAsLong() < 0 || schedule.isAfterScheduleEnd(now)) {LOG.warning("Replay loop has ended for: " + attributeRef);predictedDatapointService.purgeValuesBefore(attributeRef.getId(), attributeRef.getName(), Instant.ofEpochMilli(now));return null;@@ -258,7 +255,7 @@ public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, Simulatopublic List<ValueDatapoint<?>> calculatePredictedDatapoints(SimulatorReplayDatapoint[] simulatorReplayDatapoints,- Optional<Schedule> schedule,+ Schedule schedule,PredictedDatapointWindow status,long timeSinceOccurrenceStart,long now,@@ -266,17 +263,13 @@ public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, Simulato) {List<ValueDatapoint<?>> predictedDatapoints = new ArrayList<>();- if (status.equals(PredictedDatapointWindow.NONE)) {- return predictedDatapoints;- }-- if (!schedule.map(Schedule::hasCurrent).orElse(true)) {+ if (status.equals(PredictedDatapointWindow.NONE) || !schedule.hasCurrent()) {return predictedDatapoints;}if (status.equals(PredictedDatapointWindow.BOTH)) {for (SimulatorReplayDatapoint datapoint : simulatorReplayDatapoints) {- OptionalLong delay = Schedule.getDelay(datapoint.timestamp, timeSinceOccurrenceStart, schedule.orElse(null));+ OptionalLong delay = schedule.getDelay(datapoint.timestamp, timeSinceOccurrenceStart);if (delay.isEmpty()) {return predictedDatapoints;}@@ -284,11 +277,11 @@ public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, Simulatoif (timestamp > now) { // Delay can be negative// If the predicted datapoint rolls past the current occurrence skip it// This happens when the offset is less than the time since the occurrence started- if (timeSinceOccurrenceStart >= 0 && schedule.isPresent() && schedule.get().isAfterUpcoming(timestamp)) {+ if (timeSinceOccurrenceStart >= 0 && schedule.isAfterUpcoming(timestamp)) {continue;}// Return remaining predictions if single occurrence or recurrence end has been surpassed- if (schedule.isPresent() && schedule.get().isAfterScheduleEnd(timestamp)) {+ if (schedule.isAfterScheduleEnd(timestamp)) {return predictedDatapoints;}long UTCTimestamp = timestamp - tzOffset;@@ -298,26 +291,21 @@ public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, Simulato}// Single occurrence schedule can't have a next window- if (schedule.map(Schedule::isSingleOccurrence).orElse(false)) {- return predictedDatapoints;- }- // If a recurrence is already ongoing and is meant to end immediately- if (!schedule.map(Schedule::hasUpcoming).orElse(true)) {+ // Or a recurrence is already ongoing and is meant to end immediately+ if (schedule.isSingleOccurrence() || !schedule.hasUpcoming()) {return predictedDatapoints;}if (status.equals(PredictedDatapointWindow.BOTH) || status.equals(PredictedDatapointWindow.NEXT)) {for (SimulatorReplayDatapoint datapoint : simulatorReplayDatapoints) {- long timeSinceUpcoming = schedule- .map(s -> now - s.upcoming.toInstant(ZoneOffset.UTC).toEpochMilli())- .orElse(timeSinceOccurrenceStart - DEFAULT_REPLAY_LOOP_DURATION);+ long timeSinceUpcoming = now - schedule.upcoming.toInstant(ZoneOffset.UTC).toEpochMilli();- OptionalLong delay = Schedule.getDelay(datapoint.timestamp, timeSinceUpcoming, schedule.orElse(null));+ OptionalLong delay = schedule.getDelay(datapoint.timestamp, timeSinceUpcoming);if (delay.isEmpty()) {continue;}long timestamp = now + delay.getAsLong();- if (schedule.isPresent() && schedule.get().isAfterScheduleEnd(timestamp)) {+ if (schedule.isAfterScheduleEnd(timestamp)) {return predictedDatapoints;}long UTCTimestamp = timestamp - tzOffset;@@ -479,18 +467,18 @@ public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, Simulato}/**- * Calculates the remaining offset delay in milliseconds relative to the current time.+ * Calculates the remaining datapoint offset delay in milliseconds relative to the current time.*- * @param offset The offset from the current occurrence in seconds.+ * @param offset The datapoint offset in seconds.* @param timeSinceOccurrenceStart The time since the occurrence started in milliseconds.- * @return The remaining offset delay in milliseconds relative to the current time.+ * @return The remaining datapoint offset delay in milliseconds relative to the current time.* <p>- * If the recurrence rule has ended returns {@code null} instead.+ * If the recurrence rule has ended returns {@link OptionalLong#empty()} instead.*/- public static OptionalLong getDelay(long offset, long timeSinceOccurrenceStart, Schedule schedule) {+ public OptionalLong getDelay(long offset, long timeSinceOccurrenceStart) {long offsetInMillis = offset * 1000;if (offsetInMillis <= timeSinceOccurrenceStart) {- return getTimeUntilNextOccurrence(timeSinceOccurrenceStart, schedule)+ return this.getTimeUntilNextOccurrence(timeSinceOccurrenceStart).stream().map(n -> offsetInMillis + n).findFirst();@@ -500,26 +488,21 @@ public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, Simulato/*** Calculates the time in milliseconds until the next occurrence starts.- * <p>- * If no schedule has been defined uses the default 1-day schedule.** @param timeSinceOccurrenceStart The time since the occurrence started in milliseconds.* @return The delay in milliseconds until the next occurrence.* <p>- * If the recurrence rule has ended returns {@code null} instead.+ * If the recurrence rule has ended returns {@link OptionalLong#empty()} instead.*/- public static OptionalLong getTimeUntilNextOccurrence(long timeSinceOccurrenceStart, Schedule schedule) {- if (schedule != null) {- if (schedule.recurrence != null) {- if (schedule.current == null || schedule.upcoming == null) {- return OptionalLong.empty();- }- long duration = schedule.upcoming.toEpochSecond(ZoneOffset.UTC) - schedule.current.toEpochSecond(ZoneOffset.UTC);- return OptionalLong.of(duration*1000 - timeSinceOccurrenceStart);+ public OptionalLong getTimeUntilNextOccurrence(long timeSinceOccurrenceStart) {+ if (recurrence != null) {+ if (current == null || upcoming == null) {+ return OptionalLong.empty();}- return OptionalLong.of(-timeSinceOccurrenceStart);+ long duration = upcoming.toEpochSecond(ZoneOffset.UTC) - current.toEpochSecond(ZoneOffset.UTC);+ return OptionalLong.of(duration*1000 - timeSinceOccurrenceStart);}- return OptionalLong.of(DEFAULT_REPLAY_LOOP_DURATION - timeSinceOccurrenceStart);+ return OptionalLong.of(-timeSinceOccurrenceStart);}public boolean hasCurrent() {@@ -553,5 +536,14 @@ public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, Simulato}return false;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "start='" + start + '\'' ++ ", end='" + end + '\'' ++ ", recurrence='" + recurrence + '\'' ++ "}";+ }}}diff --git a/agent/src/test/java/org/openremote/agent/protocol/simulator/SimulatorAgentProtocolScheduleTest.java b/agent/src/test/java/org/openremote/agent/protocol/simulator/SimulatorAgentProtocolScheduleTest.javaindex 512c8287a..18f398290 100644--- a/agent/src/test/java/org/openremote/agent/protocol/simulator/SimulatorAgentProtocolScheduleTest.java+++ b/agent/src/test/java/org/openremote/agent/protocol/simulator/SimulatorAgentProtocolScheduleTest.java@@ -172,15 +172,15 @@ public class SimulatorAgentProtocolScheduleTest {long now = start.toEpochMilli();long timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(100 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(100 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T00:01:39.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T00:01:40.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(3600 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(3600 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());}@Test@@ -190,15 +190,15 @@ public class SimulatorAgentProtocolScheduleTest {long now = Instant.parse("2000-01-01T00:00:00.000Z").toEpochMilli();long timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(DAY + 100 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(DAY + 100 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T00:01:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(DAY + 40 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(DAY + 40 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T00:02:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(DAY - 20 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(DAY - 20 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());}@Test@@ -208,35 +208,35 @@ public class SimulatorAgentProtocolScheduleTest {long now = Instant.parse("2000-01-01T00:00:00.000Z").toEpochMilli();long timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(100 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(100 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T00:01:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(40 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(40 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T00:02:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(3580 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(3580 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T01:00:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(100 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(100 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T01:01:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(40 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(40 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T01:02:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(3580 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(3580 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T02:00:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(100 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(100 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T02:01:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(40 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(40 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());// UNTIL will continue to return positive delays if now < UNTIL + offset, so we use another check to end itassertTrue(schedule.isAfterScheduleEnd(Instant.parse("2000-01-01T03:00:00.001Z").toEpochMilli())); // TODO: fix@@ -244,11 +244,11 @@ public class SimulatorAgentProtocolScheduleTest {// The datapoint won't be replayed after the 3rd occurrence so the delay is negativenow = Instant.parse("2000-01-01T02:02:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(-20 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(-20 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T03:00:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(-3500 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(-3500 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());}@@ -259,44 +259,44 @@ public class SimulatorAgentProtocolScheduleTest {long now = Instant.parse("2000-01-01T00:00:00.000Z").toEpochMilli();long timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(100 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(100 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T00:01:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(40 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(40 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T00:02:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(3580 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(3580 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T01:00:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(100 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(100 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T01:01:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(40 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(40 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T01:02:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(3580 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(3580 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T02:00:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(100 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(100 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T02:01:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(40 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(40 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());// The datapoint won't be replayed after the 3rd occurrence so the delay is negativenow = Instant.parse("2000-01-01T02:02:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(-20 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(-20 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());now = Instant.parse("2000-01-01T03:00:00.000Z").toEpochMilli();timeSinceOccurrenceStarted = now - schedule.tryAdvanceActive(now, 0);- assertEquals(-3500 * SECOND, SimulatorProtocol.Schedule.getDelay(100, timeSinceOccurrenceStarted, schedule).getAsLong());+ assertEquals(-3500 * SECOND, schedule.getDelay(100, timeSinceOccurrenceStarted).getAsLong());}}}diff --git a/extension/demo-setup/src/main/java/org/openremote/extension/demosetup/ManagerDemoSetup.java b/extension/demo-setup/src/main/java/org/openremote/extension/demosetup/ManagerDemoSetup.javaindex ec88bfcef..a395c049b 100644--- a/extension/demo-setup/src/main/java/org/openremote/extension/demosetup/ManagerDemoSetup.java+++ b/extension/demo-setup/src/main/java/org/openremote/extension/demosetup/ManagerDemoSetup.java@@ -23,6 +23,7 @@ import org.openremote.agent.protocol.http.HTTPAgent;import org.openremote.agent.protocol.http.HTTPAgentLink;import org.openremote.agent.protocol.simulator.SimulatorAgent;import org.openremote.agent.protocol.simulator.SimulatorAgentLink;+import org.openremote.agent.protocol.simulator.SimulatorProtocol;import org.openremote.extension.demosetup.model.HarvestRobotAsset;import org.openremote.extension.demosetup.model.HarvestRobotAsset.OperationMode;import org.openremote.extension.demosetup.model.HarvestRobotAsset.VegetableType;@@ -96,6 +97,10 @@ public class ManagerDemoSetup extends ManagerSetup {super(container);}+ private static SimulatorProtocol.Schedule createDailySchedule() {+ return new SimulatorProtocol.Schedule(null, null, "FREQ=DAILY");+ }+private static int getRandomNumberInRange(int min, int max) {if (min >= max) {throw new IllegalArgumentException("max must be greater than min");@@ -245,7 +250,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 23),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 21),@@ -286,7 +291,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 0),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 0),@@ -351,7 +356,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 7),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 8),@@ -390,7 +395,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 0),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 0),@@ -454,7 +459,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 0),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 0),@@ -501,7 +506,7 @@ public class ManagerDemoSetup extends ManagerSetup {charger1Asset.getAttributes().getOrCreate(ElectricityChargerAsset.POWER).addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 0),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 0),@@ -542,7 +547,7 @@ public class ManagerDemoSetup extends ManagerSetup {.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 5),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 0),@@ -583,7 +588,7 @@ public class ManagerDemoSetup extends ManagerSetup {.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 0),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 0),@@ -624,7 +629,7 @@ public class ManagerDemoSetup extends ManagerSetup {.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 3),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 0),@@ -679,7 +684,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 6),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 5),@@ -732,7 +737,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 16),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 16),@@ -771,7 +776,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 0),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 0),@@ -906,7 +911,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), getRandomNumberInRange(80,90)),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), getRandomNumberInRange(75,90)),@@ -953,7 +958,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 12.2),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 12.1),@@ -988,7 +993,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), getRandomNumberInRange(110, 120)),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), getRandomNumberInRange(110, 120)),@@ -1053,7 +1058,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 34),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 37),@@ -1101,7 +1106,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 31),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 24),@@ -1149,7 +1154,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 25),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 23),@@ -1212,7 +1217,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 0.2),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 0.3),@@ -1254,7 +1259,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), 0.3),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), 0.2),@@ -1289,7 +1294,7 @@ public class ManagerDemoSetup extends ManagerSetup {peopleCounter2Asset = assetStorageService.merge(peopleCounter2Asset);MicrophoneAsset microphone1Asset = createDemoMicrophoneAsset("Microphone South", assetAreaStation, new GeoJSONPoint(4.470362, 51.923201), () ->- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), getRandomNumberInRange(50,60)),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), getRandomNumberInRange(45,50)),@@ -1323,7 +1328,7 @@ public class ManagerDemoSetup extends ManagerSetup {microphone1Asset = assetStorageService.merge(microphone1Asset);MicrophoneAsset microphone2Asset = createDemoMicrophoneAsset("Microphone North", assetAreaStation, new GeoJSONPoint(4.469190, 51.923786), () ->- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[] {new SimulatorReplayDatapoint(midnight.get(SECOND_OF_DAY), getRandomNumberInRange(50,60)),new SimulatorReplayDatapoint(midnight.plusHours(1).get(SECOND_OF_DAY), getRandomNumberInRange(45,50)),@@ -1434,7 +1439,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.plusHours(6).get(SECOND_OF_DAY), 187),new SimulatorReplayDatapoint(midnight.plusHours(6).plusMinutes(30).get(SECOND_OF_DAY), 7),@@ -1481,7 +1486,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(smartcitySimulatorAgentId).setReplayData(+ new SimulatorAgentLink(smartcitySimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.plusHours(6).get(SECOND_OF_DAY), new GeoJSONPoint(4.482669, 51.916436)),new SimulatorReplayDatapoint(midnight.plusHours(6).plusMinutes(5).get(SECOND_OF_DAY), new GeoJSONPoint(4.483362, 51.911897)),@@ -1784,7 +1789,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(manufacturerSimulatorAgentId).setReplayData(+ new SimulatorAgentLink(manufacturerSimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.plusHours(6).get(SECOND_OF_DAY), 814),new SimulatorReplayDatapoint(midnight.plusHours(6).plusMinutes(30).get(SECOND_OF_DAY), 814),@@ -1831,7 +1836,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(manufacturerSimulatorAgentId).setReplayData(+ new SimulatorAgentLink(manufacturerSimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.plusHours(6).get(SECOND_OF_DAY), 2),new SimulatorReplayDatapoint(midnight.plusHours(6).plusMinutes(30).get(SECOND_OF_DAY), 2),@@ -1885,7 +1890,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(manufacturerSimulatorAgentId).setReplayData(+ new SimulatorAgentLink(manufacturerSimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.plusHours(6).get(SECOND_OF_DAY), 1000),new SimulatorReplayDatapoint(midnight.plusHours(6).plusMinutes(30).get(SECOND_OF_DAY), 995),@@ -1932,7 +1937,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(manufacturerSimulatorAgentId).setReplayData(+ new SimulatorAgentLink(manufacturerSimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.plusHours(6).get(SECOND_OF_DAY), 10),new SimulatorReplayDatapoint(midnight.plusHours(6).plusMinutes(30).get(SECOND_OF_DAY), 10.5),@@ -1985,7 +1990,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(manufacturerSimulatorAgentId).setReplayData(+ new SimulatorAgentLink(manufacturerSimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.plusHours(6).get(SECOND_OF_DAY), 1200),new SimulatorReplayDatapoint(midnight.plusHours(6).plusMinutes(30).get(SECOND_OF_DAY), 1193),@@ -2032,7 +2037,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(manufacturerSimulatorAgentId).setReplayData(+ new SimulatorAgentLink(manufacturerSimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.plusHours(6).get(SECOND_OF_DAY), 12),new SimulatorReplayDatapoint(midnight.plusHours(6).plusMinutes(30).get(SECOND_OF_DAY), 12.5),@@ -2085,7 +2090,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(manufacturerSimulatorAgentId).setReplayData(+ new SimulatorAgentLink(manufacturerSimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.plusHours(6).get(SECOND_OF_DAY), 1210),new SimulatorReplayDatapoint(midnight.plusHours(6).plusMinutes(30).get(SECOND_OF_DAY), 1190),@@ -2132,7 +2137,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(manufacturerSimulatorAgentId).setReplayData(+ new SimulatorAgentLink(manufacturerSimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.plusHours(6).get(SECOND_OF_DAY), 13),new SimulatorReplayDatapoint(midnight.plusHours(6).plusMinutes(30).get(SECOND_OF_DAY), 13.5),@@ -2186,7 +2191,7 @@ public class ManagerDemoSetup extends ManagerSetup {assetAttribute.addMeta(new MetaItem<>(MetaItemType.AGENT_LINK,- new SimulatorAgentLink(manufacturerSimulatorAgentId).setReplayData(+ new SimulatorAgentLink(manufacturerSimulatorAgentId).setSchedule(createDailySchedule()).setReplayData(new SimulatorReplayDatapoint[]{new SimulatorReplayDatapoint(midnight.plusHours(6).get(SECOND_OF_DAY), 2),new SimulatorReplayDatapoint(midnight.plusHours(6).plusMinutes(30).get(SECOND_OF_DAY), 5),diff --git a/manager/src/main/resources/org/openremote/manager/setup/database/V20260302_01__RequireSimulatorSchedule.sql b/manager/src/main/resources/org/openremote/manager/setup/database/V20260302_01__RequireSimulatorSchedule.sqlnew file mode 100644index 000000000..eff2f9504--- /dev/null+++ b/manager/src/main/resources/org/openremote/manager/setup/database/V20260302_01__RequireSimulatorSchedule.sql@@ -0,0 +1,34 @@+UPDATE asset+SET attributes = (+ SELECT jsonb_object_agg(key, CASE+ WHEN value -> 'meta' -> 'agentLink' ->> 'type' = 'SimulatorAgentLink'+ AND NOT (value -> 'meta' -> 'agentLink' ? 'schedule')+ THEN jsonb_set(value, '{meta, agentLink, schedule}',+ jsonb_build_object(+ -- Start of the day the migration ran+ 'start', (floor(extract(epoch from now()) * 1000 / 86400000) * 86400000)::bigint,+ 'recurrence', 'FREQ=DAILY'+ )+ ) ELSE value+ END) FROM jsonb_each(attributes)+) WHERE attributes @? '$.* ? (@.meta.agentLink.type == "SimulatorAgentLink" && !exists(@.meta.agentLink.schedule))';++-- ##### Use the following to check whether all demo setup SimulatorAgentLinks have a schedule after migrating #####+--+-- SELECT+-- COUNT(*) FILTER (WHERE value -> 'meta' -> 'agentLink' ? 'schedule') AS with_schedule,+-- COUNT(*) FILTER (WHERE NOT (value -> 'meta' -> 'agentLink' ? 'schedule')) AS without_schedule,+-- COUNT(*) AS total_simulators+-- FROM asset, jsonb_each(attributes)+-- WHERE value -> 'meta' -> 'agentLink' ->> 'type' = 'SimulatorAgentLink';++-- ##### Use the following to check the schedules that are present on SimulatorAgentLinks #####+--+-- SELECT+-- id AS asset_id,+-- key AS attribute_name,+-- value->'meta'->'agentLink'->'schedule' AS schedule_data+-- FROM asset,+-- jsonb_each(attributes)+-- WHERE value @? '$.meta.agentLink.type == "SimulatorAgentLink"'+-- AND value->'meta'->'agentLink' ? 'schedule';diff --git a/test/src/test/groovy/org/openremote/test/protocol/simulator/SimulatorProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/simulator/SimulatorProtocolTest.groovyindex f29336754..032e0c219 100644--- a/test/src/test/groovy/org/openremote/test/protocol/simulator/SimulatorProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/simulator/SimulatorProtocolTest.groovy@@ -183,17 +183,58 @@ class SimulatorProtocolTest extends Specification implements ManagerContainerTraprotocol.linkedAttributes.get(attributeRef) == attribute}+ and: "has schedule"+ def schedule = agent.getAgentLink(attribute).schedule+ schedule != null++ and: "with a 1 day period"+ def start = schedule.getStart()+ schedule.getEnd() == start.plusDays(1)+and: "nothing happens"assetDatapointService.getDatapoints(attributeRef).size() == 0}+ def "Check Simulator Agent protocol follows replay data end"() {+ when: "nothing is configured"+ def replayData = new SimulatorReplayDatapoint[] {+ new SimulatorReplayDatapoint(HOUR_IN_SECONDS, "test"),+ new SimulatorReplayDatapoint(HOUR_IN_SECONDS * 23, "test"),+ new SimulatorReplayDatapoint(HOUR_IN_SECONDS * 12, "test")+ }+ asset.addOrReplaceAttributes(new Attribute<>("test1", ValueType.TEXT).addMeta(+ new MetaItem<>(AGENT_LINK, new SimulatorAgentLink(agent.getId(), replayData, null, null))+ ))+ asset = assetStorageService.merge(asset)+ def attribute = asset.getAttribute("test1").get()+ def attributeRef = new AttributeRef(asset.getId(), attribute.getName())++ then: "the agent status should become CONNECTED and the attribute linked to the protocol"+ conditions.eventually {+ assetStorageService.find(agent.getId(), Agent.class).getAgentStatus().orElse(null) == ConnectionStatus.CONNECTED+ protocol.linkedAttributes.get(attributeRef) == attribute+ }++ and: "has schedule"+ def schedule = agent.getAgentLink(attribute).schedule+ schedule != null++ and: "with a 23 hour period"+ def start = schedule.getStart()+ schedule.getEnd() == start.plusHours(23)+ }+def "Check Simulator Agent protocol with replay"() {when: "replayData is configured to add a datapoint in 1hr, 12hrs, and 24hrs every day"asset.addOrReplaceAttributes(new Attribute<>("test2", ValueType.TEXT).addMeta(new MetaItem<>(AGENT_LINK, new SimulatorAgentLink(agent.getId()).setReplayData(new SimulatorReplayDatapoint(HOUR_IN_SECONDS, "test"),new SimulatorReplayDatapoint(HOUR_IN_SECONDS * 12, "test"),- new SimulatorReplayDatapoint(HOUR_IN_SECONDS * 24, "test"))))+ new SimulatorReplayDatapoint(HOUR_IN_SECONDS * 24, "test")+ ).setSchedule(new SimulatorProtocol.Schedule(+ // We manually set the schedule so it starts when we want, as AgentLinks don't have access to the timer service+ LocalDateTime.ofInstant(Instant.parse("1970-01-01T00:00:00.000Z"), ZoneOffset.UTC), null, "FREQ=DAILY"+ )))))asset = assetStorageService.merge(asset)def attribute = asset.getAttribute("test2").get()@@ -476,7 +517,10 @@ class SimulatorProtocolTest extends Specification implements ManagerContainerTranew MetaItem<>(AGENT_LINK, new SimulatorAgentLink(agent.getId()).setReplayData(new SimulatorReplayDatapoint(HOUR_IN_SECONDS, "test"),new SimulatorReplayDatapoint(HOUR_IN_SECONDS * 2, "test"),- )),+ ).setSchedule(new SimulatorProtocol.Schedule(+ // We manually set the schedule so it starts when we want, as AgentLinks don't have access to the timer service+ LocalDateTime.ofInstant(Instant.parse("1970-01-01T00:00:00.000Z"), ZoneOffset.UTC), null, "FREQ=DAILY"+ ))),new MetaItem<>(HAS_PREDICTED_DATA_POINTS, true)))asset = assetStorageService.merge(asset)diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.jsonindex 9cf1bbea6..0f770a54e 100644--- a/ui/app/shared/locales/en/or.json+++ b/ui/app/shared/locales/en/or.json@@ -631,12 +631,15 @@"planRecurrence": "Plan a repeating occurrence","activeFromTo": "Active from {{start}} to {{end}}","fromTo": "from {{start}} to {{end}}",- "fromToDays": "from {{start}} to {{days}} days later {{end}}",- "forDays": "for {{days}} days",+ "fromToDays": "from {{start}} to {{end}}",+ "fromToDays_one": "from {{start}} to 1 day later at {{end}}",+ "fromToDays_other": "from {{start}} to {{days}} days later at {{end}}",+ "forDays": "for 1 day",+ "forDays_other": "for {{days}} days","scheduleActivity": "Schedule Activity","scheduleRuleActivity": "Schedule Rule Activity","scheduleSimulatorActivity": "Simulator Replay Schedule",- "defaultSimulatorSchedule": "Every day from 00:00",+ "defaultSimulatorSchedule": "Replay today at {{time}}","schedule": {"count_one": "occurrence","count_other": "occurrences",diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.jsonindex 447c0065f..4689ee81f 100644--- a/ui/app/shared/locales/nl/or.json+++ b/ui/app/shared/locales/nl/or.json@@ -628,12 +628,15 @@"planRecurrence": "Herhaling plannen","activeFromTo": "Actief van {{start}} tot {{end}}","fromTo": "van {{start}} tot {{end}}",- "fromToDays": "van {{start}} tot {{days}} dagen later {{end}}",- "forDays": "voor {{days}} dagen",+ "fromToDays": "van {{start}} tot {{end}}",+ "fromToDays_one": "van {{start}} tot 1 dag later om {{end}}",+ "fromToDays_other": "van {{start}} tot {{days}} dagen later om {{end}}",+ "forDays": "voor 1 dag",+ "forDays_other": "voor {{days}} dagen","scheduleActivity": "Planner","scheduleRuleActivity": "Regelplanner","scheduleSimulatorActivity": "Simulator Replay Schema",- "defaultSimulatorSchedule": "Elke dag vanaf 00:00",+ "defaultSimulatorSchedule": "Afspelen vandaag vanaf {{time}}","schedule": {"count_one": "herhaling","count_other": "herhalingen",diff --git a/ui/component/or-attribute-input/src/scheduler-renderer.ts b/ui/component/or-attribute-input/src/scheduler-renderer.tsindex 92e57d6fa..2790d4431 100644--- a/ui/component/or-attribute-input/src/scheduler-renderer.ts+++ b/ui/component/or-attribute-input/src/scheduler-renderer.ts@@ -31,7 +31,6 @@ import {isObjectControl,schemaMatches,} from "@openremote/or-json-forms";-import { CalendarEvent } from "@openremote/model";import { Frequency, RRulePartKeys, OrSchedulerChangedEvent, INTUITIVE_NOT_APPLICABLE } from "@openremote/or-scheduler";import "@openremote/or-scheduler";@@ -62,7 +61,7 @@ const schedulerRenderer = (state: JsonFormsStateContext, props: ControlProps) =>const millisSinceStartOfDay = now % dayInMillis;const start = now - millisSinceStartOfDay;const end = start + dayInMillis;- const defaultEvent = { start, end, recurrence: "FREQ=DAILY" };+ const defaultEvent = { start, end };// Resolve the end date by finding the maximum timestampconst timestamps: { timestamp: number }[] = state.core?.data?.replayData?.filter((o: { timestamp?: number }) => typeof o?.timestamp === "number") ?? [];diff --git a/ui/component/or-scheduler/src/index.ts b/ui/component/or-scheduler/src/index.tsindex fea7914d3..1df84eb33 100644--- a/ui/component/or-scheduler/src/index.ts+++ b/ui/component/or-scheduler/src/index.ts@@ -161,6 +161,9 @@ export class OrScheduler extends translate(i18next)(LitElement) {@state()protected _ends: keyof typeof RRULE_ENDS = "never";+ @state()+ protected _eventType: EventTypes = EventTypes.default;+@state()protected _rrule?: RRule;@@ -168,7 +171,6 @@ export class OrScheduler extends translate(i18next)(LitElement) {protected _dialog!: OrVaadinDialog;protected _byRRuleParts?: RRulePartKeys[];- protected _eventType: EventTypes = EventTypes.default;protected _until = moment().toDate();protected get _scheduleWithOffset(): CalendarEvent | undefined {@@ -181,7 +183,7 @@ export class OrScheduler extends translate(i18next)(LitElement) {protected get _timeLabel(): TemplateResult | undefined {if (this._eventType === EventTypes.default) {- return html`<or-translate value="${this.defaultEventTypeLabel}"></or-translate>`;+ return html`<or-translate value="${this.defaultEventTypeLabel}" .options="${this._getDefaultMessageOptions()}"></or-translate>`;}if (this._scheduleWithOffset) {@@ -193,9 +195,9 @@ export class OrScheduler extends translate(i18next)(LitElement) {let template: TemplateResult = html``;if (this.isAllDay && diff > 0) {- template = html`<or-translate value="forDays" .options="${{ days: diff }}"></or-translate>`;+ template = html`<or-translate value="forDays" .options="${{ days: diff, count: diff }}"></or-translate>`;} else if (diff > 0) {- template = html`<or-translate value="fromToDays" .options="${{ ...fromTo, days: diff }}"></or-translate>`;+ template = html`<or-translate value="fromToDays" .options="${{ ...fromTo, days: diff, count: diff }}"></or-translate>`;} else if (diff === 0) {template = html`<or-translate value="fromTo" .options="${fromTo}"></or-translate>`;}@@ -218,36 +220,40 @@ export class OrScheduler extends translate(i18next)(LitElement) {connectedCallback() {super.connectedCallback();- const schedule = this._scheduleWithOffset;- if (schedule?.start && schedule?.end) {- const { start, end } = schedule;- this.isAllDay = this._calculateIsAllDay(start, end);+ const schedule = this._applyTimezoneOffset(this.schedule ?? this.defaultSchedule, this.timezoneOffset);+ if (schedule?.start && schedule?.start) {+ const start = moment(schedule?.start), end = moment(schedule?.end);+ this.isAllDay = start.isSame(start.clone().startOf("day")) && end.isSame(end.clone().endOf("day"));}- if (schedule?.recurrence) {- const origOptions = RRule.fromString(schedule.recurrence).origOptions;+ if (this.schedule?.recurrence) {+ const origOptions = RRule.fromString(this.schedule.recurrence).origOptions;if (origOptions.until) {this._until = moment(origOptions.until).toDate();} else if (origOptions.count) {this._count = origOptions.count;}}++ if (!this.schedule || Util.objectsEqual(this.schedule, this.defaultSchedule)) {+ this._eventType = EventTypes.default;+ } else {+ this._eventType = this.schedule?.recurrence ? EventTypes.recurrence : EventTypes.period;+ }}shouldUpdate(changedProps: PropertyValues) {+ // Follow the default schedule to supply a default end time if not provided+ if (this.schedule && !this.schedule.end && this.defaultSchedule?.end) {+ this.schedule = { ...this.schedule, end: this.defaultSchedule.end };+ }+if (changedProps.has("schedule")) {if (this._scheduleWithOffset?.recurrence) {this._rrule = RRule.fromString(this._scheduleWithOffset.recurrence);} else if (this._eventType === EventTypes.default && this.defaultSchedule?.recurrence) {this._rrule = RRule.fromString(this.defaultSchedule.recurrence);}-- const schedule = this._scheduleWithOffset;- if (schedule?.start && schedule?.end) {- this._eventType = schedule.recurrence ? EventTypes.recurrence : EventTypes.period;- } else {- this._eventType = EventTypes.default;- }}if (changedProps.has("_rrule") && this._rrule) {@@ -259,10 +265,13 @@ export class OrScheduler extends translate(i18next)(LitElement) {return super.shouldUpdate(changedProps);}- protected _calculateIsAllDay(startInMillis: number, endInMillis: number): boolean {- const start = moment(startInMillis);- const end = moment(endInMillis);- return start.isSame(start.clone().startOf("day")) && end.isSame(end.clone().endOf("day"));+ protected _setAllDay() {+ const schedule = this._scheduleWithOffset;+ if (this.isAllDay && this._eventType !== EventTypes.default) {+ const start = moment(schedule?.start).startOf("day").valueOf();+ const end = moment(schedule?.end).endOf("day").valueOf();+ this._scheduleWithOffset = { ...schedule, start, end };+ }}/**@@ -351,16 +360,20 @@ export class OrScheduler extends translate(i18next)(LitElement) {const value = event.target.value;this._eventType = value;+ const fallback = moment().startOf("day");if (value === EventTypes.default) {- this.schedule = this.defaultSchedule; // Default is not local time+ this.schedule = {+ start: this.defaultSchedule?.start ?? fallback.valueOf() - this.timezoneOffset,+ end: this.defaultSchedule?.end ?? fallback.endOf("day").valueOf() - this.timezoneOffset+ };const recurrence = this.defaultSchedule?.recurrence;this._rrule = recurrence ? RRule.fromString(recurrence) : undefined;return;}const schedule = {- start: this._scheduleWithOffset?.start ?? moment().startOf("day").toDate().getTime(),- end: this._scheduleWithOffset?.end ?? moment().startOf("day").endOf("day").toDate().getTime()+ start: this._scheduleWithOffset?.start ?? fallback.valueOf(),+ end: this._scheduleWithOffset?.end ?? fallback.endOf("day").valueOf()};if (value === EventTypes.period) {this._scheduleWithOffset = schedule;@@ -391,6 +404,13 @@ export class OrScheduler extends translate(i18next)(LitElement) {}}+ protected _getDefaultMessageOptions(): { date: string, time: string } {+ return {+ date: moment.utc(this.defaultSchedule?.start).format("YYYY-MM-DD"),+ time: moment.utc(this.defaultSchedule?.start).format("HH:mm")+ };+ }+protected render() {return html`<or-vaadin-button style="max-width: 100%" @click="${() => this._dialog!.open()}">${this._timeLabel}</or-vaadin-button>@@ -424,7 +444,7 @@ export class OrScheduler extends translate(i18next)(LitElement) {protected _getDialogContent(): TemplateResult {const eventTypes = [- { value: "default", label: i18next.t(this.defaultEventTypeLabel) },+ { value: "default", label: i18next.t(this.defaultEventTypeLabel, this._getDefaultMessageOptions()) },{ value: "period", label: i18next.t("planPeriod") },{ value: "recurrence", label: i18next.t("planRecurrence") },];@@ -521,6 +541,7 @@ export class OrScheduler extends translate(i18next)(LitElement) {}protected _onSave() {+ this._setAllDay();this.dispatchEvent(new OrSchedulerChangedEvent(this.schedule ?? this.defaultSchedule));this._dialog!.close();}@@ -646,17 +667,20 @@ export class OrScheduler extends translate(i18next)(LitElement) {<div style="display: flex; gap: 8px"><div class="period"><or-vaadin-date-picker style="text-transform: capitalize" ?combined="${!this.isAllDay}" .value="${moment(calendar.start).format("YYYY-MM-DD")}"- @change="${this._onPartChange("start", "value")}" label="${i18next.t("from")}"> </or-vaadin-date-picker>+ @change="${this._onPartChange("start", "value")}" label="${i18next.t("from")}" .max="${moment(calendar.end).format("YYYY-MM-DD")}">+ </or-vaadin-date-picker><or-vaadin-time-picker style="margin-top: auto" ?hidden=${this.isAllDay} .value="${moment(calendar.start).format("HH:mm")}"- @change="${this._onPartChange("start-time", "value")}">+ @change="${this._onPartChange("start-time", "value")}"+ .max="${moment(calendar.end).isSameOrBefore(moment(calendar.start), "day") && moment(calendar.end).format("HH:mm")}"></or-vaadin-time-picker></div><div class="period"><or-vaadin-date-picker style="text-transform: capitalize" ?combined="${!this.isAllDay}" .value="${moment(calendar.end).format("YYYY-MM-DD")}"- @change="${this._onPartChange("end", "value")}" label="${i18next.t("to")}">+ @change="${this._onPartChange("end", "value")}" label="${i18next.t("to")}" .min="${moment(calendar.start).format("YYYY-MM-DD")}"></or-vaadin-date-picker><or-vaadin-time-picker style="margin-top: auto" ?hidden=${this.isAllDay} .value="${moment(calendar.end).format("HH:mm")}"- @change="${this._onPartChange("end-time", "value")}">+ @change="${this._onPartChange("end-time", "value")}"+ .min="${moment(calendar.end).isSameOrBefore(moment(calendar.start), "day") && moment(calendar.start).format("HH:mm")}"></or-vaadin-time-picker></div></div>diff --git a/ui/component/or-scheduler/stories/or-scheduler.stories.ts b/ui/component/or-scheduler/stories/or-scheduler.stories.tsindex 2b447bc85..f2b71e6e4 100644--- a/ui/component/or-scheduler/stories/or-scheduler.stories.ts+++ b/ui/component/or-scheduler/stories/or-scheduler.stories.ts@@ -30,7 +30,7 @@ const tagName = "or-scheduler";type Story = StoryObj;setCustomElementsManifest(customElements);-const { events, args, argTypes, template } = getStorybookHelpers(tagName);+const { events, args, argTypes, template } = getORStorybookHelpers(tagName);const meta: Meta = {title: "Playground/or-scheduler",