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 Turner0bf8848be580
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.javaindex f7d73dc69..e2525814a 100644--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java@@ -84,8 +84,8 @@ public class JsonRulesBuilder extends RulesBuilder {boolean trackUnmatched;BaseAssetQuery.OrderBy orderBy;int limit;- RuleCondition<AttributePredicate> attributePredicates = null;- RuleTrigger ruleTrigger;+ LogicGroup<AttributePredicate> attributePredicates = null;+ RuleCondition ruleCondition;Set<AssetState> unfilteredAssetStates = new HashSet<>();Set<AssetState> previouslyMatchedAssetStates = new HashSet<>();Set<AssetState> previouslyUnmatchedAssetStates;@@ -96,48 +96,48 @@ public class JsonRulesBuilder extends RulesBuilder {CronExpression timerExpression;RuleTriggerResult lastTriggerResult;- public RuleTriggerState(RuleTrigger ruleTrigger, boolean trackUnmatched, TimerService timerService) {+ public RuleTriggerState(RuleCondition ruleCondition, boolean trackUnmatched, TimerService timerService) {this.timerService = timerService;- this.ruleTrigger = ruleTrigger;+ this.ruleCondition = ruleCondition;this.trackUnmatched = trackUnmatched;if (trackUnmatched) {previouslyUnmatchedAssetStates = new HashSet<>();}- if (ruleTriggerResetHasTimer(ruleTrigger.reset)) {+ if (ruleConditionResetHasTimer(ruleCondition.reset)) {previouslyMatchedExpiryTimes = new HashMap<>();- if (!TextUtil.isNullOrEmpty(ruleTrigger.reset.timer) && TimeUtil.isTimeDuration(ruleTrigger.reset.timer)) {- resetDurationMillis = TimeUtil.parseTimeDuration(ruleTrigger.reset.timer);+ if (!TextUtil.isNullOrEmpty(ruleCondition.reset.timer) && TimeUtil.isTimeDuration(ruleCondition.reset.timer)) {+ resetDurationMillis = TimeUtil.parseTimeDuration(ruleCondition.reset.timer);}}- if (!TextUtil.isNullOrEmpty(ruleTrigger.timer)) {+ if (!TextUtil.isNullOrEmpty(ruleCondition.timer)) {try {- if (TimeUtil.isTimeDuration(ruleTrigger.timer)) {+ if (TimeUtil.isTimeDuration(ruleCondition.timer)) {nextExecuteMillis = timerService.getCurrentTimeMillis();- long duration = TimeUtil.parseTimeDuration(ruleTrigger.timer);+ long duration = TimeUtil.parseTimeDuration(ruleCondition.timer);updateNextExecuteTime = () -> nextExecuteMillis += duration;}- if (CronExpression.isValidExpression(ruleTrigger.timer)) {- timerExpression = new CronExpression(ruleTrigger.timer);+ if (CronExpression.isValidExpression(ruleCondition.timer)) {+ timerExpression = new CronExpression(ruleCondition.timer);nextExecuteMillis = timerExpression.getNextValidTimeAfter(new Date(timerService.getCurrentTimeMillis())).getTime();updateNextExecuteTime = () ->nextExecuteMillis = timerExpression.getNextInvalidTimeAfter(timerExpression.getNextInvalidTimeAfter(new Date(nextExecuteMillis))).getTime();}} catch (Exception e) {- log(Level.SEVERE, "Failed to parse rule trigger timer expression: " + ruleTrigger.timer, e);+ log(Level.SEVERE, "Failed to parse rule trigger timer expression: " + ruleCondition.timer, e);}}// Pull out order, limit and attribute predicates so they can be applied at required times- if (ruleTrigger.assets != null) {- orderBy = ruleTrigger.assets.orderBy;- limit = ruleTrigger.assets.limit;- attributePredicates = ruleTrigger.assets.attributes;- ruleTrigger.assets.orderBy = null;- ruleTrigger.assets.limit = 0;- ruleTrigger.assets.attributes = null;+ if (ruleCondition.assets != null) {+ orderBy = ruleCondition.assets.orderBy;+ limit = ruleCondition.assets.limit;+ attributePredicates = ruleCondition.assets.attributes;+ ruleCondition.assets.orderBy = null;+ ruleCondition.assets.limit = 0;+ ruleCondition.assets.attributes = null;}}@@ -145,15 +145,15 @@ public class JsonRulesBuilder extends RulesBuilder {// Clear last trigger to ensure update runs againlastTriggerResult = null;- if (ruleTrigger.timer != null) {+ if (ruleCondition.timer != null) {unfilteredAssetStates = new HashSet<>(facts.getAssetStates());- } else if (ruleTrigger.assets != null) {- NewAssetQuery query = ruleTrigger.assets;+ } else if (ruleCondition.assets != null) {+ NewAssetQuery query = ruleCondition.assets;unfilteredAssetStates = facts.matchAssetState(query).collect(Collectors.toSet());// Use this opportunity to notify RulesFacts about any location predicatesif (facts.trackLocationRules) {- List<AttributePredicate> flattenedAttributePredicates = RuleCondition.flatten(Collections.singletonList(attributePredicates));+ List<AttributePredicate> flattenedAttributePredicates = LogicGroup.flatten(Collections.singletonList(attributePredicates));facts.storeLocationPredicates(getLocationPredicates(flattenedAttributePredicates));}}@@ -166,7 +166,7 @@ public class JsonRulesBuilder extends RulesBuilder {return;}- if (!TextUtil.isNullOrEmpty(ruleTrigger.timer)) {+ if (!TextUtil.isNullOrEmpty(ruleCondition.timer)) {lastTriggerResult = null;if (updateNextExecuteTime != null && nextExecuteMillis < timerService.getCurrentTimeMillis()) {@@ -211,7 +211,7 @@ public class JsonRulesBuilder extends RulesBuilder {}// Apply reset logic to make previously matched asset states eligible for matching again- if (ruleTrigger.reset == null || ruleTrigger.reset.noLongerMatches) {+ if (ruleCondition.reset == null || ruleCondition.reset.noLongerMatches) {previouslyMatchedAssetStates.removeIf(assetState -> {boolean noLongerMatches = !matchedAssetStates.contains(assetState);if (noLongerMatches) {@@ -221,7 +221,7 @@ public class JsonRulesBuilder extends RulesBuilder {});}- if (ruleTriggerResetHasTimer(ruleTrigger.reset)) {+ if (ruleConditionResetHasTimer(ruleCondition.reset)) {previouslyMatchedAssetStates.removeIf(assetState -> {Long timestamp = previouslyMatchedExpiryTimes.get(assetState);boolean expired = timestamp != null && timerService.getCurrentTimeMillis() > timestamp;@@ -233,7 +233,7 @@ public class JsonRulesBuilder extends RulesBuilder {});}- if (ruleTrigger.reset != null && ruleTrigger.reset.valueChanges) {+ if (ruleCondition.reset != null && ruleCondition.reset.valueChanges) {previouslyMatchedAssetStates.removeIf(previousAssetState -> {int index = matchedAssetStates.indexOf(previousAssetState);if (index < 0) {@@ -334,7 +334,7 @@ public class JsonRulesBuilder extends RulesBuilder {final protected NotificationsFacade notificationFacade;final protected ManagerExecutorService executorService;final protected BiConsumer<Runnable, Long> scheduledActionConsumer;- final protected Map<String, Map<String, RuleTriggerState>> ruleTriggerStateMap = new HashMap<>();+ final protected Map<String, Map<String, RuleTriggerState>> ruleConditionStateMap = new HashMap<>();public JsonRulesBuilder(TimerService timerService, AssetStorageService assetStorageService, ManagerExecutorService executorService, Assets assetsFacade, Users usersFacade, NotificationsFacade notificationFacade, BiConsumer<Runnable, Long> scheduledActionConsumer) {this.timerService = timerService;@@ -347,17 +347,17 @@ public class JsonRulesBuilder extends RulesBuilder {}public void onAssetStatesChanged(RulesFacts facts) {- ruleTriggerStateMap.values().forEach(triggerStateMap -> triggerStateMap.values().forEach(ruleTriggerState -> ruleTriggerState.updateUnfilteredAssetStates(facts)));+ ruleConditionStateMap.values().forEach(triggerStateMap -> triggerStateMap.values().forEach(ruleConditionState -> ruleConditionState.updateUnfilteredAssetStates(facts)));}public JsonRulesBuilder add(Rule rule) {- if (ruleTriggerStateMap.containsKey(rule.name)) {+ if (ruleConditionStateMap.containsKey(rule.name)) {throw new IllegalArgumentException("Rules must have a unique name within a ruleset, rule name '" + rule.name + "' already used");}Map<String, RuleTriggerState> triggerStateMap = new HashMap<>();- ruleTriggerStateMap.put(rule.name, triggerStateMap);+ ruleConditionStateMap.put(rule.name, triggerStateMap);addRuleTriggerState(rule.when, rule.otherwise != null, 0, triggerStateMap, rule.reset);Condition condition = buildLhsCondition(rule, triggerStateMap);@@ -388,22 +388,22 @@ public class JsonRulesBuilder extends RulesBuilder {return this;}- protected void addRuleTriggerState(RuleCondition<RuleTrigger> ruleTriggerCondition, boolean trackUnmatched, int index, Map<String, RuleTriggerState> triggerStateMap, RuleTriggerReset defaultReset) {- if (ruleTriggerCondition != null) {- if (ruleTriggerCondition.predicates != null && ruleTriggerCondition.predicates.length > 0) {- for (RuleTrigger ruleTrigger : ruleTriggerCondition.predicates) {- if (TextUtil.isNullOrEmpty(ruleTrigger.tag)) {- ruleTrigger.tag = Integer.toString(index);+ protected void addRuleTriggerState(LogicGroup<RuleCondition> ruleConditionCondition, boolean trackUnmatched, int index, Map<String, RuleTriggerState> triggerStateMap, RuleConditionReset defaultReset) {+ if (ruleConditionCondition != null) {+ if (ruleConditionCondition.items != null && ruleConditionCondition.items.length > 0) {+ for (RuleCondition ruleCondition : ruleConditionCondition.items) {+ if (TextUtil.isNullOrEmpty(ruleCondition.tag)) {+ ruleCondition.tag = Integer.toString(index);}- if (ruleTrigger.reset == null) {- ruleTrigger.reset = defaultReset;+ if (ruleCondition.reset == null) {+ ruleCondition.reset = defaultReset;}- triggerStateMap.put(ruleTrigger.tag, new RuleTriggerState(ruleTrigger, trackUnmatched, timerService));+ triggerStateMap.put(ruleCondition.tag, new RuleTriggerState(ruleCondition, trackUnmatched, timerService));index++;}}- if (ruleTriggerCondition.conditions != null && ruleTriggerCondition.conditions.length > 0) {- for (RuleCondition<RuleTrigger> childRuleTriggerCondition : ruleTriggerCondition.conditions) {+ if (ruleConditionCondition.groups != null && ruleConditionCondition.groups.length > 0) {+ for (LogicGroup<RuleCondition> childRuleTriggerCondition : ruleConditionCondition.groups) {addRuleTriggerState(childRuleTriggerCondition, trackUnmatched, index, triggerStateMap, defaultReset);}}@@ -455,25 +455,25 @@ public class JsonRulesBuilder extends RulesBuilder {// Push rule trigger results into the trigger state for future runs and store timestamps where requiredif (triggerStateMap != null) {- triggerStateMap.values().forEach(ruleTriggerState -> {- if (ruleTriggerState.lastTriggerResult != null) {+ triggerStateMap.values().forEach(ruleConditionState -> {+ if (ruleConditionState.lastTriggerResult != null) {// Remove any stale matched asset states- ruleTriggerState.previouslyMatchedAssetStates.removeAll(ruleTriggerState.lastTriggerResult.matchedAssetStates);- ruleTriggerState.previouslyMatchedAssetStates.addAll(ruleTriggerState.lastTriggerResult.matchedAssetStates);+ ruleConditionState.previouslyMatchedAssetStates.removeAll(ruleConditionState.lastTriggerResult.matchedAssetStates);+ ruleConditionState.previouslyMatchedAssetStates.addAll(ruleConditionState.lastTriggerResult.matchedAssetStates);- RuleTriggerReset reset = ruleTriggerState.ruleTrigger.reset;- if (ruleTriggerResetHasTimer(reset)) {+ RuleConditionReset reset = ruleConditionState.ruleCondition.reset;+ if (ruleConditionResetHasTimer(reset)) {if (reset.timestampChanges) {- ruleTriggerState.lastTriggerResult.matchedAssetStates.forEach(assetState ->- ruleTriggerState.previouslyMatchedExpiryTimes.put(assetState, assetState.getTimestamp()));- } else if (ruleTriggerState.resetDurationMillis > 0) {- ruleTriggerState.lastTriggerResult.matchedAssetStates.forEach(assetState ->- ruleTriggerState.previouslyMatchedExpiryTimes.put(assetState, timerService.getCurrentTimeMillis() + ruleTriggerState.resetDurationMillis));+ ruleConditionState.lastTriggerResult.matchedAssetStates.forEach(assetState ->+ ruleConditionState.previouslyMatchedExpiryTimes.put(assetState, assetState.getTimestamp()));+ } else if (ruleConditionState.resetDurationMillis > 0) {+ ruleConditionState.lastTriggerResult.matchedAssetStates.forEach(assetState ->+ ruleConditionState.previouslyMatchedExpiryTimes.put(assetState, timerService.getCurrentTimeMillis() + ruleConditionState.resetDurationMillis));}}- if (ruleTriggerState.trackUnmatched) {- ruleTriggerState.previouslyUnmatchedAssetStates.addAll(ruleTriggerState.lastTriggerResult.unmatchedAssetStates);+ if (ruleConditionState.trackUnmatched) {+ ruleConditionState.previouslyUnmatchedAssetStates.addAll(ruleConditionState.lastTriggerResult.unmatchedAssetStates);}}});@@ -754,13 +754,13 @@ public class JsonRulesBuilder extends RulesBuilder {.parent(newQuery.parents != null && newQuery.parents.length > 0 ? newQuery.parents[0] : null).path(newQuery.paths != null && newQuery.paths.length > 0 ? newQuery.paths[0] : null).type(newQuery.types != null && newQuery.types.length > 0 ? newQuery.types[0] : null)- .attributes(newQuery.attributes != null && newQuery.attributes.predicates != null ? newQuery.attributes.predicates : null);+ .attributes(newQuery.attributes != null && newQuery.attributes.items != null ? newQuery.attributes.items : null);}protected static Collection<String> getRuleActionTargetIds(RuleActionTarget target, boolean useUnmatched, Map<String, RuleTriggerState> triggerStateMap, Assets assetsFacade, Users usersFacade) {if (target != null) {- if (!TextUtil.isNullOrEmpty(target.ruleTriggerTag) && triggerStateMap != null) {- RuleTriggerState triggerState = triggerStateMap.get(target.ruleTriggerTag);+ if (!TextUtil.isNullOrEmpty(target.ruleConditionTag) && triggerStateMap != null) {+ RuleTriggerState triggerState = triggerStateMap.get(target.ruleConditionTag);if (!useUnmatched) {return triggerState != null ? triggerState.getMatchedAssetIds() : Collections.emptyList();}@@ -792,46 +792,46 @@ public class JsonRulesBuilder extends RulesBuilder {return Collections.emptyList();}- protected static boolean matches(RuleCondition<RuleTrigger> ruleTriggerCondition, Map<String, RuleTriggerState> triggerStateMap) {+ protected static boolean matches(LogicGroup<RuleCondition> ruleConditionCondition, Map<String, RuleTriggerState> triggerStateMap) {boolean match = false;- if (conditionIsEmpty(ruleTriggerCondition)) {+ if (conditionIsEmpty(ruleConditionCondition)) {return false;}- RuleOperator operator = ruleTriggerCondition.operator == null ? RuleOperator.AND : ruleTriggerCondition.operator;+ RuleOperator operator = ruleConditionCondition.operator == null ? RuleOperator.AND : ruleConditionCondition.operator;if (operator == RuleOperator.AND) {- if (ruleTriggerCondition.predicates != null) {- match = Arrays.stream(ruleTriggerCondition.predicates)- .map(ruleTrigger -> triggerStateMap.get(ruleTrigger.tag))- .allMatch(ruleTriggerState -> ruleTriggerState.lastTriggerResult != null && ruleTriggerState.lastTriggerResult.matches);+ if (ruleConditionCondition.items != null) {+ match = Arrays.stream(ruleConditionCondition.items)+ .map(ruleCondition -> triggerStateMap.get(ruleCondition.tag))+ .allMatch(ruleConditionState -> ruleConditionState.lastTriggerResult != null && ruleConditionState.lastTriggerResult.matches);if (!match) {return false;}}- if (ruleTriggerCondition.conditions != null) {- match = Arrays.stream(ruleTriggerCondition.conditions)+ if (ruleConditionCondition.groups != null) {+ match = Arrays.stream(ruleConditionCondition.groups).allMatch(condition -> matches(condition, triggerStateMap));}}if (operator == RuleOperator.OR) {- if (ruleTriggerCondition.predicates != null) {- match = Arrays.stream(ruleTriggerCondition.predicates)- .map(ruleTrigger -> triggerStateMap.get(ruleTrigger.tag))- .anyMatch(ruleTriggerState -> ruleTriggerState.lastTriggerResult != null && ruleTriggerState.lastTriggerResult.matches);+ if (ruleConditionCondition.items != null) {+ match = Arrays.stream(ruleConditionCondition.items)+ .map(ruleCondition -> triggerStateMap.get(ruleCondition.tag))+ .anyMatch(ruleConditionState -> ruleConditionState.lastTriggerResult != null && ruleConditionState.lastTriggerResult.matches);if (match) {return true;}}- if (ruleTriggerCondition.conditions != null) {- match = Arrays.stream(ruleTriggerCondition.conditions)+ if (ruleConditionCondition.groups != null) {+ match = Arrays.stream(ruleConditionCondition.groups).anyMatch(condition -> matches(condition, triggerStateMap));}}@@ -839,12 +839,12 @@ public class JsonRulesBuilder extends RulesBuilder {return match;}- protected static boolean ruleTriggerResetHasTimer(RuleTriggerReset reset) {+ protected static boolean ruleConditionResetHasTimer(RuleConditionReset reset) {return reset != null && (!TextUtil.isNullOrEmpty(reset.timer) || reset.timestampChanges);}protected static boolean targetIsNotAssets(RuleActionTarget target) {- return target != null && target.assets == null && TextUtil.isNullOrEmpty(target.ruleTriggerTag);+ return target != null && target.users != null;}protected static void log(Level level, String message) {diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.javaindex dce2dbae4..5aa38e40c 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java@@ -34,7 +34,7 @@ import org.openremote.model.query.filter.GeofencePredicate;import org.openremote.model.rules.AssetState;import org.openremote.model.rules.Assets;import org.openremote.model.rules.TemporaryFact;-import org.openremote.model.rules.json.RuleCondition;+import org.openremote.model.rules.json.LogicGroup;import org.openremote.model.util.TimeUtil;import org.openremote.model.value.Value;import org.openremote.model.value.Values;@@ -438,7 +438,7 @@ public class RulesFacts extends Facts implements RuleListener {public Stream<AssetState> matchAssetState(NewAssetQuery assetQuery) {if (trackLocationRules && assetQuery.attributes != null) {- List<AttributePredicate> attributePredicates = RuleCondition.flatten(Collections.singletonList(assetQuery.attributes));+ List<AttributePredicate> attributePredicates = LogicGroup.flatten(Collections.singletonList(assetQuery.attributes));storeLocationPredicates(getLocationPredicates(attributePredicates));}diff --git a/model/src/main/java/org/openremote/model/rules/json/LogicGroup.java b/model/src/main/java/org/openremote/model/rules/json/LogicGroup.javanew file mode 100644index 000000000..cbb3554fa--- /dev/null+++ b/model/src/main/java/org/openremote/model/rules/json/LogicGroup.java@@ -0,0 +1,62 @@+/*+ * 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.model.rules.json;++import java.util.ArrayList;+import java.util.Arrays;+import java.util.List;++public class LogicGroup<T> {++ public LogicGroup() {+ }++ public LogicGroup(RuleOperator operator, T[] items, LogicGroup<T>[] groups) {+ this.operator = operator;+ this.items = items;+ this.groups = groups;+ }++ /**+ * If not specified then {@link RuleOperator#AND} is assumed.+ */+ public RuleOperator operator;++ /**+ * Defines the items that the {@link #operator} should be applied to+ */+ public T[] items;++ /**+ * Nested groups allow for more complex logic with a mix of operators+ */+ public LogicGroup<T>[] groups;++ public static <T> List<T> flatten(List<LogicGroup<T>> conditions) {+ List<T> flattened = new ArrayList<>();+ for (LogicGroup<T> ruleCondition : conditions) {+ flattened.addAll(Arrays.asList(ruleCondition.items));+ if (ruleCondition.groups != null) {+ flattened.addAll(flatten(Arrays.asList(ruleCondition.groups)));+ }+ }+ return flattened;+ }+}diff --git a/model/src/main/java/org/openremote/model/rules/json/Rule.java b/model/src/main/java/org/openremote/model/rules/json/Rule.javaindex b64007472..6ef8c3408 100644--- a/model/src/main/java/org/openremote/model/rules/json/Rule.java+++ b/model/src/main/java/org/openremote/model/rules/json/Rule.java@@ -26,13 +26,13 @@ import org.openremote.model.query.NewAssetQuery;* <p>* <h2>LHS</li>* <p>- * {@link #when} - A series of grouped {@link RuleTrigger}s to which bitwise operations can be performed based on the- * {@link RuleCondition#operator} of each group. These are used to filter {@link org.openremote.model.rules.AssetState}s+ * {@link #when} - A series of grouped {@link RuleCondition}s to which bitwise operations can be performed based on the+ * {@link LogicGroup#operator} of each group. These are used to filter {@link org.openremote.model.rules.AssetState}s* in the RuleEngine that this rule is loaded into to determine which {@link org.openremote.model.asset.Asset}s match;* if one or more assets match then the RHS {@link #then} will be triggered. Once a rule is triggered the* {@link org.openremote.model.rules.AssetState}s that triggered the rule cannot trigger the rule again until it no longer- * matches (within the context of the {@link RuleTrigger} i.e. an {@link org.openremote.model.rules.AssetState} can- * re-trigger a rule if it is matched by a different {@link RuleTrigger})+ * matches (within the context of the {@link RuleCondition} i.e. an {@link org.openremote.model.rules.AssetState} can+ * re-trigger a rule if it is matched by a different {@link RuleCondition})* <p>* The {@link #otherwise} {@link RuleAction}s are applied to the {@link org.openremote.model.asset.Asset}s filtered by* the query that don't match the {@link NewAssetQuery#attributes} predicates.@@ -42,14 +42,13 @@ import org.openremote.model.query.NewAssetQuery;* <h2>RHS</h2>* <p>* {@link #then} - Defines a series of {@link RuleAction}s to perform when the bitwise result of applying all- * {@link RuleTrigger}s in the {@link #when} is true.+ * {@link RuleCondition}s in the {@link #when} is true.* <p>* {@link #otherwise} - Defines a series of {@link RuleAction}s to perform when there is one or more asset that matched rule doesn't match the assets specified* in the {@link Rule#when}. The list of assets this applies to is the assets filtered by applying the* {@link Rule#when} but excluding the {@link NewAssetQuery#attributes} predicates and excluding any assets that match* the entire {@link Rule#when}. If the number of these assets is greater than 0 then these {@link RuleAction}s will be- * executed, if any {@link RuleActionWithTarget#target} is set to {@link RuleActionTarget#useAssetsFromWhen}- * then the assets that caused this to trigger will be used.+ * executed.* <h2>Reset</h2>* <p>* {@link #reset} - Optional logic used to reset the rule, this is applied to each@@ -63,10 +62,10 @@ public class Rule {public String name;public String description;public int priority = Integer.MAX_VALUE-1;- public RuleCondition<RuleTrigger> when;+ public LogicGroup<RuleCondition> when;public RuleAction[] then;public RuleAction[] otherwise;- public RuleTriggerReset reset;+ public RuleConditionReset reset;public RuleAction[] onStart;public RuleAction[] onStop;}diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleActionTarget.java b/model/src/main/java/org/openremote/model/rules/json/RuleActionTarget.javaindex 7b1d70882..73b05c261 100644--- a/model/src/main/java/org/openremote/model/rules/json/RuleActionTarget.java+++ b/model/src/main/java/org/openremote/model/rules/json/RuleActionTarget.java@@ -25,13 +25,13 @@ import org.openremote.model.query.UserQuery;/*** None or one of the options should be set the precedence is:* <ol>- * <li>{@link #ruleTriggerTag}</li>+ * <li>{@link #ruleConditionTag}</li>* <li>{@link #assets}</li>* <li>{@link #users}</li>* </ol>*/public class RuleActionTarget {- public String ruleTriggerTag;+ public String ruleConditionTag;public NewAssetQuery assets;public UserQuery users;}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 28142e639..f16767640 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@@ -19,44 +19,26 @@*/package org.openremote.model.rules.json;-import java.util.ArrayList;-import java.util.Arrays;-import java.util.List;--public class RuleCondition<T> {-- public RuleCondition() {- }-- public RuleCondition(RuleOperator operator, T[] predicates, RuleCondition<T>[] conditions) {- this.operator = operator;- this.predicates = predicates;- this.conditions = conditions;- }-- /**- * If not specified then {@link RuleOperator#AND} is assumed.- */- public RuleOperator operator;-- /**- * Defines the predicates to apply using the {@link #operator}- */- public T[] predicates;-- /**- * Nested conditions allow for more complex logic with a mix of operators- */- public RuleCondition<T>[] conditions;+import org.openremote.model.query.NewAssetQuery;+import org.openremote.model.query.filter.DateTimePredicate;++/**+ * Consists of a timer expression (interval, absolute, CRON etc.) or query for filtering+ * {@link org.openremote.model.rules.AssetState}s, if both are specified then the timer is used.+ * <p>+ * For timer based trigger it evaluates to true if the timer expression matches the current time. For query based trigger+ * it evaluates to true when one or more {@link org.openremote.model.rules.AssetState}s (referencing unique+ * {@link org.openremote.model.asset.Asset}s) are returned after applying the query to the+ * {@link org.openremote.model.rules.AssetState}s in the RuleEngine that this rule is loaded into.+ * <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 {- public static <T> List<T> flatten(List<RuleCondition<T>> conditions) {- List<T> flattened = new ArrayList<>();- for (RuleCondition<T> ruleCondition : conditions) {- flattened.addAll(Arrays.asList(ruleCondition.predicates));- if (ruleCondition.conditions != null) {- flattened.addAll(flatten(Arrays.asList(ruleCondition.conditions)));- }- }- return flattened;- }+ public String timer;+ public DateTimePredicate datetime;+ public NewAssetQuery assets;+ public String tag;+ public RuleConditionReset reset;}diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleTriggerReset.java b/model/src/main/java/org/openremote/model/rules/json/RuleConditionReset.javasimilarity index 98%rename from model/src/main/java/org/openremote/model/rules/json/RuleTriggerReset.javarename to model/src/main/java/org/openremote/model/rules/json/RuleConditionReset.javaindex 2b8bbe7e4..f63544862 100644--- a/model/src/main/java/org/openremote/model/rules/json/RuleTriggerReset.java+++ b/model/src/main/java/org/openremote/model/rules/json/RuleConditionReset.java@@ -25,7 +25,7 @@ package org.openremote.model.rules.json;* <p>* There is an implicit OR condition between each option.*/-public class RuleTriggerReset {+public class RuleConditionReset {/*** Never reset i.e. fire once only for a given {@link org.openremote.model.rules.AssetState}.diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleTrigger.java b/model/src/main/java/org/openremote/model/rules/json/RuleTrigger.javadeleted file mode 100644index 26da0847a..000000000--- a/model/src/main/java/org/openremote/model/rules/json/RuleTrigger.java+++ /dev/null@@ -1,42 +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.model.rules.json;--import org.openremote.model.query.NewAssetQuery;--/**- * Consists of a timer expression (interval, absolute, CRON etc.) or query for filtering- * {@link org.openremote.model.rules.AssetState}s, if both are specified then the timer is used.- * <p>- * For timer based trigger it evaluates to true if the timer expression matches the current time. For query based trigger- * it evaluates to true when one or more {@link org.openremote.model.rules.AssetState}s (referencing unique- * {@link org.openremote.model.asset.Asset}s) are returned after applying the query to the- * {@link org.openremote.model.rules.AssetState}s in the RuleEngine that this rule is loaded into.- * <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 RuleTrigger {-- public String timer;- public NewAssetQuery assets;- public String tag;- public RuleTriggerReset reset;-}