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
JSON rules updates
Rich Turner8ccfaf97b2ea
diff --git a/deployment/manager/shared/locales/en/or.json b/deployment/manager/shared/locales/en/or.jsonindex b0a915371..662d84470 100644--- a/deployment/manager/shared/locales/en/or.json+++ b/deployment/manager/shared/locales/en/or.json@@ -160,18 +160,11 @@"message": "Message","warn": "Warning","error": "Error",- "recurrence": "Recurrence","always": "Always","once": "Once",- "oncePerAsset": "Once per asset","oncePerHour": "Once per hour",- "oncePerHourPerAsset": "Once per hour per asset","oncePerDay": "Once per day",- "oncePerDayPerAsset": "Once per day per asset","oncePerWeek": "Once per week",- "oncePerWeekPerAsset": "Once per week per asset",- "oncePerMonth": "Once per month",- "oncePerMonthPerAsset": "Once per month per asset","reset": "Reset","noLongerMatches": "No longer matches"}diff --git a/deployment/manager/shared/locales/nl/or.json b/deployment/manager/shared/locales/nl/or.jsonindex ed13a7f1e..dbb6fade0 100644--- a/deployment/manager/shared/locales/nl/or.json+++ b/deployment/manager/shared/locales/nl/or.json@@ -133,7 +133,7 @@"german": "Duits","spanish": "Spaans","noRuleSelected": "Kies links een regel om te bekijken",- "anyOfThisType": "Elk van dit type",+ "anyOfThisType": "Eén van dit type","notification": "Melding","matched": "Dezelfde","unmatched": "Niet dezelfde",@@ -150,18 +150,11 @@"operator": "Operator","area": "Gebied","timestamp": "Tijdsaanduiding",- "recurrence": "Recurrence","always": "Iedere keer","once": "Eenmalig",- "oncePerAsset": "Eenmalig per asset","oncePerHour": "1x per uur",- "oncePerHourPerAsset": "1x per uur per asset","oncePerDay": "1x per dag",- "oncePerDayPerAsset": "1x per dag per asset","oncePerWeek": "1x per week",- "oncePerWeekPerAsset": "1x per week per asset",- "oncePerMonth": "1x per maand",- "oncePerMonthPerAsset": "1x per maand per asset","reset": "Reset","noLongerMatches": "No longer matches"}diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.javaindex 9afbf7e39..a80de231d 100644--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java@@ -38,7 +38,6 @@ import org.openremote.model.rules.Assets;import org.openremote.model.rules.Ruleset;import org.openremote.model.rules.Users;import org.openremote.model.rules.json.*;-import org.openremote.model.util.Pair;import org.openremote.model.util.TextUtil;import org.openremote.model.util.TimeUtil;import org.openremote.model.value.*;@@ -48,6 +47,7 @@ import java.util.*;import java.util.concurrent.atomic.AtomicLong;import java.util.function.BiConsumer;import java.util.function.Predicate;+import java.util.function.Supplier;import java.util.logging.Level;import java.util.stream.Collectors;import java.util.stream.Stream;@@ -169,8 +169,10 @@ public class JsonRulesBuilder extends RulesBuilder {// Replace or remove asset state as requiredswitch (event.cause) {case UPDATE:- unfilteredAssetStates.remove(event.assetState);- unfilteredAssetStates.add(event.assetState);+ // Only insert if fact was already in there (i.e. it matches the asset type constraints)+ if (unfilteredAssetStates.remove(event.assetState)) {+ unfilteredAssetStates.add(event.assetState);+ }break;case DELETE:unfilteredAssetStates.remove(event.assetState);@@ -265,22 +267,16 @@ public class JsonRulesBuilder extends RulesBuilder {matchedAssetStates.removeIf(matchedAssetState -> nextRecurAssetIdMap.containsKey(matchedAssetState.getId())&& nextRecurAssetIdMap.get(matchedAssetState.getId()) > timerService.getCurrentTimeMillis());- // Remove previous matches where the asset state no longer matches or the value has changed (depending on reset option)+ // Remove previous matches where the asset state no longer matchespreviouslyMatchedAssetStates.removeIf(previousAssetState -> {- int matchIndex = matchedAssetStates.indexOf(previousAssetState);- boolean valueChangedOrNoLongerMatches = matchIndex < 0;-- // If reset on value change and still matches check to see if the value has changed- if (!valueChangedOrNoLongerMatches && ruleCondition.resetOnValueChange) {- valueChangedOrNoLongerMatches = !Objects.equals(previousAssetState.getValue().orElse(null), matchedAssetStates.get(matchIndex).getValue().orElse(null));- }+ boolean noLongerMatches = !matchedAssetStates.contains(previousAssetState);- if (valueChangedOrNoLongerMatches) {- log(Level.FINER, "Rule trigger previously matched asset state value has changed or no longer matches so resetting: " + previousAssetState);+ if (noLongerMatches) {+ log(Level.FINER, "Rule trigger previously matched asset state no longer matches so resetting: " + previousAssetState);}- return valueChangedOrNoLongerMatches;+ return noLongerMatches;});// Filter out previous matches to avoid re-triggering@@ -366,14 +362,45 @@ public class JsonRulesBuilder extends RulesBuilder {*/static class RuleState {- protected Map<String, RuleConditionState> conditionStateMap;- protected List<String> thenMatchedAssetIds = new ArrayList<>();- protected List<String> otherwiseMatchedAssetIds = new ArrayList<>();+ protected JsonRule rule;+ protected Map<String, RuleConditionState> conditionStateMap = new HashMap<>();+ protected Set<String> thenMatchedAssetIds;+ protected Set<String> otherwiseMatchedAssetIds;protected long nextRecur;+ protected boolean matched;protected Map<String, Long> nextRecurAssetIdMap = new HashMap<>();- public RuleState(Map<String, RuleConditionState> conditionStateMap) {- this.conditionStateMap = conditionStateMap;+ public RuleState(JsonRule rule) {+ this.rule = rule;+ }++ public void update(Supplier<Long> currentMillisSupplier) {++ matched = false;++ // Check if next recurrence in the future+ if (nextRecur > currentMillisSupplier.get()) {+ return;+ }++ // Clear out expired recurrence timers+ nextRecurAssetIdMap.entrySet().removeIf(entry -> entry.getValue() <= currentMillisSupplier.get());++ // Update each condition state+ log(Level.FINEST, "Updating rule condition states for rule: " + rule.name);+ conditionStateMap.values().forEach(ruleConditionState -> ruleConditionState.update(nextRecurAssetIdMap));++ thenMatchedAssetIds = new HashSet<>();+ otherwiseMatchedAssetIds = rule.otherwise != null ? new HashSet<>() : null;++ matched = updateMatches(rule.when, thenMatchedAssetIds, otherwiseMatchedAssetIds);++ if (!matched) {+ thenMatchedAssetIds.clear();+ if (otherwiseMatchedAssetIds != null) {+ otherwiseMatchedAssetIds.clear();+ }+ }}public boolean thenMatched() {@@ -383,6 +410,68 @@ public class JsonRulesBuilder extends RulesBuilder {public boolean otherwiseMatched() {return otherwiseMatchedAssetIds != null && !otherwiseMatchedAssetIds.isEmpty();}++ protected boolean updateMatches(LogicGroup<RuleCondition> ruleConditionGroup, Set<String> thenMatchedAssetIds, Set<String> otherwiseMatchedAssetIds) {++ if (groupIsEmpty(ruleConditionGroup)) {+ return false;+ }++ LogicGroup.Operator operator = ruleConditionGroup.operator == null ? LogicGroup.Operator.AND : ruleConditionGroup.operator;+ boolean groupMatches = false;++ if (!ruleConditionGroup.getItems().isEmpty()) {++ if (operator == LogicGroup.Operator.AND) {+ groupMatches = ruleConditionGroup.getItems().stream()+ .map(ruleCondition -> conditionStateMap.get(ruleCondition.tag))+ .allMatch(ruleConditionState -> ruleConditionState.lastEvaluationResult != null && ruleConditionState.lastEvaluationResult.matches);+ } else {+ groupMatches = ruleConditionGroup.getItems().stream()+ .map(ruleCondition -> conditionStateMap.get(ruleCondition.tag))+ .anyMatch(ruleConditionState -> ruleConditionState.lastEvaluationResult != null && ruleConditionState.lastEvaluationResult.matches);+ }++ thenMatchedAssetIds.addAll(ruleConditionGroup.getItems().stream()+ .map(ruleCondition -> conditionStateMap.get(ruleCondition.tag))+ .filter(ruleConditionState -> ruleConditionState.lastEvaluationResult != null && ruleConditionState.lastEvaluationResult.matches)+ .map(RuleConditionState::getMatchedAssetIds)//Get all unmatched assetIds+ .flatMap(Collection::stream)+ .collect(Collectors.toSet()));++ if (otherwiseMatchedAssetIds != null) {+ otherwiseMatchedAssetIds.addAll(ruleConditionGroup.getItems().stream()+ .map(ruleCondition -> conditionStateMap.get(ruleCondition.tag))+ .filter(ruleConditionState -> ruleConditionState.trackUnmatched && ruleConditionState.lastEvaluationResult != null && ruleConditionState.lastEvaluationResult.matches)+ .map(RuleConditionState::getUnmatchedAssetIds)//Get all unmatched assetIds+ .flatMap(Collection::stream)+ .collect(Collectors.toSet()));+ }+ }++ if (ruleConditionGroup.groups != null) {++ if (operator == LogicGroup.Operator.AND) {+ if (!ruleConditionGroup.items.isEmpty() && !groupMatches) {+ return false;+ }++ groupMatches = ruleConditionGroup.groups.stream()+ .allMatch(group -> updateMatches(group, thenMatchedAssetIds, otherwiseMatchedAssetIds));++ } else {++ // updateMatches has side effects which we need (inserts into then and otherwise)+ //noinspection ReplaceInefficientStreamCount+ groupMatches = ruleConditionGroup.groups.stream()+ .filter(group -> updateMatches(group, thenMatchedAssetIds, otherwiseMatchedAssetIds))+ .count() > 0;++ }+ }++ return groupMatches;+ }}public static final String PLACEHOLDER_RULESET_ID = "%RULESET_ID%";@@ -396,7 +485,7 @@ public class JsonRulesBuilder extends RulesBuilder {final protected NotificationsFacade<?> notificationsFacade;final protected ManagerExecutorService executorService;final protected BiConsumer<Runnable, Long> scheduledActionConsumer;- final protected Map<String, RuleState> ruleEvaluationMap = new HashMap<>();+ final protected Map<String, RuleState> ruleStateMap = new HashMap<>();final protected JsonRule[] jsonRules;public JsonRulesBuilder(Ruleset ruleset, TimerService timerService, AssetStorageService assetStorageService, ManagerExecutorService executorService, Assets assetsFacade, Users usersFacade, NotificationsFacade<?> notificationsFacade, BiConsumer<Runnable, Long> scheduledActionConsumer) throws Exception {@@ -439,21 +528,21 @@ public class JsonRulesBuilder extends RulesBuilder {}public void onAssetStatesChanged(RulesFacts facts, RulesEngine.AssetStateChangeEvent event) {- ruleEvaluationMap.values().forEach(triggerStateMap -> triggerStateMap.conditionStateMap.values().forEach(ruleConditionState -> ruleConditionState.updateUnfilteredAssetStates(facts, event)));+ ruleStateMap.values().forEach(triggerStateMap -> triggerStateMap.conditionStateMap.values().forEach(ruleConditionState -> ruleConditionState.updateUnfilteredAssetStates(facts, event)));}protected JsonRulesBuilder add(JsonRule rule) throws Exception {- if (ruleEvaluationMap.containsKey(rule.name)) {+ if (ruleStateMap.containsKey(rule.name)) {throw new IllegalArgumentException("Rules must have a unique name within a ruleset, rule name '" + rule.name + "' already used");}- RuleState ruleEvaluationResult = new RuleState(new HashMap<>());- ruleEvaluationMap.put(rule.name, ruleEvaluationResult);- addRuleConditionStates(rule.when, rule.otherwise != null, 0, ruleEvaluationResult.conditionStateMap);+ RuleState ruleState = new RuleState(rule);+ ruleStateMap.put(rule.name, ruleState);+ addRuleConditionStates(rule.when, rule.otherwise != null, 0, ruleState.conditionStateMap);- Condition condition = buildLhsCondition(rule, ruleEvaluationResult);- Action action = buildRhsAction(rule, ruleEvaluationResult);+ Condition condition = buildLhsCondition(rule, ruleState);+ Action action = buildRhsAction(rule, ruleState);if (condition == null || action == null) {throw new IllegalArgumentException("Error building JSON rule when or then is not defined: " + rule.name);@@ -487,6 +576,7 @@ public class JsonRulesBuilder extends RulesBuilder {if (TextUtil.isNullOrEmpty(ruleCondition.tag)) {ruleCondition.tag = Integer.toString(index);}+triggerStateMap.put(ruleCondition.tag, new RuleConditionState(ruleCondition, trackUnmatched, timerService));index++;}@@ -505,25 +595,8 @@ public class JsonRulesBuilder extends RulesBuilder {}return facts -> {-- // Check if next recurrence in the future- if (ruleState.nextRecur > timerService.getCurrentTimeMillis()) {- return false;- }-- // Clear out expired recurrence timers- ruleState.nextRecurAssetIdMap.entrySet().removeIf(entry -> entry.getValue() <= timerService.getCurrentTimeMillis());-- // Update each condition state- log(Level.FINEST, "Updating rule condition states for rule: " + rule.name);- ruleState.conditionStateMap.values().forEach(ruleConditionState -> ruleConditionState.update(ruleState.nextRecurAssetIdMap));-- // Apply group operator and extract resulting matched asset IDs- Pair<List<String>, List<String>> matchedUnmatchedGroupResults = getGroupLastTriggerResults(rule.when, ruleState.conditionStateMap, rule.otherwise != null);- ruleState.thenMatchedAssetIds = matchedUnmatchedGroupResults.key;- ruleState.otherwiseMatchedAssetIds = matchedUnmatchedGroupResults.value;-- return ruleState.thenMatched() || ruleState.otherwiseMatched();+ ruleState.update(timerService::getCurrentTimeMillis);+ return ruleState.matched;};}@@ -536,8 +609,8 @@ public class JsonRulesBuilder extends RulesBuilder {return facts -> {try {- log(Level.FINER, "Triggered rule so executing 'then' actions for rule: " + rule.name);if (ruleState.thenMatched()) {+ log(Level.FINER, "Triggered rule so executing 'then' actions for rule: " + rule.name);executeRuleActions(rule, rule.then, "then", false, facts, ruleState, assetsFacade, usersFacade, notificationsFacade, scheduledActionConsumer);}@@ -563,8 +636,8 @@ public class JsonRulesBuilder extends RulesBuilder {}}- // Store last evaluation results in stateruleState.conditionStateMap.values().forEach(ruleConditionState -> {+ // Store last evaluation results in stateif (ruleConditionState.lastEvaluationResult != null) {// Replace any stale matched asset states (values may have changed equality is by asset ID and attribute name)@@ -577,10 +650,10 @@ public class JsonRulesBuilder extends RulesBuilder {ruleConditionState.previouslyUnmatchedAssetStates.addAll(ruleConditionState.lastEvaluationResult.unmatchedAssetStates);}}- });- // Clear last results- ruleState.conditionStateMap.values().forEach(triggerState -> triggerState.lastEvaluationResult = null);+ // Clear last results+ ruleConditionState.lastEvaluationResult = null;+ });}};}@@ -844,7 +917,7 @@ public class JsonRulesBuilder extends RulesBuilder {private static String buildTriggeredAssetInfo(boolean useUnmatched, RuleState ruleEvaluationResult, boolean isHtml) {- List<String> assetIds = useUnmatched ? ruleEvaluationResult.otherwiseMatchedAssetIds : ruleEvaluationResult.thenMatchedAssetIds;+ Set<String> assetIds = useUnmatched ? ruleEvaluationResult.otherwiseMatchedAssetIds : ruleEvaluationResult.thenMatchedAssetIds;if (assetIds == null || assetIds.isEmpty()) {return "";@@ -945,68 +1018,6 @@ public class JsonRulesBuilder extends RulesBuilder {return Collections.emptyList();}- protected static Pair<List<String>, List<String>> getGroupLastTriggerResults(LogicGroup<RuleCondition> ruleConditionGroup, Map<String, RuleConditionState> conditionStateMap, boolean trackUnmatched) {-- if (groupIsEmpty(ruleConditionGroup)) {- return new Pair<>(Collections.emptyList(), Collections.emptyList());- }-- List<String> matchedAssetIds = new ArrayList<>();- List<String> unmatchedAssetIds = new ArrayList<>();- LogicGroup.Operator operator = ruleConditionGroup.operator == null ? LogicGroup.Operator.AND : ruleConditionGroup.operator;-- if (!ruleConditionGroup.getItems().isEmpty()) {-- if (operator == LogicGroup.Operator.AND) {-- // Find asset IDs that are matched in all rule conditions- matchedAssetIds.addAll(ruleConditionGroup.getItems().stream()- .map(ruleCondition -> conditionStateMap.get(ruleCondition.tag))- .filter(ruleConditionState -> ruleConditionState.lastEvaluationResult != null && ruleConditionState.lastEvaluationResult.matches) //Only trigger results which matches- .map(RuleConditionState::getMatchedAssetIds)//Get all matched assetIds- .flatMap(Collection::stream)- .collect(Collectors.groupingBy(assetId -> assetId, Collectors.counting())) // Group them and count the number of times appearing in the rule conditions- .entrySet()- .stream()- .filter(entry -> entry.getValue() == ruleConditionGroup.getItems().size())- .map(Map.Entry::getKey)- .collect(Collectors.toList()));-- } else if (operator == LogicGroup.Operator.OR) {-- matchedAssetIds.addAll(ruleConditionGroup.getItems().stream()- .map(ruleCondition -> conditionStateMap.get(ruleCondition.tag))- .filter(ruleConditionState -> ruleConditionState.lastEvaluationResult != null && ruleConditionState.lastEvaluationResult.matches)- .map(RuleConditionState::getMatchedAssetIds)//Get all unmatched assetIds- .flatMap(Collection::stream)- .distinct()- .collect(Collectors.toList()));-- }-- if (trackUnmatched) {- // Unmatched we don't apply group AND/OR just collate them all- unmatchedAssetIds.addAll(ruleConditionGroup.getItems().stream()- .map(ruleCondition -> conditionStateMap.get(ruleCondition.tag))- .filter(ruleConditionState -> ruleConditionState.trackUnmatched && ruleConditionState.lastEvaluationResult != null && ruleConditionState.lastEvaluationResult.matches)- .map(RuleConditionState::getUnmatchedAssetIds)//Get all unmatched assetIds- .flatMap(Collection::stream)- .distinct()- .collect(Collectors.toList()));- }- }-- if (ruleConditionGroup.groups != null) {- for (LogicGroup<RuleCondition> childRuleConditionGroup : ruleConditionGroup.groups) {- Pair<List<String>, List<String>> childGroupMatchedAndUnmatched = getGroupLastTriggerResults(childRuleConditionGroup, conditionStateMap, trackUnmatched);- matchedAssetIds.addAll(childGroupMatchedAndUnmatched.key);- unmatchedAssetIds.addAll(childGroupMatchedAndUnmatched.value);- }- }-- return new Pair<>(matchedAssetIds, unmatchedAssetIds);- }-protected static boolean targetIsNotAssets(RuleActionTarget target) {return target != null && target.users != null;}diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.javaindex 5b92050b8..7a2e1019d 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java@@ -498,49 +498,56 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse} else {if (ruleset instanceof GlobalRuleset) {- RulesEngine<GlobalRuleset> newEngine = deployGlobalRuleset((GlobalRuleset) ruleset);- if (newEngine != null) {+ boolean isNewEngine = globalEngine == null;+ RulesEngine<GlobalRuleset> engine = deployGlobalRuleset((GlobalRuleset) ruleset);++ if (isNewEngine) {// Push all existing facts into the engine- assetStates.forEach(assetState -> newEngine.updateOrInsertAssetState(assetState, true));- newEngine.start();+ assetStates.forEach(assetState -> engine.updateOrInsertAssetState(assetState, true));}+ engine.start();+} else if (ruleset instanceof TenantRuleset) {- RulesEngine<TenantRuleset> newEngine = deployTenantRuleset((TenantRuleset) ruleset);- if (newEngine != null) {+ boolean isNewEngine = !tenantEngines.containsKey(((TenantRuleset)ruleset).getRealm());+ RulesEngine<TenantRuleset> engine = deployTenantRuleset((TenantRuleset) ruleset);++ if (isNewEngine) {// Push all existing facts into the engineassetStates.forEach(assetState -> {if (assetState.getRealm().equals(((TenantRuleset) ruleset).getRealm())) {- newEngine.updateOrInsertAssetState(assetState, true);+ engine.updateOrInsertAssetState(assetState, true);}});- newEngine.start();}+ engine.start();+} else if (ruleset instanceof AssetRuleset) {// Must reload from the database, the ruleset might not be completely hydrated on CREATE or UPDATEAssetRuleset assetRuleset = rulesetStorageService.find(AssetRuleset.class, ruleset.getId());- RulesEngine<AssetRuleset> newEngine = deployAssetRuleset(assetRuleset);- if (newEngine != null) {+ boolean isNewEngine = !assetEngines.containsKey(((AssetRuleset)ruleset).getAssetId());+ RulesEngine<AssetRuleset> engine = deployAssetRuleset(assetRuleset);++ if (isNewEngine) {// Push all existing facts for this asset (and it's children into the engine)getAssetStatesInScope(((AssetRuleset) ruleset).getAssetId())- .forEach(assetState -> newEngine.updateOrInsertAssetState(assetState, true));- newEngine.start();+ .forEach(assetState -> engine.updateOrInsertAssetState(assetState, true));}++ engine.start();}}});}/**- * Deploy the ruleset into the global engine creating the engine if necessary; if the engine was created then it is- * returned from the method.+ * Deploy the ruleset into the global engine creating the engine if necessary.*/protected RulesEngine<GlobalRuleset> deployGlobalRuleset(GlobalRuleset ruleset) {return withLockReturning(getClass().getSimpleName() + "::deployGlobalRuleset", () -> {- boolean created = globalEngine == null;// Global rules have access to everything in the systemif (globalEngine == null) {@@ -559,7 +566,7 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseglobalEngine.addRuleset(ruleset);- return created ? globalEngine : null;+ return globalEngine;});}@@ -578,13 +585,12 @@ public class RulesService extends RouteBuilder implements ContainerService, Asseprotected RulesEngine<TenantRuleset> deployTenantRuleset(TenantRuleset ruleset) {return withLockReturning(getClass().getSimpleName() + "::deployTenantRuleset", () -> {- AtomicBoolean created = new AtomicBoolean(false);+// Look for existing rules engines for this tenantRulesEngine<TenantRuleset> tenantRulesEngine = tenantEngines- .computeIfAbsent(ruleset.getRealm(), (realm) -> {- created.set(true);- return new RulesEngine<>(+ .computeIfAbsent(ruleset.getRealm(), (realm) ->+ new RulesEngine<>(timerService,identityService,executorService,@@ -594,12 +600,11 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseclientEventService,new RulesEngineId<>(realm),locationPredicateRulesConsumer- );- });+ ));tenantRulesEngine.addRuleset(ruleset);- return created.get() ? tenantRulesEngine : null;+ return tenantRulesEngine;});}@@ -641,20 +646,17 @@ public class RulesService extends RouteBuilder implements ContainerService, Assereturn tenantAssetAndRules.stream()//.sorted(Comparator.comparingInt(item -> item.key.getPath().length)).flatMap(assetAndRules -> assetAndRules.value.stream())- .map(this::deployAssetRuleset)- .filter(Objects::nonNull);+ .map(this::deployAssetRuleset);});}protected RulesEngine<AssetRuleset> deployAssetRuleset(AssetRuleset ruleset) {return withLockReturning(getClass().getSimpleName() + "::deployAssetRuleset", () -> {- AtomicBoolean created = new AtomicBoolean(false);// Look for existing rules engine for this assetRulesEngine<AssetRuleset> assetRulesEngine = assetEngines- .computeIfAbsent(ruleset.getAssetId(), (assetId) -> {- created.set(true);- return new RulesEngine<>(+ .computeIfAbsent(ruleset.getAssetId(), (assetId) ->+ new RulesEngine<>(timerService,identityService,executorService,@@ -664,12 +666,11 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseclientEventService,new RulesEngineId<>(ruleset.getRealm(), assetId),locationPredicateRulesConsumer- );- });+ ));assetRulesEngine.addRuleset(ruleset);- return created.get() ? assetRulesEngine : null;+ return assetRulesEngine;});}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 c403662eb..b7a384839 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@@ -33,10 +33,6 @@ import org.openremote.model.query.AssetQuery;* returned after applying the query.</li>* </ol>* <p>- * The {@link #resetOnValueChange} is used to indicate that an {@link org.openremote.model.rules.AssetState} is- * re-eligible for triggering the rule again when its' value changes (the default behaviour is that it only becomes- * re-eligible when it no longer matches the condition).- * <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.*/@@ -44,6 +40,5 @@ public class RuleCondition {public String timer;public AssetQuery assets;- public boolean resetOnValueChange;public String tag;}diff --git a/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.tsindex cd8da7d2c..48149c57b 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts@@ -32,7 +32,7 @@ import manager, {AssetModelUtil, Util} from "@openremote/core";import i18next from "i18next";import {buttonStyle} from "../style";import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";-import { translate } from "@openremote/or-translate";+import {translate} from "@openremote/or-translate";// language=CSSconst style = css`diff --git a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.tsindex b5b41b7cb..a31d93a31 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts@@ -116,7 +116,11 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implementsif (this.config && this.config.json && this.config.json.rule) {this._rule = JSON.parse(JSON.stringify(this.config.json.rule)) as JsonRule;} else {- this._rule = {};+ this._rule = {+ recurrence: {+ mins: 0 //always+ }+ };}} else {try {@@ -418,6 +422,7 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implementsreturn (valuePredicate.index && !valuePredicate.value) || valuePredicate.value || valuePredicate.lengthEquals || valuePredicate.lengthLessThan || valuePredicate.lengthGreaterThan;case "value-empty":case "value-not-empty":+ case "value-changed":return true;default:return false;diff --git a/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts b/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.tsindex 04896d44a..acb113f25 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts@@ -80,15 +80,9 @@ interface ResetOptions {export enum RecurrenceOption {ALWAYS = "always",ONCE = "once",- ONCE_PER_ASSET = "oncePerAsset",ONCE_PER_HOUR = "oncePerHour",- ONCE_PER_HOUR_PER_ASSET = "oncePerHourPerAsset",ONCE_PER_DAY = "oncePerDay",- ONCE_PER_DAY_PER_ASSET = "oncePerDayPerAsset",ONCE_PER_WEEK = "oncePerWeek",- ONCE_PER_WEEK_PER_ASSET = "oncePerWeekPerAsset",- ONCE_PER_MONTH = "oncePerMonth",- ONCE_PER_MONTH_PER_ASSET = "oncePerMonthPerAsset"}function getRecurrenceMenu(config?: RulesConfig): MenuItem[] {@@ -203,27 +197,24 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {protected ruleRecurrenceTemplate(reset: RuleRecurrence | undefined) {let recurrenceTemplate: TemplateResult | string = ``;const buttonColor = "inherit";- let value = RecurrenceOption.ONCE_PER_ASSET;+ let value = RecurrenceOption.ONCE;if (reset) {- let isGlobal = reset.scope === RuleRecurrenceScope.GLOBAL;if (reset.mins === undefined || reset.mins === null) {- value = isGlobal ? RecurrenceOption.ONCE : RecurrenceOption.ONCE_PER_ASSET;+ value = RecurrenceOption.ONCE;} else if (reset.mins === 0) {value = RecurrenceOption.ALWAYS;} else if (reset.mins === 60) {- value = isGlobal ? RecurrenceOption.ONCE_PER_HOUR : RecurrenceOption.ONCE_PER_HOUR_PER_ASSET;+ value = RecurrenceOption.ONCE_PER_HOUR;} else if (reset.mins === 1440) {- value = isGlobal ? RecurrenceOption.ONCE_PER_DAY : RecurrenceOption.ONCE_PER_DAY_PER_ASSET;+ value = RecurrenceOption.ONCE_PER_DAY;} else if (reset.mins === 10080) {- value = isGlobal ? RecurrenceOption.ONCE_PER_WEEK : RecurrenceOption.ONCE_PER_WEEK_PER_ASSET;- } else if (reset.mins === 43200) {- value = isGlobal ? RecurrenceOption.ONCE_PER_MONTH : RecurrenceOption.ONCE_PER_MONTH_PER_ASSET;+ value = RecurrenceOption.ONCE_PER_WEEK;}}recurrenceTemplate = html`- <div style="color: #${buttonColor}; margin-right: 6px;"><span><or-translate value="recurrence"></or-translate>:</span>+ <div style="color: #${buttonColor}; margin-right: 6px;">${getContentWithMenuTemplate(html`<or-input .type="${InputType.BUTTON}" .label="${i18next.t(value)}"></or-input>`,getRecurrenceMenu(this.config),@@ -365,34 +356,16 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {case RecurrenceOption.ALWAYS:this.rule.recurrence = {mins: 0};break;- case RecurrenceOption.ONCE:- this.rule.recurrence = {scope: RuleRecurrenceScope.GLOBAL};- break;case RecurrenceOption.ONCE_PER_HOUR:- this.rule.recurrence = {scope: RuleRecurrenceScope.GLOBAL, mins: 60};- break;- case RecurrenceOption.ONCE_PER_HOUR_PER_ASSET:this.rule.recurrence = {mins: 60};break;case RecurrenceOption.ONCE_PER_DAY:- this.rule.recurrence = {scope: RuleRecurrenceScope.GLOBAL, mins: 1440};- break;- case RecurrenceOption.ONCE_PER_DAY_PER_ASSET:this.rule.recurrence = {mins: 1440};break;case RecurrenceOption.ONCE_PER_WEEK:- this.rule.recurrence = {scope: RuleRecurrenceScope.GLOBAL, mins: 10080};- break;- case RecurrenceOption.ONCE_PER_WEEK_PER_ASSET:this.rule.recurrence = {mins: 10080};break;- case RecurrenceOption.ONCE_PER_MONTH:- this.rule.recurrence = {scope: RuleRecurrenceScope.GLOBAL, mins: 43200};- break;- case RecurrenceOption.ONCE_PER_MONTH_PER_ASSET:- this.rule.recurrence = {mins: 43200};- break;- case RecurrenceOption.ONCE_PER_ASSET:+ case RecurrenceOption.ONCE:default:delete this.rule.recurrence;break;diff --git a/ui/component/or-rules/src/json-viewer/or-rule-when.ts b/ui/component/or-rules/src/json-viewer/or-rule-when.tsindex 64962fc15..3ccab0396 100644--- a/ui/component/or-rules/src/json-viewer/or-rule-when.ts+++ b/ui/component/or-rules/src/json-viewer/or-rule-when.ts@@ -94,12 +94,6 @@ const style = css`.add-button-wrapper or-mwc-menu {text-transform: capitalize;}-- .rule-reset {- position: absolute;- top: 5px;- right: 0;- }`;@customElement("or-rule-when")@@ -118,33 +112,6 @@ class OrRuleWhen extends translate(i18next)(LitElement) {public assetDescriptors?: AssetDescriptor[];- protected conditionResetTemplate(condition: RuleCondition): TemplateResult | string {-- if (!condition.assets) {- return ``;- }-- const buttonColor = "inherit";- let value = condition.resetOnValueChange ? ResetOption.VALUE_CHANGES : ResetOption.NO_LONGER_MATCHES;- let menuItems: MenuItem[] = Object.values(ResetOption).map((resetOption) => {- return {- text: i18next.t(resetOption),- value: resetOption- } as MenuItem;- });-- return html`- <div class="rule-reset">- <div style="color: #${buttonColor}; margin-right: 6px;"><span><or-translate value="reset"></or-translate>:</span>- ${getContentWithMenuTemplate(- html`<or-input .type="${InputType.BUTTON}" .label="${i18next.t(value)}"></or-input>`,- menuItems,- value,- (value) => this.setResetOption(condition, value as ResetOption))}- </div>- </div>`;- }-protected ruleGroupTemplate(group: LogicGroup<RuleCondition>, parentGroup?: LogicGroup<RuleCondition>): TemplateResult | undefined {if (!group) {@@ -161,8 +128,7 @@ class OrRuleWhen extends translate(i18next)(LitElement) {if (isTopLevel) {wrapper = (content, item, parent, isGroup, isFirst) => {return html`-- <or-panel .heading="${i18next.t(isFirst ? "when": "orWhen")}...">+ <or-panel .heading="${i18next.t(isFirst ? "when" : "orWhen")}...">${showRemoveGroup ? html`<button class="button-clear remove-button" @click="${() => this.removeItem(item, parent, isGroup)}"><or-icon icon="close-circle"></or-icon>@@ -173,13 +139,7 @@ class OrRuleWhen extends translate(i18next)(LitElement) {};} else {wrapper = (content, item, parent, isGroup, isFirst) => {-- let isCondition = (item as LogicGroup<RuleCondition>).items === undefined;-return html`-- ${isCondition ? this.conditionResetTemplate(item as RuleCondition) : ``}-${!isFirst ? html`<or-icon class="small" icon="ampersand"></or-icon>` : ``}@@ -418,14 +378,4 @@ class OrRuleWhen extends translate(i18next)(LitElement) {this.requestUpdate();}}-- private setResetOption(condition: RuleCondition, value: ResetOption) {- if (value === ResetOption.NO_LONGER_MATCHES) {- delete condition.resetOnValueChange;- } else {- condition.resetOnValueChange = true;- }- this.dispatchEvent(new OrRulesJsonRuleChangedEvent());- this.requestUpdate();- }}diff --git a/ui/component/or-rules/src/or-rule-list.ts b/ui/component/or-rules/src/or-rule-list.tsindex 53f9458b9..da7a98bc9 100644--- a/ui/component/or-rules/src/or-rule-list.ts+++ b/ui/component/or-rules/src/or-rule-list.ts@@ -1,9 +1,7 @@-import {css, customElement, html, LitElement, property, PropertyValues, query, TemplateResult} from "lit-element";-import {JsonRule, RuleCondition, RulesetLang, TenantRuleset, ClientRole, CalendarEvent} from "@openremote/model";+import {css, customElement, html, LitElement, property, PropertyValues, TemplateResult} from "lit-element";+import {CalendarEvent, ClientRole, RulesetLang, TenantRuleset} from "@openremote/model";import "@openremote/or-translate";import manager, {EventCallback, OREvent} from "@openremote/core";-import moment from "moment";-import { RRule, RRuleSet, rrulestr } from "rrule";import "@openremote/or-input";import {InputType} from "@openremote/or-input";import {style as OrAssetTreeStyle} from "@openremote/or-asset-tree";@@ -15,7 +13,8 @@ import {OrRulesSelectionChangedEvent,RequestEventDetail,RulesConfig,- RulesetNode} from "./index";+ RulesetNode+} from "./index";import "@openremote/or-mwc-components/dist/or-mwc-menu";import {MenuItem} from "@openremote/or-mwc-components/dist/or-mwc-menu";import {translate} from "@openremote/or-translate";@@ -269,7 +268,7 @@ export class OrRuleList extends translate(i18next)(LitElement) {<li ?data-selected="${node.selected}" @click="${(evt: MouseEvent) => this._onNodeClicked(evt, node)}"><div class="node-container"><span class="node-status ${OrRuleList._getNodeStatusClasses(node.ruleset)}"></span>- <span class="node-name">${node.ruleset.name}<span class="node-language">${node.ruleset.lang}</span></span>+ <span class="node-name">${node.ruleset.name}<span class="node-language">${node.ruleset.lang !== RulesetLang.JSON ? node.ruleset.lang : ""}</span></span></div></li>`;