Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Added sun position trigger support to JSON (when then) rules (#777)

Rich Turnerb095e83bf68c
diff --git a/gradle.properties b/gradle.properties
index f5c4bd3a5..76442a720 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -36,7 +36,6 @@ jmxtermVersion = 1.0.0
nettyVersion = 4.1.79.Final
flywaydbVersion = 9.0.1
ical4jVersion = 2.1.5
-jafamaVersion = 2.3.1
friendlyIdVersion = 1.0.1
geotoolsVersion = 19.1
firebaseAdminVersion = 7.1.0
@@ -55,5 +54,6 @@ hiveMQClientVersion=1.2.2
bluetoothVersion = 0.39
nashornVersion=15.3
failsafeVersion=3.1.0
+suncalcVersion=3.5
snapshotsRepoUrl=https://s01.oss.sonatype.org/content/repositories/snapshots/
releasesRepoUrl=https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/
diff --git a/manager/build.gradle b/manager/build.gradle
index 6da10f0f2..d1922f49e 100644
--- a/manager/build.gradle
+++ b/manager/build.gradle
@@ -14,18 +14,17 @@ dependencies {
api resolveProject(":agent")
api resolveProject(":model")
- api "org.xerial:sqlite-jdbc:$sqliteVersion"
+ implementation "org.xerial:sqlite-jdbc:$sqliteVersion"
api "org.mnode.ical4j:ical4j:$ical4jVersion"
- api "net.jafama:jafama:$jafamaVersion"
- api "org.geotools:gt-main:$geotoolsVersion"
- api "com.google.firebase:firebase-admin:$firebaseAdminVersion"
- api "org.simplejavamail:simple-java-mail:$simpleJavaMailVersion"
- api "io.swagger.core.v3:swagger-jaxrs2:$swaggerVersion"
- api "org.openjdk.nashorn:nashorn-core:$nashornVersion"
+ implementation "org.geotools:gt-main:$geotoolsVersion"
+ implementation "com.google.firebase:firebase-admin:$firebaseAdminVersion"
+ implementation "org.simplejavamail:simple-java-mail:$simpleJavaMailVersion"
+ implementation "io.swagger.core.v3:swagger-jaxrs2:$swaggerVersion"
+ implementation "org.openjdk.nashorn:nashorn-core:$nashornVersion"
- api ("io.netty:netty-codec-http:$nettyVersion") {
+ implementation ("io.netty:netty-codec-http:$nettyVersion") {
force = true
}
@@ -33,9 +32,11 @@ dependencies {
exclude module: "slf4j-log4j12" // Don't want log4J
}
- api("org.quartz-scheduler:quartz:$quartzVersion") {
+ implementation("org.quartz-scheduler:quartz:$quartzVersion") {
exclude group: "c3p0"
}
+
+ implementation "org.shredzone.commons:commons-suncalc:$suncalcVersion"
}
jar {
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
index e50093133..b03030fe0 100644
--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
@@ -27,6 +27,7 @@ import org.openremote.container.timer.TimerService;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.model.asset.Asset;
import org.openremote.model.attribute.AttributeRef;
+import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.notification.EmailNotificationMessage;
import org.openremote.model.notification.Notification;
import org.openremote.model.notification.PushNotificationMessage;
@@ -37,15 +38,22 @@ import org.openremote.model.query.filter.AttributePredicate;
import org.openremote.model.query.filter.UserAssetPredicate;
import org.openremote.model.rules.*;
import org.openremote.model.rules.json.*;
+import org.openremote.model.util.EnumUtil;
import org.openremote.model.util.TextUtil;
import org.openremote.model.util.TimeUtil;
import org.openremote.model.util.ValueUtil;
import org.openremote.model.value.MetaItemType;
import org.quartz.CronExpression;
+import org.shredzone.commons.suncalc.SunTimes;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
@@ -88,6 +96,7 @@ public class JsonRulesBuilder extends RulesBuilder {
Predicate<Long> timePredicate;
RuleConditionEvaluationResult lastEvaluationResult;
+ @SuppressWarnings("ConstantConditions")
public RuleConditionState(RuleCondition ruleCondition, boolean trackUnmatched, TimerService timerService) throws Exception {
this.timerService = timerService;
this.ruleCondition = ruleCondition;
@@ -97,40 +106,75 @@ public class JsonRulesBuilder extends RulesBuilder {
previouslyUnmatchedAssetStates = new HashSet<>();
}
- if (!TextUtil.isNullOrEmpty(ruleCondition.timer)) {
-
+ if (!TextUtil.isNullOrEmpty(ruleCondition.duration)) {
try {
- if (TimeUtil.isTimeDuration(ruleCondition.timer)) {
-
- final long duration = TimeUtil.parseTimeDuration(ruleCondition.timer);
- AtomicLong nextExecuteMillis = new AtomicLong(timerService.getCurrentTimeMillis());
-
- timePredicate = (time) -> {
- long nextExecute = nextExecuteMillis.get();
- if (time >= nextExecute) {
- nextExecuteMillis.set(nextExecute + duration);
- return true;
- }
- return false;
- };
- }
-
- if (CronExpression.isValidExpression(ruleCondition.timer)) {
+ final long duration = TimeUtil.parseTimeDuration(ruleCondition.duration);
+ AtomicLong nextExecuteMillis = new AtomicLong(timerService.getCurrentTimeMillis());
+
+ timePredicate = (time) -> {
+ long nextExecute = nextExecuteMillis.get();
+ if (time >= nextExecute) {
+ nextExecuteMillis.set(nextExecute + duration);
+ return true;
+ }
+ return false;
+ };
+ } catch (Exception e) {
+ log(Level.SEVERE, "Failed to parse rule condition duration expression: " + ruleCondition.duration, e);
+ throw e;
+ }
+ } else if (!TextUtil.isNullOrEmpty(ruleCondition.cron)) {
+ try {
+ CronExpression timerExpression = new CronExpression(ruleCondition.cron);
+ AtomicLong nextExecuteMillis = new AtomicLong(timerExpression.getNextValidTimeAfter(new Date(timerService.getCurrentTimeMillis())).getTime());
+
+ timePredicate = (time) -> {
+ long nextExecute = nextExecuteMillis.get();
+ if (time >= nextExecute) {
+ nextExecuteMillis.set(timerExpression.getNextInvalidTimeAfter(timerExpression.getNextInvalidTimeAfter(new Date(nextExecute))).getTime());
+ return true;
+ }
+ return false;
+ };
+ } catch (Exception e) {
+ log(Level.SEVERE, "Failed to parse rule condition cron expression: " + ruleCondition.cron, e);
+ throw e;
+ }
+ } else if (ruleCondition.sun != null) {
+ SunTimes.Parameters sunCalculator = getSunCalculator(ruleCondition.sun, timerService);
+ long offsetMillis = ruleCondition.sun.getOffsetMins() != null ? ruleCondition.sun.getOffsetMins() * 60000 : 0;
- CronExpression timerExpression = new CronExpression(ruleCondition.timer);
- AtomicLong nextExecuteMillis = new AtomicLong(timerExpression.getNextValidTimeAfter(new Date(timerService.getCurrentTimeMillis())).getTime());
+ // Calculate the next occurrence
+ AtomicReference<SunTimes> sunTimes = new AtomicReference<>(sunCalculator.execute());
+ ZonedDateTime occurrence = ruleCondition.sun.getPosition() == SunPositionTrigger.Position.SUNSET ? sunTimes.get().getSet() : sunTimes.get().getRise();
- timePredicate = (time) -> {
- long nextExecute = nextExecuteMillis.get();
- if (time >= nextExecute) {
- nextExecuteMillis.set(timerExpression.getNextInvalidTimeAfter(timerExpression.getNextInvalidTimeAfter(new Date(nextExecute))).getTime());
- return true;
+ if (occurrence == null) {
+ Exception e = new IllegalStateException("Rule condition requested sun position never occurs at the specified location: " + ruleCondition.sun);
+ log(Level.SEVERE, e.getMessage(), e);
+ throw e;
+ }
+ try {
+ AtomicLong nextExecuteMillis = new AtomicLong(occurrence.toInstant().toEpochMilli() + offsetMillis);
+
+ timePredicate = (time) -> {
+ long nextExecute = nextExecuteMillis.get();
+ if (time >= nextExecute) {
+ // Advance the calculator to when the previous occurrence ends
+ sunTimes.set(sunCalculator.on(sunTimes.get().getSet()).execute());
+ ZonedDateTime nextOccurrence = ruleCondition.sun.getPosition() == SunPositionTrigger.Position.SUNSET ? sunTimes.get().getSet() : sunTimes.get().getRise();
+
+ if (nextOccurrence == null) {
+ log(Level.WARNING, "Rule condition requested sun position never occurs at the specified location: " + ruleCondition.sun);
+ } else {
+ nextExecuteMillis.set(nextOccurrence.toInstant().toEpochMilli() + offsetMillis);
}
- return false;
- };
- }
+ log(Level.INFO, "Rule condition sun position has triggered");
+ return true;
+ }
+ return false;
+ };
} catch (Exception e) {
- log(Level.SEVERE, "Failed to parse rule condition timer expression: " + ruleCondition.timer, e);
+ log(Level.SEVERE, "Failed to parse rule condition duration expression: " + ruleCondition.duration, e);
throw e;
}
} else if (ruleCondition.assets != null) {
@@ -415,7 +459,7 @@ public class JsonRulesBuilder extends RulesBuilder {
}
public boolean thenMatched() {
- return thenMatchedAssetIds != null && !thenMatchedAssetIds.isEmpty();
+ return (thenMatchedAssetIds != null && !thenMatchedAssetIds.isEmpty()) || !otherwiseMatched();
}
public boolean otherwiseMatched() {
@@ -488,6 +532,7 @@ public class JsonRulesBuilder extends RulesBuilder {
public static final String PLACEHOLDER_RULESET_ID = "%RULESET_ID%";
public static final String PLACEHOLDER_RULESET_NAME = "%RULESET_NAME%";
public static final String PLACEHOLDER_TRIGGER_ASSETS = "%TRIGGER_ASSETS%";
+ final static String TIMER_TEMPORAL_FACT_NAME_PREFIX = "TimerTemporalFact-";
final static String LOG_PREFIX = "JSON Rules: ";
final protected AssetStorageService assetStorageService;
final protected TimerService timerService;
@@ -500,6 +545,7 @@ public class JsonRulesBuilder extends RulesBuilder {
final protected BiConsumer<Runnable, Long> scheduledActionConsumer;
final protected Map<String, RuleState> ruleStateMap = new HashMap<>();
final protected JsonRule[] jsonRules;
+ final protected Ruleset jsonRuleset;
public JsonRulesBuilder(Ruleset ruleset, TimerService timerService,
AssetStorageService assetStorageService, ScheduledExecutorService executorService,
@@ -516,6 +562,7 @@ public class JsonRulesBuilder extends RulesBuilder {
this.predictedDatapointsFacade = predictedDatapoints;
this.scheduledActionConsumer = scheduledActionConsumer;
+ jsonRuleset = ruleset;
String rulesStr = ruleset.getRules();
rulesStr = rulesStr.replace(PLACEHOLDER_RULESET_ID, Long.toString(ruleset.getId()));
rulesStr = rulesStr.replace(PLACEHOLDER_RULESET_NAME, ruleset.getName());
@@ -536,14 +583,28 @@ public class JsonRulesBuilder extends RulesBuilder {
public void stop(RulesFacts facts) {
Arrays.stream(jsonRules).forEach(jsonRule ->
executeRuleActions(jsonRule, jsonRule.onStop, "onStop", false, facts, null, assetsFacade, usersFacade, notificationsFacade, predictedDatapointsFacade, this.scheduledActionConsumer));
+
+ // Remove temporal fact for timer rule evaluation
+ String tempFactName = TIMER_TEMPORAL_FACT_NAME_PREFIX + jsonRuleset.getId();
+ facts.remove(tempFactName);
}
public void start(RulesFacts facts) {
- Arrays.stream(jsonRules).forEach(jsonRule ->
- executeRuleActions(jsonRule, jsonRule.onStart, "onStart", false, facts, null, assetsFacade, usersFacade, notificationsFacade, predictedDatapointsFacade, this.scheduledActionConsumer));
+ AtomicBoolean hasTimeTrigger = new AtomicBoolean(false);
+
+ Arrays.stream(jsonRules).forEach(jsonRule -> {
+ hasTimeTrigger.set(hasTimeTrigger.get() || LogicGroup.getItemsRecursive(jsonRule.when).stream().anyMatch(RuleCondition::hasTimeTrigger));
+ executeRuleActions(jsonRule, jsonRule.onStart, "onStart", false, facts, null, assetsFacade, usersFacade, notificationsFacade, predictedDatapointsFacade, this.scheduledActionConsumer);
+ });
// Initialise asset states
onAssetStatesChanged(facts, null);
+
+ // Insert a temporal fact if we have a time trigger (this will cause the engine to fire periodically)
+ if (hasTimeTrigger.get()) {
+ String tempFactName = TIMER_TEMPORAL_FACT_NAME_PREFIX + jsonRuleset.getId();
+ facts.putTemporary(tempFactName, Long.MAX_VALUE - timerService.getCurrentTimeMillis(), ""); // current time + expiration shouldn't overflow
+ }
}
public void onAssetStatesChanged(RulesFacts facts, RulesEngine.AssetStateChangeEvent event) {
@@ -1071,4 +1132,41 @@ public class JsonRulesBuilder extends RulesBuilder {
protected static void log(Level level, String message, Throwable t) {
RulesEngine.RULES_LOG.log(level, LOG_PREFIX + message, t);
}
+
+ protected static SunTimes.Parameters getSunCalculator(SunPositionTrigger sunPositionTrigger, TimerService timerService) throws IllegalStateException {
+ SunPositionTrigger.Position position = sunPositionTrigger.getPosition();
+ GeoJSONPoint location = sunPositionTrigger.getLocation();
+
+ if (position == null) {
+ IllegalStateException e = new IllegalStateException("Rule condition sun requires a position value");
+ log(Level.SEVERE, e.getMessage(), e);
+ throw e;
+ }
+ if (location == null) {
+ IllegalStateException e = new IllegalStateException("Rule condition sun requires a location value");
+ log(Level.SEVERE, e.getMessage(), e);
+ throw e;
+ }
+
+ SunTimes.Twilight twilight = null;
+ if (position.name().startsWith(SunPositionTrigger.TWILIGHT_PREFIX)) {
+ String lookupValue = position.name().substring(SunPositionTrigger.TWILIGHT_PREFIX.length());
+ twilight = EnumUtil.enumFromString(SunTimes.Twilight.class, lookupValue).orElseThrow(() -> {
+ IllegalStateException e = new IllegalStateException("Rule condition un-supported twilight position value '" + lookupValue + "'");
+ log(Level.SEVERE, e.getMessage(), e);
+ return e;
+ });
+ }
+
+ SunTimes.Parameters sunCalculator = SunTimes.compute()
+ .at(location.getY(), location.getX())
+ .utc()
+ .on(timerService.getNow());
+
+ if (twilight != null) {
+ sunCalculator.twilight(twilight);
+ }
+
+ return sunCalculator;
+ }
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesClock.java b/manager/src/main/java/org/openremote/manager/rules/RulesClock.java
deleted file mode 100644
index 45e9266d3..000000000
--- a/manager/src/main/java/org/openremote/manager/rules/RulesClock.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright 2018, 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.rules;
-
-import org.openremote.container.timer.TimerService;
-import org.openremote.model.rules.TemporaryFact;
-import org.openremote.model.util.TimeUtil;
-
-import java.time.*;
-import java.time.temporal.ChronoUnit;
-import java.util.function.Predicate;
-
-/**
- * A fact that is present in any {@link RulesFacts}.
- */
-public class RulesClock {
-
- final public long timestamp;
- final public LocalDateTime time;
-
- public RulesClock(TimerService timerService) {
- this(timerService.getCurrentTimeMillis());
- }
-
- public RulesClock(long timestamp) {
- this.timestamp = timestamp;
- time = LocalDateTime.ofInstant(Instant.ofEpochMilli(this.timestamp), ZoneId.systemDefault());
- }
-
- public long getTimestamp() {
- return timestamp;
- }
-
- public LocalDateTime getTime() {
- return time;
- }
-
- public ZonedDateTime getZonedTime() {
- return time.atZone(ZoneId.systemDefault());
- }
-
- public Instant getInstant() {
- return getZonedTime().toInstant();
- }
-
- public <T extends TemporaryFact> Predicate<T> last(String timeWindow) {
- double timeWindowStart = getTimestamp() - TimeUtil.parseTimeDuration(timeWindow);
- return fact -> timeWindowStart <= fact.getTimestamp();
- }
-
- public DayOfWeek getDayOfWeek() {
- return getTime().getDayOfWeek();
- }
-
- public LocalDateTime getYesterday() {
- return getTime().minus(1, ChronoUnit.DAYS);
- }
-
- public LocalDateTime getTomorrow() {
- return getTime().plus(1, ChronoUnit.DAYS);
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "timestamp=" + timestamp +
- ", time=" + time +
- '}';
- }
-}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
index e118c17f8..e476026d2 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
@@ -505,10 +505,6 @@ public class RulesEngine<T extends Ruleset> {
facts.startTrackingLocationRules();
}
- // Set the current clock
- RulesClock clock = new RulesClock(timerService);
- facts.setClock(clock);
-
// Remove any expired temporary facts
facts.removeExpiredTemporaryFacts();
@@ -517,7 +513,7 @@ public class RulesEngine<T extends Ruleset> {
if (deployment.getStatus() == DEPLOYED) {
- RULES_LOG.fine("Executing rules @" + clock + " of: " + deployment);
+ RULES_LOG.fine("Executing rules of: " + deployment);
// If full detail logging is enabled
// Log asset states and events before firing
@@ -526,10 +522,10 @@ public class RulesEngine<T extends Ruleset> {
// Reset facts for this firing (loop detection etc.)
facts.reset();
- long startTimestamp = System.currentTimeMillis();
+ long startTimestamp = timerService.getCurrentTimeMillis();
lastFireTimestamp = startTimestamp;
engine.fire(deployment.getRules(), facts);
- RULES_FIRED_LOG.fine("Rules deployment '" + deployment.getName() + "' executed in: " + (System.currentTimeMillis() - startTimestamp) + "ms");
+ RULES_FIRED_LOG.fine("Rules deployment '" + deployment.getName() + "' executed in: " + (timerService.getCurrentTimeMillis() - startTimestamp) + "ms");
}
} catch (Exception ex) {
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
index 58b0dd13b..5c5cc7adf 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
@@ -36,6 +36,7 @@ import org.openremote.model.rules.TemporaryFact;
import org.openremote.model.util.TimeUtil;
import java.time.Duration;
+import java.time.Instant;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
@@ -55,7 +56,6 @@ public class RulesFacts extends Facts implements RuleListener {
public static final int INITIAL_CAPACITY = 100000;
- public static final String CLOCK = "INTERNAL_CLOCK";
public static final String ASSET_STATES = "INTERNAL_ASSET_STATES";
public static final String ASSET_EVENTS = "INTERNAL_ASSET_EVENTS";
public static final String EXECUTION_VARS = "INTERNAL_EXECUTION_VAR";
@@ -68,7 +68,6 @@ public class RulesFacts extends Facts implements RuleListener {
final protected Logger LOG;
final protected Map<String, Collection<AssetState<?>>> assetIdIndex = new HashMap<>();
final protected Map<String, Collection<AssetState<?>>> assetTypeIndex = new HashMap<>();
- public RulesClock clock;
protected int triggerCount;
protected boolean trackLocationRules;
protected Map<String, Set<GeofencePredicate>> assetStateLocationPredicateMap = null;
@@ -103,15 +102,6 @@ public class RulesFacts extends Facts implements RuleListener {
assetStateSetEntry.getValue())).collect(Collectors.toList());
}
- public RulesClock getClock() {
- return clock;
- }
-
- public void setClock(RulesClock clock) {
- this.clock = clock;
- super.put(CLOCK, clock);
- }
-
@SuppressWarnings("unchecked")
public Collection<AssetState<?>> getAssetStates() {
return get(ASSET_STATES);
@@ -129,8 +119,7 @@ public class RulesFacts extends Facts implements RuleListener {
public Map<String, Object> getNamedFacts() {
return asMap().entrySet().stream().filter(entry ->
- !entry.getKey().equals(CLOCK)
- && !entry.getKey().equals(ASSET_STATES)
+ !entry.getKey().equals(ASSET_STATES)
&& !entry.getKey().equals(ASSET_EVENTS)
&& !entry.getKey().equals(EXECUTION_VARS)
&& !entry.getKey().equals(ANONYMOUS_FACTS)
@@ -188,7 +177,6 @@ public class RulesFacts extends Facts implements RuleListener {
case ASSET_EVENTS:
case ASSET_STATES:
case EXECUTION_VARS:
- case CLOCK:
throw new IllegalArgumentException("Reserved internal fact name: " + name);
}
if (LOG.isLoggable(Level.FINEST)) {
@@ -269,7 +257,7 @@ public class RulesFacts extends Facts implements RuleListener {
}
public RulesFacts putTemporary(long expires, Object value) {
- getAnonymousFacts().add(new TemporaryFact<>((long) getClock().getTimestamp(), expires, value));
+ getAnonymousFacts().add(new TemporaryFact<>(timerService.getCurrentTimeMillis(), expires, value));
return this;
}
@@ -282,7 +270,7 @@ public class RulesFacts extends Facts implements RuleListener {
}
public RulesFacts putTemporary(String name, long expires, Object value) {
- put(name, new TemporaryFact<>((long) getClock().getTimestamp(), expires, value));
+ put(name, new TemporaryFact<>(timerService.getCurrentTimeMillis(), expires, value));
return this;
}
@@ -462,7 +450,7 @@ public class RulesFacts extends Facts implements RuleListener {
}
public void removeExpiredTemporaryFacts() {
- long currentTimestamp = (long) getClock().getTimestamp();
+ long currentTimestamp = timerService.getCurrentTimeMillis();
getAssetEvents().removeIf(fact -> {
boolean result = fact.isExpired(currentTimestamp);
if (result && LOG.isLoggable(Level.FINEST)) {
@@ -472,8 +460,7 @@ public class RulesFacts extends Facts implements RuleListener {
});
List<Fact<?>> expiredFacts = StreamSupport.stream(super.spliterator(), false).filter(fact -> {
- if (fact.getName().equals(CLOCK)
- || fact.getName().equals(ASSET_STATES)
+ if (fact.getName().equals(ASSET_STATES)
|| fact.getName().equals(ASSET_EVENTS)
|| fact.getName().equals(EXECUTION_VARS)
|| fact.getName().equals(ANONYMOUS_FACTS)
@@ -494,7 +481,7 @@ public class RulesFacts extends Facts implements RuleListener {
boolean result = false;
if (fact instanceof TemporaryFact<?>) {
TemporaryFact<?> temporaryFact = (TemporaryFact<?>) fact;
- result = temporaryFact.isExpired((long) getClock().getTimestamp());
+ result = temporaryFact.isExpired(timerService.getCurrentTimeMillis());
}
if (result && LOG.isLoggable(Level.FINEST)) {
LOG.finest("Fact change (DELETE EXPIRED): " + fact + " - on: " + loggingContext);
@@ -512,7 +499,7 @@ public class RulesFacts extends Facts implements RuleListener {
boolean haveLog = false;
if (getAllFacts().count() > 0) {
logger.log(level, "--------------------------------- CLOCK ---------------------------------");
- logger.log(level, getClock().toString());
+ logger.log(level, Instant.ofEpochMilli(timerService.getCurrentTimeMillis()).toString());
haveLog = true;
}
@@ -568,6 +555,10 @@ public class RulesFacts extends Facts implements RuleListener {
return haveLog;
}
+ public TimerService getClock() {
+ return timerService;
+ }
+
public static Comparator<AssetState<?>> asComparator(AssetQuery.OrderBy orderBy) {
Function<AssetState<?>, String> keyExtractor = AssetState::getAssetName;
diff --git a/model/src/main/java/org/openremote/model/query/LogicGroup.java b/model/src/main/java/org/openremote/model/query/LogicGroup.java
index 436680267..2885f5a04 100644
--- a/model/src/main/java/org/openremote/model/query/LogicGroup.java
+++ b/model/src/main/java/org/openremote/model/query/LogicGroup.java
@@ -90,4 +90,15 @@ public class LogicGroup<T> {
", groups=" + (groups == null ? "[]" : Arrays.toString(groups.toArray())) +
'}';
}
+
+ public static <S> List<S> getItemsRecursive(LogicGroup<S> group) {
+ List<S> items = new ArrayList<>();
+ if (group.items != null) {
+ items.addAll(group.items);
+ }
+ if (group.groups != null) {
+ group.groups.forEach(g -> items.addAll(getItemsRecursive(g)));
+ }
+ return items;
+ }
}
diff --git a/model/src/main/java/org/openremote/model/rules/SunPositionTrigger.java b/model/src/main/java/org/openremote/model/rules/SunPositionTrigger.java
new file mode 100644
index 000000000..f88ebc0fc
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/SunPositionTrigger.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright 2022, 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.rules;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import org.openremote.model.geo.GeoJSONPoint;
+
+public class SunPositionTrigger {
+
+ public static final String TWILIGHT_PREFIX = "TWILIGHT_";
+
+ /**
+ * The astronomical position of the sun
+ */
+ public enum Position {
+ SUNRISE,
+ SUNSET,
+ TWILIGHT_VISUAL,
+ TWILIGHT_VISUAL_LOWER,
+ TWILIGHT_HORIZON,
+ TWILIGHT_CIVIL,
+ TWILIGHT_NAUTICAL,
+ TWILIGHT_ASTRONOMICAL,
+ TWILIGHT_GOLDEN_HOUR,
+ TWILIGHT_BLUE_HOUR,
+ TWILIGHT_NIGHT_HOUR
+ }
+
+ Position position;
+ GeoJSONPoint location;
+ Integer offsetMins;
+
+ @JsonCreator
+ public SunPositionTrigger(Position position, GeoJSONPoint location, Integer offsetMins) {
+ this.position = position;
+ this.location = location;
+ this.offsetMins = offsetMins;
+ }
+
+ public Position getPosition() {
+ return position;
+ }
+
+ public GeoJSONPoint getLocation() {
+ return location;
+ }
+
+ public Integer getOffsetMins() {
+ return offsetMins;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "position=" + position +
+ ", location=" + location +
+ ", offsetMins=" + offsetMins +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java b/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java
index 3c8bb2a2c..5c5127162 100644
--- a/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java
@@ -20,13 +20,14 @@
package org.openremote.model.rules.json;
import org.openremote.model.query.AssetQuery;
+import org.openremote.model.rules.SunPositionTrigger;
/**
* Consists of one of the following triggers in order of precedence:
* <ol>
- * <li>{@link #timer} - Timer expression (interval e.g. '1h' or CRON expression) which means the condition becomes
- * true when the interval duration passes or the cron expression matches the current time - note the firing of the
- * rule will not be precise</li>
+ * <li>{@link #duration} - ISO8601 duration expression (e.g. 'PT1H') after which the condition becomes true - 1min precision</li>
+ * <li>{@link #cron} - CRON expression (e.g. "*&#47;5 * * * *") at which time the condition becomes true - 1min precision</li>
+ * <li>{@link #sun} - {@link SunPositionTrigger} at which time the condition becomes true - 1min precision</li>
* <li>{@link #assets} - {@link AssetQuery} to be applied to the {@link org.openremote.model.rules.AssetState}s
* available within the rule engine this rule is loaded into. Evaluates to true when one or more
* {@link org.openremote.model.rules.AssetState}s (referencing unique {@link org.openremote.model.asset.Asset}s) are
@@ -39,9 +40,31 @@ import org.openremote.model.query.AssetQuery;
public class RuleCondition {
/**
- * Must be an ISO8601 duration string (e.g. PT1H)
+ * ISO8601 duration expression (e.g. PT1H)
+ */
+ public String duration;
+
+ /**
+ * CRON expression (e.g. *&#47;5 * * * *)
+ */
+ public String cron;
+
+ /**
+ * {@link SunPositionTrigger}
+ */
+ public SunPositionTrigger sun;
+
+ /**
+ * {@link AssetQuery}
*/
- public String timer;
public AssetQuery assets;
+
+ /**
+ * Can be used to reference the {@link #assets} that cause this condition to trigger
+ */
public String tag;
+
+ public boolean hasTimeTrigger() {
+ return duration != null || cron != null || sun != null;
+ }
}
diff --git a/test/build.gradle b/test/build.gradle
index 75eaed5e6..b49ffd3fc 100644
--- a/test/build.gradle
+++ b/test/build.gradle
@@ -27,6 +27,10 @@ dependencies {
// Libraries should not depend on a logging implementation and/or alpha versions!
exclude group: "org.slf4j"
}
+
+ testImplementation "com.google.firebase:firebase-admin:$firebaseAdminVersion"
+ testImplementation "org.simplejavamail:simple-java-mail:$simpleJavaMailVersion"
+ testImplementation "org.shredzone.commons:commons-suncalc:$suncalcVersion"
}
tasks.withType(Test) {
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy
index ae449d0cc..fd126cdb0 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy
@@ -5,12 +5,12 @@ import groovy.transform.ToString
import org.openremote.container.Container
import org.openremote.container.timer.TimerService
import org.openremote.manager.asset.AssetStorageService
-import org.openremote.manager.rules.RulesClock
import org.openremote.manager.rules.RulesEngine
import org.openremote.manager.rules.RulesFacts
import org.openremote.manager.rules.facade.AssetsFacade
import spock.lang.Specification
+import java.util.concurrent.TimeUnit
import java.util.stream.Collectors
class BasicRulesFactsTest extends Specification {
@@ -42,6 +42,7 @@ class BasicRulesFactsTest extends Specification {
def assetsFacade
RulesFacts rulesFacts
+ TimerService timerService
def setupSpec() {
// Init logging config
@@ -51,14 +52,11 @@ class BasicRulesFactsTest extends Specification {
def setup() {
given: "some rule facts"
assetsFacade = Mock(AssetsFacade)
- def timerService = new TimerService()
+ timerService = new TimerService()
def assetStorageService = new AssetStorageService()
timerService.clock = TimerService.Clock.PSEUDO
+ timerService.clock.stop()
rulesFacts = new RulesFacts(timerService, assetStorageService, assetsFacade, this, RulesEngine.RULES_LOG)
-
- and: "a rules clock"
- def rulesClock = new RulesClock(0)
- rulesFacts.setClock(rulesClock)
}
def "Handle named facts"() {
@@ -297,7 +295,7 @@ class BasicRulesFactsTest extends Specification {
rulesFacts.putTemporary("baz", "PT15S", "BAZ")
and: "the clock is advanced and temporary facts are expired"
- rulesFacts.setClock(new RulesClock(3000))
+ timerService.getClock().advanceTime(3, TimeUnit.SECONDS)
rulesFacts.removeExpiredTemporaryFacts()
then: "all temporary facts should still be present"
@@ -312,7 +310,7 @@ class BasicRulesFactsTest extends Specification {
assert !rulesFacts.getOptional("abc").isPresent()
when: "the clock is advanced and temporary facts are expired"
- rulesFacts.setClock(new RulesClock(6000))
+ timerService.getClock().advanceTime(3, TimeUnit.SECONDS)
rulesFacts.removeExpiredTemporaryFacts()
then: "some temporary facts should still be present"
@@ -323,7 +321,7 @@ class BasicRulesFactsTest extends Specification {
assert rulesFacts.matchFirst("baz").isPresent()
when: "the clock is advanced and temporary facts are expired"
- rulesFacts.setClock(new RulesClock(12000))
+ timerService.getClock().advanceTime(6, TimeUnit.SECONDS)
rulesFacts.removeExpiredTemporaryFacts()
then: "some temporary facts should still be present"
@@ -355,7 +353,7 @@ class BasicRulesFactsTest extends Specification {
rulesFacts.putTemporary("PT15S", anonFact3)
and: "the clock is advanced and temporary facts are expired"
- rulesFacts.setClock(new RulesClock(3000))
+ timerService.getClock().advanceTime(3, TimeUnit.SECONDS)
rulesFacts.removeExpiredTemporaryFacts()
then: "all temporary facts should still be present"
@@ -370,7 +368,7 @@ class BasicRulesFactsTest extends Specification {
assert rulesFacts.match(AnonFact).collect(Collectors.toList()).contains(anonFact3)
when: "the clock is advanced and temporary facts are expired"
- rulesFacts.setClock(new RulesClock(6000))
+ timerService.getClock().advanceTime(3, TimeUnit.SECONDS)
rulesFacts.removeExpiredTemporaryFacts()
then: "some temporary facts should still be present"
@@ -381,7 +379,7 @@ class BasicRulesFactsTest extends Specification {
assert rulesFacts.match(AnonFact, { fact -> fact.baz }).count() == 1
when: "the clock is advanced and temporary facts are expired"
- rulesFacts.setClock(new RulesClock(12000))
+ timerService.getClock().advanceTime(6, TimeUnit.SECONDS)
rulesFacts.removeExpiredTemporaryFacts()
then: "some temporary facts should still be present"
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
index 03fd8c064..6e00a4901 100644
--- a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
@@ -4,11 +4,13 @@ import com.fasterxml.jackson.databind.node.ObjectNode
import com.google.firebase.messaging.Message
import net.fortuna.ical4j.model.Recur
import org.openremote.container.timer.TimerService
+import org.openremote.container.util.UniqueIdentifierGenerator
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
import org.openremote.manager.notification.EmailNotificationHandler
import org.openremote.manager.notification.NotificationService
import org.openremote.manager.notification.PushNotificationHandler
+import org.openremote.manager.rules.JsonRulesBuilder
import org.openremote.manager.rules.RulesEngine
import org.openremote.manager.rules.RulesService
import org.openremote.manager.rules.RulesetDeployment
@@ -16,6 +18,10 @@ import org.openremote.manager.rules.RulesetStorageService
import org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapter
import org.openremote.manager.setup.SetupService
import org.openremote.model.asset.UserAssetLink
+import org.openremote.model.asset.impl.ThingAsset
+import org.openremote.model.attribute.Attribute
+import org.openremote.model.rules.json.JsonRule
+import org.openremote.model.value.ValueType
import org.openremote.test.setup.KeycloakTestSetup
import org.openremote.test.setup.ManagerTestSetup
import org.openremote.model.asset.Asset
@@ -41,8 +47,10 @@ import org.simplejavamail.email.Email
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
+import java.time.Duration
import java.time.Instant
import java.time.temporal.ChronoUnit
+import java.util.concurrent.TimeUnit
import static java.util.concurrent.TimeUnit.HOURS
import static java.util.concurrent.TimeUnit.MILLISECONDS
@@ -489,4 +497,231 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
notificationService.notificationHandlerMap.put(pushNotificationHandler.getTypeName(), pushNotificationHandler)
}
}
+
+ def "Trigger actions based on the position of the sun"() {
+
+ given: "the rule firing delay time is set to a small value for testing"
+ def expirationMillis = TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS
+ TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS = 500
+
+ and: "the container environment is started"
+ def conditions = new PollingConditions(timeout: 15, delay: 0.2)
+ def container = startContainer(defaultConfig(), defaultServices())
+ def pushNotificationHandler = container.getService(PushNotificationHandler.class)
+ def emailNotificationHandler = container.getService(EmailNotificationHandler.class)
+ def notificationService = container.getService(NotificationService.class)
+ def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
+ def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)
+ def rulesService = container.getService(RulesService.class)
+ def rulesetStorageService = container.getService(RulesetStorageService.class)
+ def timerService = container.getService(TimerService.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
+ RulesEngine realmBuildingEngine
+
+ and: "a thing asset is added to the building realm"
+ def thingId = UniqueIdentifierGenerator.generateId("TestThing")
+ def thingAsset = new ThingAsset("TestThing")
+ .setId(thingId)
+ .setRealm(keycloakTestSetup.realmBuilding.name)
+ .setLocation(new GeoJSONPoint(0, 0))
+ .addAttributes(
+ new Attribute<>("sunset", ValueType.INTEGER, null),
+ new Attribute<>("sunriseWithOffset", ValueType.INTEGER, null),
+ new Attribute<>("twilightHorizon", ValueType.INTEGER, null),
+ )
+ thingAsset = assetStorageService.merge(thingAsset)
+
+ and: "the pseudo clock is stopped"
+ stopPseudoClock()
+
+ and: "a ruleset with sunset trigger condition is added whose action updates the thing asset"
+ def rulesStr = getClass().getResource("/org/openremote/test/rules/JsonRuleSunset.json").text
+ def rule = parse(rulesStr, JsonRulesetDefinition.class).orElseThrow()
+ Ruleset ruleset = new RealmRuleset(
+ keycloakTestSetup.realmBuilding.name,
+ "Sunset Rule",
+ Ruleset.Lang.JSON,
+ rulesStr)
+ ruleset = rulesetStorageService.merge(ruleset)
+ def sunsetCalculator = JsonRulesBuilder.getSunCalculator(rule.rules[0].when.groups[0].items[0].sun, timerService)
+ def sunTimes = sunsetCalculator.execute()
+ def lastFireTimestamp = 0
+
+ expect: "the rule engines to become available and be running with asset states inserted"
+ conditions.eventually {
+ realmBuildingEngine = rulesService.realmEngines.get(keycloakTestSetup.realmBuilding.name)
+ assert realmBuildingEngine != null
+ assert realmBuildingEngine.isRunning()
+ assert realmBuildingEngine.assetStates.size() == DEMO_RULE_STATES_SMART_BUILDING
+ assert realmBuildingEngine.lastFireTimestamp == timerService.getNow().toEpochMilli()
+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp
+ }
+
+ and: "the next sunset should be calculated and should be in the future"
+ assert sunTimes.getSet() != null
+ assert sunTimes.getSet().toInstant().isAfter(timerService.getNow())
+
+ and: "the rule should not have triggered"
+ conditions.eventually {
+ thingAsset = assetStorageService.find(thingId) as ThingAsset
+ assert thingAsset.getAttribute("sunset").get().getValue().orElse(0) == 0
+ }
+
+ when: "time advances slightly"
+ advancePseudoClock(1, TimeUnit.SECONDS, container)
+
+ then: "the rule engine should have fired again and the rule should not have triggered"
+ conditions.eventually {
+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp
+ assert realmBuildingEngine.lastFireTimestamp == timerService.getNow().toEpochMilli()
+ thingAsset = assetStorageService.find(thingId) as ThingAsset
+ assert thingAsset.getAttribute("sunset").get().getValue().orElse(0) == 0
+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp
+ }
+
+ when: "time advances slightly past the next sunset time and the rule engine fires"
+ advancePseudoClock(Duration.between(timerService.getNow(), sunTimes.getSet()).getSeconds()+1, TimeUnit.SECONDS, container)
+
+ then: "the rule engine should have fired again and the rule should have triggered"
+ conditions.eventually {
+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp
+ assert realmBuildingEngine.lastFireTimestamp == timerService.getNow().toEpochMilli()
+ thingAsset = assetStorageService.find(thingId) as ThingAsset
+ assert thingAsset.getAttribute("sunset").get().getValue().orElse(0) == 100
+ }
+
+ when: "the updated attribute is cleared"
+ thingAsset.getAttribute("sunset").get().setValue(null)
+ thingAsset = assetStorageService.merge(thingAsset)
+
+ and: "time advances past the next sunrise"
+ sunTimes = sunsetCalculator.on(sunTimes.getSet()).execute()
+ advancePseudoClock(Duration.between(timerService.getNow(), sunTimes.getRise()).getSeconds(), TimeUnit.SECONDS, container)
+
+ then: "the rule engine should have fired again and the rule should not have triggered"
+ conditions.eventually {
+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp
+ assert realmBuildingEngine.lastFireTimestamp == timerService.getNow().toEpochMilli()
+ thingAsset = assetStorageService.find(thingId) as ThingAsset
+ assert thingAsset.getAttribute("sunset").get().getValue().orElse(0) == 0
+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp
+ }
+
+ when: "time advances slightly past the next sunset time and the rule engine fires"
+ advancePseudoClock(Duration.between(timerService.getNow(), sunTimes.getSet()).getSeconds()+1, TimeUnit.SECONDS, container)
+
+ then: "the rule engine should have fired again and the rule should have triggered"
+ conditions.eventually {
+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp
+ assert realmBuildingEngine.lastFireTimestamp == timerService.getNow().toEpochMilli()
+ thingAsset = assetStorageService.find(thingId) as ThingAsset
+ assert thingAsset.getAttribute("sunset").get().getValue().orElse(0) == 100
+ }
+
+ when: "a ruleset with sunrise offset trigger condition is added whose action updates the thing asset"
+ rulesStr = getClass().getResource("/org/openremote/test/rules/JsonRuleSunriseOffset.json").text
+ rule = parse(rulesStr, JsonRulesetDefinition.class).orElseThrow()
+ ruleset = new RealmRuleset(
+ keycloakTestSetup.realmBuilding.name,
+ "Sunrise with offset Rule",
+ Ruleset.Lang.JSON,
+ rulesStr)
+ ruleset = rulesetStorageService.merge(ruleset)
+ sunsetCalculator = JsonRulesBuilder.getSunCalculator(rule.rules[0].when.groups[0].items[0].sun, timerService)
+ sunTimes = sunsetCalculator.execute()
+
+ then: "the rule engines to become available and be running with asset states inserted"
+ conditions.eventually {
+ realmBuildingEngine = rulesService.realmEngines.get(keycloakTestSetup.realmBuilding.name)
+ assert realmBuildingEngine != null
+ assert realmBuildingEngine.isRunning()
+ assert realmBuildingEngine.assetStates.size() == DEMO_RULE_STATES_SMART_BUILDING
+ assert realmBuildingEngine.lastFireTimestamp == timerService.getNow().toEpochMilli()
+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp
+ }
+
+ and: "the next sunrise should be calculated and should be in the future"
+ assert sunTimes.getRise() != null
+ assert sunTimes.getRise().toInstant().isAfter(timerService.getNow())
+
+ and: "the rule should not have triggered"
+ conditions.eventually {
+ thingAsset = assetStorageService.find(thingId) as ThingAsset
+ assert thingAsset.getAttribute("sunriseWithOffset").get().getValue().orElse(0) == 0
+ }
+
+ when: "time advances slightly past the next sunrise time and the rule engine fires"
+ advancePseudoClock(Duration.between(timerService.getNow(), sunTimes.getRise()).getSeconds()+1, TimeUnit.SECONDS, container)
+
+ then: "the rule engine should have fired again and the rule should not have triggered"
+ conditions.eventually {
+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp
+ assert realmBuildingEngine.lastFireTimestamp == timerService.getNow().toEpochMilli()
+ thingAsset = assetStorageService.find(thingId) as ThingAsset
+ assert thingAsset.getAttribute("sunriseWithOffset").get().getValue().orElse(0) == 0
+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp
+ }
+
+ when: "time advances past the offset delay and the rule engine fires"
+ advancePseudoClock(rule.rules[0].when.groups[0].items[0].sun.offsetMins, TimeUnit.MINUTES, container)
+
+ then: "the rule engine should have fired again and the rule should have triggered"
+ conditions.eventually {
+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp
+ assert realmBuildingEngine.lastFireTimestamp == timerService.getNow().toEpochMilli()
+ thingAsset = assetStorageService.find(thingId) as ThingAsset
+ assert thingAsset.getAttribute("sunriseWithOffset").get().getValue().orElse(0) == 100
+ }
+
+ when: "a ruleset with twilight trigger condition is added whose action updates the thing asset"
+ rulesStr = getClass().getResource("/org/openremote/test/rules/JsonRuleTwilight.json").text
+ rule = parse(rulesStr, JsonRulesetDefinition.class).orElseThrow()
+ ruleset = new RealmRuleset(
+ keycloakTestSetup.realmBuilding.name,
+ "Twilight Rule",
+ Ruleset.Lang.JSON,
+ rulesStr)
+ ruleset = rulesetStorageService.merge(ruleset)
+ sunsetCalculator = JsonRulesBuilder.getSunCalculator(rule.rules[0].when.groups[0].items[0].sun, timerService)
+ sunTimes = sunsetCalculator.execute()
+
+ then: "the rule engines to become available and be running with asset states inserted"
+ conditions.eventually {
+ realmBuildingEngine = rulesService.realmEngines.get(keycloakTestSetup.realmBuilding.name)
+ assert realmBuildingEngine != null
+ assert realmBuildingEngine.isRunning()
+ assert realmBuildingEngine.assetStates.size() == DEMO_RULE_STATES_SMART_BUILDING
+ assert realmBuildingEngine.lastFireTimestamp == timerService.getNow().toEpochMilli()
+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp
+ }
+
+ and: "the next twilight should be calculated and should be in the future"
+ assert sunTimes.getRise() != null
+ assert sunTimes.getRise().toInstant().isAfter(timerService.getNow())
+
+ and: "the rule should not have triggered"
+ conditions.eventually {
+ thingAsset = assetStorageService.find(thingId) as ThingAsset
+ assert thingAsset.getAttribute("twilightHorizon").get().getValue().orElse(0) == 0
+ }
+
+ when: "time advances slightly past the next occurrence time and the rule engine fires"
+ advancePseudoClock(Duration.between(timerService.getNow(), sunTimes.getRise()).getSeconds()+1, TimeUnit.SECONDS, container)
+
+ then: "the rule engine should have fired again and the rule should have triggered"
+ conditions.eventually {
+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp
+ assert realmBuildingEngine.lastFireTimestamp == timerService.getNow().toEpochMilli()
+ thingAsset = assetStorageService.find(thingId) as ThingAsset
+ assert thingAsset.getAttribute("twilightHorizon").get().getValue().orElse(0) == 100
+ }
+
+ cleanup: "static variables are reset"
+ TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS = expirationMillis
+ if (notificationService != null) {
+ notificationService.notificationHandlerMap.put(emailNotificationHandler.getTypeName(), emailNotificationHandler)
+ notificationService.notificationHandlerMap.put(pushNotificationHandler.getTypeName(), pushNotificationHandler)
+ }
+ }
}
diff --git a/test/src/test/resources/org/openremote/test/rules/JsonRuleSunriseOffset.json b/test/src/test/resources/org/openremote/test/rules/JsonRuleSunriseOffset.json
new file mode 100644
index 000000000..11794d374
--- /dev/null
+++ b/test/src/test/resources/org/openremote/test/rules/JsonRuleSunriseOffset.json
@@ -0,0 +1,41 @@
+{
+ "rules": [
+ {
+ "name": "Sunrise with offset Trigger Rule",
+ "when": {
+ "operator": "OR",
+ "groups": [
+ {
+ "operator": "AND",
+ "items": [
+ {
+ "sun": {
+ "position": "SUNRISE",
+ "offsetMins": 10,
+ "location": {
+ "type": "Point",
+ "coordinates": [0,0]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "then": [
+ {
+ "action": "write-attribute",
+ "target": {
+ "assets": {
+ "ids": [
+ "5laT6pWbZa9BHdPvzBHA7T"
+ ]
+ }
+ },
+ "value": 100,
+ "attributeName": "sunriseWithOffset"
+ }
+ ]
+ }
+ ]
+}
diff --git a/test/src/test/resources/org/openremote/test/rules/JsonRuleSunset.json b/test/src/test/resources/org/openremote/test/rules/JsonRuleSunset.json
new file mode 100644
index 000000000..a8598ae90
--- /dev/null
+++ b/test/src/test/resources/org/openremote/test/rules/JsonRuleSunset.json
@@ -0,0 +1,40 @@
+{
+ "rules": [
+ {
+ "name": "Sunset Trigger Rule",
+ "when": {
+ "operator": "OR",
+ "groups": [
+ {
+ "operator": "AND",
+ "items": [
+ {
+ "sun": {
+ "position": "SUNSET",
+ "location": {
+ "type": "Point",
+ "coordinates": [0,0]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "then": [
+ {
+ "action": "write-attribute",
+ "target": {
+ "assets": {
+ "ids": [
+ "5laT6pWbZa9BHdPvzBHA7T"
+ ]
+ }
+ },
+ "value": 100,
+ "attributeName": "sunset"
+ }
+ ]
+ }
+ ]
+}
diff --git a/test/src/test/resources/org/openremote/test/rules/JsonRuleTwilight.json b/test/src/test/resources/org/openremote/test/rules/JsonRuleTwilight.json
new file mode 100644
index 000000000..b545c19d0
--- /dev/null
+++ b/test/src/test/resources/org/openremote/test/rules/JsonRuleTwilight.json
@@ -0,0 +1,40 @@
+{
+ "rules": [
+ {
+ "name": "Sunrise with offset Trigger Rule",
+ "when": {
+ "operator": "OR",
+ "groups": [
+ {
+ "operator": "AND",
+ "items": [
+ {
+ "sun": {
+ "position": "TWILIGHT_HORIZON",
+ "location": {
+ "type": "Point",
+ "coordinates": [0,0]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "then": [
+ {
+ "action": "write-attribute",
+ "target": {
+ "assets": {
+ "ids": [
+ "5laT6pWbZa9BHdPvzBHA7T"
+ ]
+ }
+ },
+ "value": 100,
+ "attributeName": "twilightHorizon"
+ }
+ ]
+ }
+ ]
+}
diff --git a/test/src/test/resources/org/openremote/test/rules/ResidenceAutoVentilation.groovy b/test/src/test/resources/org/openremote/test/rules/ResidenceAutoVentilation.groovy
index 33fbb581f..9d1d1533a 100644
--- a/test/src/test/resources/org/openremote/test/rules/ResidenceAutoVentilation.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/ResidenceAutoVentilation.groovy
@@ -8,6 +8,7 @@ import org.openremote.model.query.AssetQuery
import org.openremote.model.query.AssetQuery.Operator
import org.openremote.model.rules.AssetState
+import java.time.temporal.ChronoUnit
import java.util.logging.Logger
import java.util.stream.Stream
@@ -80,7 +81,7 @@ Closure<Boolean> roomThresholdMatch =
new AssetQuery()
.ids(roomAboveBelowThreshold.id)
.attributeValue(attribute, above ? LESS_EQUALS : GREATER_THAN, threshold)
- ).filter(facts.clock.last(timeWindow)).count() == 0
+ ).filter{facts.clock.now.minus(12, ChronoUnit.MINUTES).toEpochMilli() < it.timestamp}.count() == 0
}.isPresent()
} else {
// if we don't have a room with max level (empty attribute?), it's always "below threshold"
diff --git a/test/src/test/resources/org/openremote/test/rules/ResidenceNotifyAlarmTrigger.groovy b/test/src/test/resources/org/openremote/test/rules/ResidenceNotifyAlarmTrigger.groovy
index 9557515bc..98ed8a7dc 100644
--- a/test/src/test/resources/org/openremote/test/rules/ResidenceNotifyAlarmTrigger.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/ResidenceNotifyAlarmTrigger.groovy
@@ -157,7 +157,7 @@ rules.add()
"ApartmentAlarm",
new PushNotificationMessage()
.setTitle("Apartment Alarm")
- .setBody("Aanwezigheid in " + alarmTrigger.roomName + " (" + facts.clock.time + ").")
+ .setBody("Aanwezigheid in " + alarmTrigger.roomName + " (" + facts.clock.now + ").")
.setButtons([
new PushNotificationButton("Details", new PushNotificationAction("#security")),
new PushNotificationButton("Alarm uit", PushNotificationAction.writeAttributeValueAction(new AttributeRef(alarmTrigger.residenceId, "alarmEnabled"), false))
diff --git a/test/src/test/resources/org/openremote/test/rules/ResidencePresenceDetection.groovy b/test/src/test/resources/org/openremote/test/rules/ResidencePresenceDetection.groovy
index 102234585..8ad894211 100644
--- a/test/src/test/resources/org/openremote/test/rules/ResidencePresenceDetection.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/ResidencePresenceDetection.groovy
@@ -16,6 +16,8 @@ import org.openremote.model.query.AssetQuery
import org.openremote.model.rules.AssetState
import org.openremote.model.util.Pair
+import java.time.temporal.ChronoUnit
+import java.util.concurrent.TimeUnit
import java.util.logging.Logger
import static org.openremote.model.query.AssetQuery.Operator.GREATER_THAN
@@ -100,7 +102,7 @@ rules.add()
// with increasing values
coLevelFact.getFact().isValueGreaterThanOldValue()
// in the last 12 minutes
- }.filter(facts.clock.last("12m")).count() == 0
+ }.filter{facts.clock.now.minus(12, ChronoUnit.MINUTES).toEpochMilli() < it.timestamp}.count() == 0
}.orElse(true) // or we don't have a CO2 sensor
}.orElse(false)
diff --git a/test/src/test/resources/org/openremote/test/rules/ResidenceSmartSwitch.groovy b/test/src/test/resources/org/openremote/test/rules/ResidenceSmartSwitch.groovy
index af5bd08ef..e37e9669c 100644
--- a/test/src/test/resources/org/openremote/test/rules/ResidenceSmartSwitch.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/ResidenceSmartSwitch.groovy
@@ -121,7 +121,7 @@ rules.add()
// User-provided begin/end time of cycle
beginEnd.flatMap { it.value}.filter {
// is now or in future
- it >= facts.clock.timestamp
+ it >= facts.clock.currentTimeMillis
}.map { expectedStartTime ->
// and actuator start time attribute
def startTime = beginEnd.flatMap {
@@ -173,7 +173,7 @@ rules.add()
// User-provided begin/end time of cycle
beginEnd.flatMap { it.value}.filter {
// allows the cycle to complete in future
- (it - CYCLE_TIME_MILLISECONDS) >= facts.clock.timestamp
+ (it - CYCLE_TIME_MILLISECONDS) >= facts.clock.currentTimeMillis
}.map { expectedStopTime ->
// and actuator stop time attribute
def stopTime = beginEnd.flatMap {
@@ -195,7 +195,7 @@ rules.add()
{ facts ->
AssetState<Long> beginEnd = facts.bound("beginEnd")
// Start time is current time (in seconds)
- def startMilliseconds = facts.clock.timestamp
+ def startMilliseconds = facts.clock.currentTimeMillis
// Stop time is user-provided smart switch time (in seconds)
def stopMilliseconds = beginEnd.value.orElse(0l)
LOG.info("Smart switch mode is READY_AT, enabling actuator with start/stop times " +
@@ -222,7 +222,7 @@ rules.add()
}.filter { stopTime ->
// Actuator stop time attribute is present and value (in seconds) is not zero and in the past
stopTime.flatMap { it.value}.map {
- it > 0 && it < facts.clock.timestamp
+ it > 0 && it < facts.clock.currentTimeMillis
}.orElse(false)
}.findFirst().map { stopTime ->
facts.bind("stopTime", stopTime.get())
diff --git a/test/src/test/resources/org/openremote/test/rules/ResidenceVacationMode.groovy b/test/src/test/resources/org/openremote/test/rules/ResidenceVacationMode.groovy
index f2b377222..b8dc8d2ee 100644
--- a/test/src/test/resources/org/openremote/test/rules/ResidenceVacationMode.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/ResidenceVacationMode.groovy
@@ -32,7 +32,7 @@ rules.add()
{ facts ->
facts.matchAssetState(
new AssetQuery().types(BuildingAsset)
- .attributeValue("vacationUntil", GREATER_THAN, facts.clock.timestamp)
+ .attributeValue("vacationUntil", GREATER_THAN, facts.clock.currentTimeMillis)
).filter { residenceWithVacationUntil ->
facts.match(VacationMode).noneMatch {
vacationMode -> vacationMode.residenceId == residenceWithVacationUntil.id
@@ -51,7 +51,7 @@ rules.add()
)
LOG.info("Vacation mode enabled: " + vacationMode)
- def vacationModeExpiresMillis = vacationMode.until - facts.clock.timestamp
+ def vacationModeExpiresMillis = vacationMode.until - facts.clock.currentTimeMillis
facts.putTemporary(vacationModeExpiresMillis, vacationMode)
facts.updateAssetState(vacationMode.residenceId, "dayScene", REQUEST_START)
@@ -64,7 +64,7 @@ rules.add()
{ facts ->
facts.matchAssetState(
new AssetQuery().types(BuildingAsset)
- .attributeValue("vacationUntil", LESS_EQUALS, facts.clock.timestamp)
+ .attributeValue("vacationUntil", LESS_EQUALS, facts.clock.currentTimeMillis)
).filter { residenceWithVacationUntilInPast ->
residenceWithVacationUntilInPast.getValueAs(Double.class).isPresent()
}.filter { residenceWithVacationUntilInPast ->