100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Added support for duration in When-Then LHS conditions (#1534)
Dominique Kleevenf72f79fc6723
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.javaindex 9419dcba7..362cee635 100644--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java@@ -20,7 +20,6 @@package org.openremote.manager.rules;import jakarta.ws.rs.core.MediaType;-import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.AssetStorageService;import org.openremote.model.PersistenceEvent;@@ -30,6 +29,7 @@ import org.openremote.model.asset.UserAssetLink;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeInfo;import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.MetaMap;import org.openremote.model.geo.GeoJSONPoint;import org.openremote.model.notification.*;import org.openremote.model.query.AssetQuery;@@ -38,11 +38,9 @@ import org.openremote.model.query.UserQuery;import org.openremote.model.query.filter.AttributePredicate;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.util.*;import org.openremote.model.value.MetaItemType;+import org.openremote.model.value.NameValueHolder;import org.openremote.model.webhook.Webhook;import org.quartz.CronExpression;import org.shredzone.commons.suncalc.SunTimes;@@ -51,6 +49,7 @@ import java.time.ZonedDateTime;import java.time.temporal.ChronoUnit;import java.util.*;import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicLong;import java.util.concurrent.atomic.AtomicReference;@@ -61,6 +60,7 @@ import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger;import java.util.stream.Collectors;+import java.util.stream.IntStream;import java.util.stream.Stream;import static org.openremote.manager.rules.AssetQueryPredicate.groupIsEmpty;@@ -79,7 +79,6 @@ public class JsonRulesBuilder extends RulesBuilder {}}-/*** Stores all state for a given {@link RuleCondition} and calculates which {@link AttributeInfo}s match and don't* match the condition.@@ -93,6 +92,7 @@ public class JsonRulesBuilder extends RulesBuilder {int limit;LogicGroup<AttributePredicate> attributePredicates = null;Function<Collection<AttributeInfo>, Set<AttributeInfo>> assetPredicate = null;+ Map<Pair<AttributeInfo, Integer>, Long> durationMatchTimes = new HashMap<>();Set<AttributeInfo> unfilteredAssetStates = new HashSet<>();Set<AttributeInfo> previouslyMatchedAssetStates = new HashSet<>();Set<AttributeInfo> previouslyUnmatchedAssetStates;@@ -109,24 +109,7 @@ public class JsonRulesBuilder extends RulesBuilder {previouslyUnmatchedAssetStates = new HashSet<>();}- if (!TextUtil.isNullOrEmpty(ruleCondition.duration)) {- try {- 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)) {+ if (!TextUtil.isNullOrEmpty(ruleCondition.cron)) {try {CronExpression timerExpression = new CronExpression(ruleCondition.cron);timerExpression.setTimeZone(TimeZone.getTimeZone("UTC"));@@ -184,17 +167,21 @@ public class JsonRulesBuilder extends RulesBuilder {return false;};} else if (ruleCondition.assets != null) {-// Pull out order, limit and attribute predicates so they can be applied at required timesorderBy = ruleCondition.assets.orderBy;limit = ruleCondition.assets.limit;attributePredicates = ruleCondition.assets.attributes;+ boolean attributePredicateHasDurationCondition = ruleCondition.duration != null && !ruleCondition.duration.isEmpty();if (attributePredicates != null && attributePredicates.items != null) {// Only supports a single level or logic group for attributes (i.e. cannot nest groups in the UI so// don't support it here either)attributePredicates.groups = null;- assetPredicate = AssetQueryPredicate.asAttributeMatcher(timerService::getCurrentTimeMillis, attributePredicates);+ if (attributePredicateHasDurationCondition) {+ assetPredicate = asAttributeMatcher(timerService::getCurrentTimeMillis, attributePredicates.getItems(), ruleCondition.duration, durationMatchTimes);+ } else {+ assetPredicate = AssetQueryPredicate.asAttributeMatcher(timerService::getCurrentTimeMillis, attributePredicates);+ }}ruleCondition.assets.orderBy = null;ruleCondition.assets.limit = 0;@@ -223,7 +210,12 @@ public class JsonRulesBuilder extends RulesBuilder {unfilteredAssetStates.add(event.assetState);}}- case DELETE -> unfilteredAssetStates.remove(event.assetState);+ case DELETE -> {+ unfilteredAssetStates.remove(event.assetState);+ if (durationMatchTimes != null) {+ durationMatchTimes.keySet().removeIf(attributeRefPredicateIndex -> attributeRefPredicateIndex.getKey().getRef().equals(event.assetState.getRef()));+ }+ }}}@@ -286,15 +278,19 @@ public class JsonRulesBuilder extends RulesBuilder {results.put(true, matched);results.put(false, unmatched);- unfilteredAssetStates.stream().collect(Collectors.groupingBy(AttributeInfo::getId)).forEach((id, states) -> {- Set<AttributeInfo> matches = assetPredicate.apply(states);- if (matches != null) {- matched.addAll(matches);- unmatched.addAll(states.stream().filter(matches::contains).collect(Collectors.toSet()));- } else {- unmatched.addAll(states);- }- });+ unfilteredAssetStates.stream()+ .collect(Collectors.groupingBy(AttributeInfo::getId))+ .forEach((id, states) -> {+ Set<AttributeInfo> matches = assetPredicate.apply(states);+ if (matches != null) {+ matched.addAll(matches);+ unmatched.addAll(states.stream()+ .filter(state -> !matches.contains(state))+ .collect(Collectors.toSet()));+ } else {+ unmatched.addAll(states);+ }+ });matchedAssetStates = results.getOrDefault(true, Collections.emptyList());unmatchedAssetStates = results.getOrDefault(false, Collections.emptyList());@@ -306,7 +302,6 @@ public class JsonRulesBuilder extends RulesBuilder {// Filter out previous un-matches to avoid re-triggeringunmatchedAssetStates.removeIf(previouslyUnmatchedAssetStates::contains);-}}@@ -360,9 +355,9 @@ public class JsonRulesBuilder extends RulesBuilder {// Filter out unmatched asset ids that are in the matched listunmatchedAssetIds = unmatchedAssetStateStream- .map(AttributeInfo::getId)- .filter(id -> !matchedAssetIds.contains(id))- .collect(Collectors.toList());+ .map(AttributeInfo::getId)+ .filter(id -> !matchedAssetIds.contains(id))+ .collect(Collectors.toList());}lastEvaluationResult = new RuleConditionEvaluationResult((!matchedAssetIds.isEmpty() || (trackUnmatched && !unmatchedAssetIds.isEmpty())), matchedAssetStates, matchedAssetIds, unmatchedAssetStates, unmatchedAssetIds);@@ -407,12 +402,12 @@ public class JsonRulesBuilder extends RulesBuilder {@Overridepublic String toString() {return RuleConditionEvaluationResult.class.getSimpleName() + "{" +- "matches=" + matches +- ", matchedAssetStates=" + matchedAssetStates.size() +- ", unmatchedAssetStates=" + unmatchedAssetStates.size() +- ", matchedAssetIds=" + matchedAssetIds.size() +- ", unmatchedAssetIds=" + unmatchedAssetIds.size() +- '}';+ "matches=" + matches ++ ", matchedAssetStates=" + matchedAssetStates.size() ++ ", unmatchedAssetStates=" + unmatchedAssetStates.size() ++ ", matchedAssetIds=" + matchedAssetIds.size() ++ ", unmatchedAssetIds=" + unmatchedAssetIds.size() ++ '}';}}@@ -631,10 +626,10 @@ public class JsonRulesBuilder extends RulesBuilder {}add().name(rule.name)- .description(rule.description)- .priority(rule.priority)- .when(condition)- .then(action);+ .description(rule.description)+ .priority(rule.priority)+ .when(condition)+ .then(action);return this;}@@ -804,7 +799,7 @@ public class JsonRulesBuilder extends RulesBuilder {action.setUrl(newUrl);pushMsg.setAction(action);}-+if (pushMsg.getBody() != null) {String newBody = replaceAssetIdPlaceholder(pushMsg.getBody(), ruleState, useUnmatched, "notification body", false);pushMsg.setBody(newBody);@@ -878,7 +873,7 @@ public class JsonRulesBuilder extends RulesBuilder {// Check if the body containers the PLACEHOLDER_TRIGGER_ASSETSif(isLocalized) {bodyContainsTriggeredAssetInfo = localizedBodies.values().stream().anyMatch(- text -> !TextUtil.isNullOrEmpty(text) && text.contains(PLACEHOLDER_TRIGGER_ASSETS));+ text -> !TextUtil.isNullOrEmpty(text) && text.contains(PLACEHOLDER_TRIGGER_ASSETS));} else {bodyContainsTriggeredAssetInfo = !TextUtil.isNullOrEmpty(body) && body.contains(PLACEHOLDER_TRIGGER_ASSETS);}@@ -938,7 +933,7 @@ public class JsonRulesBuilder extends RulesBuilder {customNotifications.forEach(customNotification -> {log(Level.FINE, "Sending custom user notification for rule action: " + rule.name + " '" + actionsName + "' action index " + index + " [Targets=" + (customNotification.getTargets() != null ? customNotification.getTargets().stream().map(Object::toString).collect(Collectors.joining(",")) : "null") + "]");notificationsFacade.send(customNotification);- }), 0);+ }), 0);}} else {targetIds = getRuleActionTargetIds(ruleAction.target, useUnmatched, ruleState, assetsFacade, usersFacade, facts);@@ -1054,8 +1049,8 @@ public class JsonRulesBuilder extends RulesBuilder {log(Level.FINE, "Writing attribute '" + attributeAction.attributeName + "' for " + ids.size() + " asset(s) for rule action: " + rule.name + " '" + actionsName + "' action index " + index);return new RuleActionExecution(() ->- ids.forEach(id ->- assetsFacade.dispatch(id, attributeAction.attributeName, attributeAction.value)), 0);+ ids.forEach(id ->+ assetsFacade.dispatch(id, attributeAction.attributeName, attributeAction.value)), 0);}if (ruleAction instanceof RuleActionWait) {@@ -1102,12 +1097,12 @@ public class JsonRulesBuilder extends RulesBuilder {List<AttributeInfo> matchingAssetStates = matchingAssetIds.stream().map(assetId ->- facts.getAssetStates()- .stream()- .filter(state -> state.getId().equals(assetId) && state.getName().equals(attributeUpdateAction.attributeName))- .findFirst().orElseGet(() -> {- log(Level.WARNING, "Failed to find attribute in rule states for attribute update: " + new AttributeRef(assetId, attributeUpdateAction.attributeName));- return null;+ facts.getAssetStates()+ .stream()+ .filter(state -> state.getId().equals(assetId) && state.getName().equals(attributeUpdateAction.attributeName))+ .findFirst().orElseGet(() -> {+ log(Level.WARNING, "Failed to find attribute in rule states for attribute update: " + new AttributeRef(assetId, attributeUpdateAction.attributeName));+ return null;})).filter(Objects::nonNull).collect(Collectors.toList());@@ -1187,7 +1182,7 @@ public class JsonRulesBuilder extends RulesBuilder {assetsFacade.dispatch(assetState.getId(), attributeUpdateAction.attributeName, value);}}),- 0);+ 0);}log(Level.FINE, "Unsupported rule action: " + rule.name + " '" + actionsName + "' action index " + index);@@ -1239,23 +1234,23 @@ public class JsonRulesBuilder extends RulesBuilder {if (TextUtil.isNullOrEmpty(text) || !text.contains(PLACEHOLDER_ASSET_ID)) {return text;}-+Set<String> matchedIds = useUnmatched ? ruleState.otherwiseMatchedAssetIds : ruleState.thenMatchedAssetIds;if (matchedIds != null && !matchedIds.isEmpty()) {String replacement = firstOnly ? matchedIds.iterator().next() : String.join(",", matchedIds);-+String result = text.replace(PLACEHOLDER_ASSET_ID, replacement);log(Level.FINEST, "Replaced asset ID(s) in " + context + ": " + result);- return result;+ return result;} else {log(Level.WARNING, "Asset ID placeholder used but no matched assets found for " + context);return text;}}--++protected String insertTriggeredAssetInfo(String sourceText, Map<String, Set<AttributeInfo>> assetStates, boolean isHtml, boolean isJson) {StringBuilder sb = new StringBuilder();@@ -1353,12 +1348,12 @@ public class JsonRulesBuilder extends RulesBuilder {if (conditionStateMap != null) {if (!useUnmatched) {return conditionStateMap.values().stream().flatMap(triggerState ->- triggerState != null ? triggerState.getMatchedAssetIds().stream() : Stream.empty()+ triggerState != null ? triggerState.getMatchedAssetIds().stream() : Stream.empty()).distinct().collect(Collectors.toList());}return conditionStateMap.values().stream().flatMap(triggerState ->- triggerState != null ? triggerState.getUnmatchedAssetIds().stream() : Stream.empty()+ triggerState != null ? triggerState.getUnmatchedAssetIds().stream() : Stream.empty()).distinct().collect(Collectors.toList());}@@ -1397,9 +1392,9 @@ public class JsonRulesBuilder extends RulesBuilder {}SunTimes.Parameters sunCalculator = SunTimes.compute()- .on(timerService.getNow())- .utc()- .at(location.getX(), location.getY());+ .on(timerService.getNow())+ .utc()+ .at(location.getX(), location.getY());if (twilight != null) {sunCalculator.twilight(twilight);@@ -1407,4 +1402,99 @@ public class JsonRulesBuilder extends RulesBuilder {return sunCalculator;}+++ /**+ * Creates a function that matches attributes similar to {@link AssetQueryPredicate#asAttributeMatcher},+ * but with duration logic applied per {@link AttributePredicate} and only supports a single list of predicates.+ */+ @SuppressWarnings("unchecked")+ protected static Function<Collection<AttributeInfo>, Set<AttributeInfo>> asAttributeMatcher(Supplier<Long> currentMillisProducer, List<AttributePredicate> attributePredicates, Map<Integer, String> predicateDurationStrings, Map<Pair<AttributeInfo, Integer>, Long> durationMatchTimes) {+ if (attributePredicates == null || attributePredicates.isEmpty()) {+ return as -> Collections.EMPTY_SET;+ }++ List<Pair<Predicate<AttributeInfo>, Long>> attributePredicatesAndDurations = IntStream.range(0, attributePredicates.size()).mapToObj(i -> {+ AttributePredicate p = attributePredicates.get(i);+ Long predicateDuration = null;++ // Parse duration string only once during build not each time during eval for each asset state as this is computationally expensive+ if (predicateDurationStrings != null && predicateDurationStrings.get(i) != null) {+ String durationStr = predicateDurationStrings.get(i);+ predicateDuration = TimeUtil.parseTimeDuration(durationStr);+ }++ Predicate<AttributeInfo> predicate = (Predicate<AttributeInfo>) (Predicate) AssetQueryPredicate.asPredicate(currentMillisProducer, p);++ if (p.meta != null) {+ final Predicate<NameValueHolder<?>> innerMetaPredicate = Arrays.stream(p.meta)+ .map(metaPred -> AssetQueryPredicate.asPredicate(currentMillisProducer, metaPred))+ .reduce(x -> true, Predicate::and);++ predicate = predicate.and(assetState -> {+ MetaMap metaItems = assetState.getMeta();+ return metaItems.stream().anyMatch(metaItem ->+ innerMetaPredicate.test(assetState)+ );+ });+ }++ if (p.previousValue != null) {+ Predicate<Object> innerOldValuePredicate = p.previousValue.asPredicate(currentMillisProducer);+ predicate = predicate.and(nameValueHolder -> innerOldValuePredicate.test(nameValueHolder.getOldValue()));+ }++ return new Pair<>(predicate, predicateDuration);+ }).toList();+++ return assetStates -> {+ Set<AttributeInfo> matchedAssetStates = new HashSet<>();+ // Can't just fail on first nonmatch as we need to keep duration times up to date for each predicate+ boolean allPredicatesMatch = IntStream.range(0, attributePredicatesAndDurations.size()).mapToObj(i -> {+ Pair<Predicate<AttributeInfo>, Long> predicateAndDuration = attributePredicatesAndDurations.get(i);+ Long duration = predicateAndDuration.getValue();++ if (duration == null) {+ // Find the first match as an attribute predicate shouldn't match more than one asset state+ return assetStates.stream().filter(predicateAndDuration.getKey()).findFirst().map(matchedAssetState -> {+ matchedAssetStates.add(matchedAssetState);+ return true;+ }).orElse(false);+ } else {+ AtomicBoolean matchFound = new AtomicBoolean();+ // Need to clear any duration timer for each asset state that doesn't match+ assetStates.forEach(assetState -> {+ if (predicateAndDuration.getKey().test(assetState)) {+ boolean durationMatches = false;++ Pair<AttributeInfo, Integer> assetStatePredicateIndex = new Pair<>(assetState, i);+ // Look for existing duration end time+ Long previousMatchTime = durationMatchTimes.get(assetStatePredicateIndex);++ if (previousMatchTime != null) {+ // Check if previous match time is longer than duration millis ago+ durationMatches = previousMatchTime + duration <= currentMillisProducer.get();+ } else {+ // Insert the current time for this asset state and predicate index+ durationMatchTimes.put(assetStatePredicateIndex, currentMillisProducer.get());+ }++ // Store first match+ if (durationMatches && !matchFound.get()) {+ matchFound.set(true);+ matchedAssetStates.add(assetState);+ }+ } else {+ durationMatchTimes.remove(new Pair<>(assetState, i));+ }+ });++ return matchFound.get();+ }+ }).filter(predicateMatches -> predicateMatches.equals(true))+ .count() == attributePredicatesAndDurations.size();+ return allPredicatesMatch ? matchedAssetStates : null;+ };+ }}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.javaindex 233b7b019..67e8db0ae 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@@ -22,10 +22,11 @@ package org.openremote.model.rules.json;import org.openremote.model.query.AssetQuery;import org.openremote.model.rules.SunPositionTrigger;+import java.util.Map;+/*** Consists of one of the following triggers in order of precedence:* <ol>- * <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. "*/5 * * * *") in UTC 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.attribute.AttributeInfo}s@@ -34,15 +35,18 @@ import org.openremote.model.rules.SunPositionTrigger;* returned after applying the query.</li>* </ol>* <p>+ * The {@link #duration} map tracks attribute predicates and their required duration thresholds. A predicate with a duration+ * is only considered true after it has continuously remained true for its specified duration period.+ * <p>* The {@link #tag} is used to name the {@link org.openremote.model.asset.Asset}s that are filtered by the query and can* be used in the rule RHS to perform actions on these specific assets.*/public class RuleCondition {/**- * ISO8601 duration expression (e.g. PT1H)+ * Map of attribute and ISO8601 duration expression (e.g. PT1H)*/- public String duration;+ public Map<Integer, String> duration;/*** CRON expression in UTC (e.g. */5 * * * *)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.groovyindex 7505ce5b4..496336673 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@@ -30,6 +30,7 @@ import org.openremote.model.asset.Assetimport org.openremote.model.asset.UserAssetLinkimport org.openremote.model.asset.impl.ConsoleAssetimport org.openremote.model.asset.impl.ThingAsset+import org.openremote.model.asset.impl.LightAssetimport org.openremote.model.attribute.Attributeimport org.openremote.model.attribute.AttributeEventimport org.openremote.model.attribute.MetaItem@@ -692,6 +693,423 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {}}+ def "Trigger actions when attribute conditions match for specified durations"() {++ given: "the container environment is started"+ def conditions = new PollingConditions(timeout: 15, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())+ 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)+ RulesEngine realmBuildingEngine++ and: "the pseudo clock is stopped"+ stopPseudoClock()++ when: "a light asset is added to the building realm"+ def lightId = UniqueIdentifierGenerator.generateId("TestLight")+ def lightAsset = new LightAsset("TestLight")+ .setId(lightId)+ .setRealm(keycloakTestSetup.realmBuilding.name)+ .setLocation(new GeoJSONPoint(0, 0))+++ def ruleState = new MetaItem<>(MetaItemType.RULE_STATE)+ lightAsset.getAttributes().get("brightness").get().addMeta(ruleState)+ lightAsset.getAttributes().get("onOff").get().addMeta(ruleState)+ lightAsset.getAttributes().get("notes").get().addMeta(ruleState)+ assetStorageService.merge(lightAsset)++ then: "the light asset should be present"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light != null+ }++ when: "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))+ thingAsset.getAttributes().get("notes").get().addMeta(ruleState)+ thingAsset = assetStorageService.merge(thingAsset)++ then: "the thing asset should be present"+ conditions.eventually {+ def thing = assetStorageService.find(thingId)+ assert thing != null+ }++ // RuleSet: WHEN:+ // Any light asset has brightness higher than 50 for 5 minutes and onOff is true+ // AND+ // Any thing asset has notes set to "Test"+ // OR+ // Any light asset has a note that equals "TriggerDuration" for 10 minutes+ // THEN:+ // Set the notes of the light asset to "Triggered"++ when: "a ruleset with a duration map has been added"+ def rulesStr = getClass().getResource("/org/openremote/test/rules/JsonAttributeDurationRule.json").text+ def rule = parse(rulesStr, JsonRulesetDefinition.class).orElseThrow()+ Ruleset ruleset = new RealmRuleset(+ keycloakTestSetup.realmBuilding.name,+ "Duration Rule",+ Ruleset.Lang.JSON,+ rulesStr)+ ruleset = rulesetStorageService.merge(ruleset)+ def lastFireTimestamp = 0++ 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.facts.assetStates.size() == DEMO_RULE_STATES_SMART_BUILDING + 4 // 4 additional rule states+ assert realmBuildingEngine.lastFireTimestamp == timerService.getNow().toEpochMilli()+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ when: "the light asset is updated with brightness set to 100"+ lightAsset = assetStorageService.find(lightId)+ lightAsset.getAttribute("brightness").get().setValue(100)+ assetStorageService.merge(lightAsset)++ then: "the brightness value should be 100"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("brightness").get().getValue().orElse(0) == 100+ }++ when: "time advances for 6 seconds"+ advancePseudoClock(6, TimeUnit.SECONDS, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should still have its notes attribute be empty"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == ""+ }++ when: "the thing asset is updated with notes set to Test"+ thingAsset = assetStorageService.find(thingId)+ thingAsset.getAttribute("notes").get().setValue("Test")+ assetStorageService.merge(thingAsset)++ then: "the thing asset should have its notes set to Test"+ conditions.eventually {+ def thing = assetStorageService.find(thingId)+ assert thing.getAttribute("notes").get().getValue().orElse("") == "Test"+ }++ when: "time advances by 6 seconds"+ advancePseudoClock(6, TimeUnit.SECONDS, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should still have its notes attribute be empty"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == ""+ }++ when: "time advances for 5 minutes"+ advancePseudoClock(5, TimeUnit.MINUTES, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should have its notes attribute be empty" // because onOff is still false+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == ""+ }++ when: "the light asset is updated with onOff set to true"+ lightAsset = assetStorageService.find(lightId)+ lightAsset.getAttribute("onOff").get().setValue(true)+ assetStorageService.merge(lightAsset)++ then: "the light asset should have its onOff attribute set to true"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("onOff").get().getValue().orElse(false) == true+ }++ when: "time advances for 6 seconds"+ advancePseudoClock(6, TimeUnit.SECONDS, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should have its notes attribute set to Triggered" // because onOff was set to true, and brightness was above 50 for 5 minutes and the thing asset notes was set to Test+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == "Triggered"+ }++ when: "the light asset notes is updated to empty"+ lightAsset = assetStorageService.find(lightId)+ lightAsset.getAttribute("notes").get().setValue("")+ assetStorageService.merge(lightAsset)++ then: "the light asset should have its notes attribute be empty"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == ""+ }++ when: "time advances for 10 minutes"+ advancePseudoClock(10, TimeUnit.MINUTES, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should have its notes attribute be empty"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == ""+ }+++ when: "the light asset notes is updated to TriggerDuration"+ lightAsset = assetStorageService.find(lightId)+ lightAsset.getAttribute("notes").get().setValue("TriggerDuration")+ assetStorageService.merge(lightAsset)++ then: "the light asset should have its notes attribute be TriggerDuration"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == "TriggerDuration"+ }+++ // Start OR condition part+ when: "time advances for 6 seconds"+ advancePseudoClock(6, TimeUnit.SECONDS, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should have its notes attribute be TriggerDuration"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == "TriggerDuration"+ }++ when: "time advances for 10 minutes"+ advancePseudoClock(10, TimeUnit.MINUTES, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should have its notes attribute be Triggered" // because the OR condition was satisfied (thing asset notes was set to Test for 10 minutes)+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == "Triggered"+ }++ when: "the light asset notes and brightness are updated and thing asset notes is updated to empty"+ lightAsset = assetStorageService.find(lightId)+ lightAsset.getAttribute("notes").get().setValue("")+ lightAsset.getAttribute("brightness").get().setValue(0)+ thingAsset = assetStorageService.find(thingId)+ thingAsset.getAttribute("notes").get().setValue("")+ assetStorageService.merge(lightAsset)+ assetStorageService.merge(thingAsset)++ then: "the light asset should have its notes attribute be empty"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == ""+ assert light.getAttribute("brightness").get().getValue().orElse(0) == 0+ def thing = assetStorageService.find(thingId)+ assert thing.getAttribute("notes").get().getValue().orElse("") == ""+ }++ when: "time advances for 1 minute"+ advancePseudoClock(1, TimeUnit.MINUTES, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should have its notes empty abd brightness set to 0 and thing asset notes set to empty"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == ""+ assert light.getAttribute("brightness").get().getValue().orElse(0) == 0+ def thing = assetStorageService.find(thingId)+ assert thing.getAttribute("notes").get().getValue().orElse("") == ""+ }++ when: "time advances for 6 seconds"+ advancePseudoClock(6, TimeUnit.SECONDS, container)++ then: "the rule engine should have fired and"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ when: "light asset brightness is updated to 100 and thing asset notes is updated to Test"+ lightAsset = assetStorageService.find(lightId)+ lightAsset.getAttribute("brightness").get().setValue(100)+ thingAsset = assetStorageService.find(thingId)+ thingAsset.getAttribute("notes").get().setValue("Test")+ assetStorageService.merge(lightAsset)+ assetStorageService.merge(thingAsset)++ then: "the light asset should have its brightness set to 100"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("brightness").get().getValue().orElse(0) == 100+ def thing = assetStorageService.find(thingId)+ assert thing.getAttribute("notes").get().getValue().orElse("") == "Test"+ }++ when: "time advances for 6 seconds"+ advancePseudoClock(6, TimeUnit.SECONDS, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should have its notes attribute be empty"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == ""+ }++ when: "time advances for 3 minutes"+ advancePseudoClock(3, TimeUnit.MINUTES, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should have its notes attribute be empty"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == ""+ }++ when: "brightness is updated to 0"+ lightAsset = assetStorageService.find(lightId)+ lightAsset.getAttribute("brightness").get().setValue(0)+ assetStorageService.merge(lightAsset)++ then: "the light asset should have its brightness set to 0" // this is done to reset the duration of the matched state+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("brightness").get().getValue().orElse(0) == 0+ }++ when: "time advances for 6 seconds"+ advancePseudoClock(6, TimeUnit.SECONDS, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should have its notes attribute be empty"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == ""+ }++ when: "brightness is updated to 100"+ lightAsset = assetStorageService.find(lightId)+ lightAsset.getAttribute("brightness").get().setValue(100)+ assetStorageService.merge(lightAsset)++ then: "the light asset should have its brightness set to 100" // set to 100 to start the duration of the matched state+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("brightness").get().getValue().orElse(0) == 100+ }++ when: "time advances for 6 seconds"+ advancePseudoClock(6, TimeUnit.SECONDS, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should have its notes attribute be empty"+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == ""+ }++ when: "time advances for 4 minutes"+ advancePseudoClock(3, TimeUnit.MINUTES, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should have its notes attribute be empty" // because brightness was set to 0 in between so the timer was reset for that attribute match+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == ""+ }++ when: "time advances for 3 minutes"+ advancePseudoClock(3, TimeUnit.MINUTES, container)++ then: "the rule engine should have fired"+ conditions.eventually {+ assert realmBuildingEngine.lastFireTimestamp > lastFireTimestamp+ lastFireTimestamp = realmBuildingEngine.lastFireTimestamp+ }++ and: "the light asset should have its notes attribute be Triggered" // because brightness has been above 50 for 5 minutes.+ conditions.eventually {+ def light = assetStorageService.find(lightId)+ assert light.getAttribute("notes").get().getValue().orElse("") == "Triggered"+ }+ }+def "Trigger actions based on the position of the sun"() {given: "the container environment is started"diff --git a/test/src/test/resources/org/openremote/test/rules/JsonAttributeDurationRule.json b/test/src/test/resources/org/openremote/test/rules/JsonAttributeDurationRule.jsonnew file mode 100644index 000000000..876b7f6fb--- /dev/null+++ b/test/src/test/resources/org/openremote/test/rules/JsonAttributeDurationRule.json@@ -0,0 +1,140 @@+{+ "rules": [+ {+ "recurrence": {+ "mins": 0+ },+ "when": {+ "operator": "OR",+ "groups": [+ {+ "operator": "AND",+ "items": [+ {+ "assets": {+ "types": [+ "LightAsset"+ ],+ "attributes": {+ "items": [+ {+ "name": {+ "predicateType": "string",+ "match": "EXACT",+ "value": "onOff"+ },+ "value": {+ "predicateType": "boolean",+ "value": true+ }+ },+ {+ "name": {+ "predicateType": "string",+ "match": "EXACT",+ "value": "brightness"+ },+ "value": {+ "predicateType": "number",+ "operator": "GREATER_THAN",+ "value": 50+ }+ },+ {+ "name": {+ "predicateType": "string",+ "match": "EXACT",+ "value": "brightness"+ },+ "value": {+ "predicateType": "number",+ "operator": "GREATER_THAN",+ "value": 10+ }+ }+ ]+ }+ },+ "duration": {+ "1": "PT5M",+ "2": "PT3M"+ }+ },+ {+ "assets": {+ "types": [+ "ThingAsset"+ ],+ "attributes": {+ "items": [+ {+ "name": {+ "predicateType": "string",+ "match": "EXACT",+ "value": "notes"+ },+ "value": {+ "predicateType": "string",+ "negate": false,+ "match": "EXACT",+ "value": "Test"+ }+ }+ ]+ }+ }+ }+ ]+ },+ {+ "operator": "AND",+ "items": [+ {+ "assets": {+ "types": [+ "LightAsset"+ ],+ "attributes": {+ "items": [+ {+ "name": {+ "predicateType": "string",+ "match": "EXACT",+ "value": "notes"+ },+ "value": {+ "predicateType": "string",+ "negate": false,+ "match": "EXACT",+ "value": "TriggerDuration"+ }+ }+ ]+ }+ },+ "duration": {+ "0": "PT10M"+ }+ }+ ]+ }+ ]+ },+ "then": [+ {+ "action": "write-attribute",+ "target": {+ "matchedAssets": {+ "types": [+ "LightAsset"+ ]+ }+ },+ "value": "Triggered",+ "attributeName": "notes"+ }+ ],+ "name": "Duration Rule"+ }+ ]+}\ No newline at end of file