Skip to content

armgit / core

Public Imported from GitHub
0

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

Initial commit of JSON rules (WIP)

Rich Turner6baec89d8be0
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
new file mode 100644
index 000000000..0d1ef27f7
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
@@ -0,0 +1,484 @@
+/*
+ * Copyright 2018, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.rules;
+
+import org.openremote.container.timer.TimerService;
+import org.openremote.manager.asset.AssetStorageService;
+import org.openremote.model.attribute.Meta;
+import org.openremote.model.query.filter.AttributeMetaPredicate;
+import org.openremote.model.rules.AssetState;
+import org.openremote.model.rules.json.Rule;
+import org.openremote.model.rules.json.RuleCondition;
+import org.openremote.model.rules.json.RuleOperator;
+import org.openremote.model.rules.json.RuleTriggerReset;
+import org.openremote.model.rules.json.predicate.AssetPredicate;
+import org.openremote.model.rules.json.predicate.AttributePredicate;
+import org.openremote.model.util.TextUtil;
+import org.openremote.model.value.Value;
+
+import java.util.*;
+import java.util.function.BiPredicate;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+public class JsonRulesBuilder extends RulesBuilder {
+
+ public static class RuleFiredInfo {
+ AssetState firedAssetState;
+
+ }
+
+ final protected AssetStorageService assetStorageService;
+ final protected TimerService timerService;
+
+ public JsonRulesBuilder(TimerService timerService, AssetStorageService assetStorageService) {
+ this.timerService = timerService;
+ this.assetStorageService = assetStorageService;
+ }
+
+ public JsonRulesBuilder add(Rule rule) {
+
+ final Predicate<AssetState> assetStatePredicate = rule.when != null && rule.when.asset != null
+ ? asPredicate(timerService, assetStorageService, rule.when.asset) : null;
+
+ Condition condition = buildLhsCondition(rule, assetStatePredicate);
+ Action action = buildAction(rule);
+
+ if (condition == null || action == null) {
+ throw new IllegalArgumentException("Error building JSON rule '" + rule.name + "'");
+ }
+
+ add()
+ .name(rule.name)
+ .description(rule.description)
+ .priority(rule.priority)
+ .when(facts -> {
+ Object result;
+ try {
+ result = condition.evaluate(facts);
+ } catch (Exception ex) {
+ throw new RuntimeException("Error evaluating condition of rule '" + rule.name + "': " + ex.getMessage(), ex);
+ }
+ if (result instanceof Boolean) {
+ return result;
+ } else {
+ throw new IllegalArgumentException("Error evaluating condition of rule '" + rule.name + "': result is not boolean but " + result);
+ }
+ })
+ .then(action);
+
+ Condition resetCondition = buildResetCondition(rule, assetStatePredicate);
+
+
+ return this;
+ }
+
+ protected Condition buildLhsCondition(Rule rule, Predicate<AssetState> assetStatePredicate) {
+ if (rule.when == null || (rule.when.asset == null && rule.when.timer == null)) {
+ return facts -> false;
+ }
+
+ Predicate<RulesFacts> whenPredicate = facts -> false;
+ Predicate<RulesFacts> andPredicate = facts -> true;
+
+ if (rule.when.asset != null) {
+
+
+ whenPredicate = facts -> {
+
+ List<AssetState> assetStates = new ArrayList<>(facts.getAssetStates());
+
+ assetStates.removeIf(as -> assetStatePredicate.negate().test(as));
+
+ if (assetStates.isEmpty()) {
+ return false;
+ }
+
+ // Apply reset predicate (to prevent re-running a rule on an asset state before the reset has triggered)
+ assetStates.removeIf(as -> {
+ String factName = buildResetFactName(rule, as);
+ return facts.getOptional(factName).isPresent();
+ });
+ if (assetStates.isEmpty()) {
+ return false;
+ }
+
+ if (rule.when.asset.matchOrder != null) {
+ assetStates.sort(asComparator(rule.when.asset.matchOrder));
+ }
+
+ if (rule.when.asset.matchLimit > 0) {
+ int limit = Math.min(assetStates.size(), rule.when.asset.matchLimit);
+ assetStates = assetStates.subList(0, limit);
+ }
+
+ // Push matched asset states into RHS
+ facts.bind("assetStates", assetStates);
+
+ if (!assetStates.isEmpty()) {
+ // Push matched asset states into RHS
+ facts.bind("assetStates", assetStates);
+ return true;
+ }
+
+ return false;
+ };
+ } else if (!TextUtil.isNullOrEmpty(rule.when.timer)) {
+ // TODO: Create timer condition
+ }
+
+ if (rule.and != null) {
+ andPredicate = asPredicate(timerService, assetStorageService, rule.and);
+ }
+
+
+ Predicate<RulesFacts> finalWhenPredicate = whenPredicate;
+ Predicate<RulesFacts> finalAndPredicate = andPredicate;
+
+ return facts -> {
+ if (!finalWhenPredicate.test(facts)) {
+ return false;
+ }
+
+ if (!finalAndPredicate.test(facts)) {
+ return false;
+ }
+
+ return true;
+ };
+ }
+
+ // TODO: Implement action
+ protected Action buildAction(Rule rule) {
+ // If reset then add RuleFireInfo as temporary fact
+ return facts -> {};
+ }
+
+ protected Condition buildResetCondition(Rule rule, Predicate<AssetState> assetStatePredicate) {
+
+ // Timer only reset is handled in rule action with temporary fact other resets require rule.when.asset to be set
+ // so that we have
+ if (rule.reset == null || assetStatePredicate == null
+ || (!rule.reset.triggerNoLongerMatches && rule.reset.attributeTimestampChange == null
+ && rule.reset.attributeValueChange == null)) {
+
+ return null;
+ }
+
+ RuleTriggerReset reset = rule.reset;
+
+ Predicate<AssetState> noLongerMatchesPredicate = ruleFiredInfo -> false;
+ BiPredicate<AssetState, RuleFiredInfo> attributeTimestampPredicate = (assetState, ruleFiredInfo) -> false;
+ BiPredicate<AssetState, RuleFiredInfo> attributeValuePredicate = (assetState, ruleFiredInfo) -> false;
+
+ if (reset.triggerNoLongerMatches) {
+ noLongerMatchesPredicate = assetState -> assetStatePredicate.negate().test(assetState);
+ }
+
+ if (reset.attributeTimestampChange != null) {
+ attributeTimestampPredicate = (assetState, ruleFiredInfo) -> {
+ long firedTimestamp = ruleFiredInfo.firedAssetState.getTimestamp();
+ long currentTimestamp = assetState.getTimestamp();
+ return firedTimestamp != currentTimestamp;
+ };
+ }
+
+ if (reset.attributeValueChange != null) {
+ attributeValuePredicate = (assetState, ruleFiredInfo) -> {
+ Value firedValue = ruleFiredInfo.firedAssetState.getValue().orElse(null);
+ Value currentValue = assetState.getValue().orElse(null);
+ return !Objects.equals(firedValue, currentValue);
+ };
+ }
+
+ Predicate<AssetState> finalNoLongerMatchesPredicate = noLongerMatchesPredicate;
+ BiPredicate<AssetState, RuleFiredInfo> finalAttributeTimestampPredicate = attributeTimestampPredicate;
+ BiPredicate<AssetState, RuleFiredInfo> finalAttributeValuePredicate = attributeValuePredicate;
+
+ BiPredicate<AssetState, RuleFiredInfo> resetPredicate = (assetState, ruleFiredInfo) ->
+ finalNoLongerMatchesPredicate.test(assetState)
+ || finalAttributeTimestampPredicate.test(assetState, ruleFiredInfo)
+ || finalAttributeValuePredicate.test(assetState, ruleFiredInfo);
+
+ return facts -> {
+ List<String> resetAssetStates = facts.getAssetStates()
+ .stream()
+ .filter(as -> {
+
+ String factName = buildResetFactName(rule, as);
+ Optional<RuleFiredInfo> firedInfo = facts.getOptional(factName);
+
+ return firedInfo.filter(ruleFiredInfo -> resetPredicate.test(as, ruleFiredInfo)).isPresent();
+
+ })
+ .map(as -> buildResetFactName(rule, as))
+ .collect(Collectors.toList());
+
+ if (resetAssetStates.isEmpty()) {
+ return false;
+ }
+
+ facts.bind("resetAssetStates", resetAssetStates);
+ return true;
+ };
+ }
+
+ protected Action buildResetAction() {
+ return facts -> {
+ List<String> resetAssets = facts.bound("resetAssetStates");
+ if (resetAssets != null) {
+ resetAssets.forEach(facts::remove);
+ }
+ };
+ }
+
+ protected static Predicate<RulesFacts> asPredicate(TimerService timerService, AssetStorageService assetStorageService, RuleCondition<AssetPredicate> condition) {
+
+ if ((condition.predicates == null || condition.predicates.length == 0)
+ && (condition.conditions == null || condition.conditions.length == 0)) {
+ return facts -> true;
+ }
+
+ RuleOperator operator = condition.operator == null ? RuleOperator.AND : condition.operator;
+
+ List<Predicate<RulesFacts>> assetPredicates = new ArrayList<>();
+
+ if (condition.predicates != null && condition.predicates.length > 0) {
+ assetPredicates.addAll(
+ Arrays.stream(condition.predicates)
+ .map(p -> {
+ Predicate<AssetState> assetStatePredicate = asPredicate(timerService, assetStorageService, p);
+ return (Predicate<RulesFacts>) facts -> {
+ List<AssetState> assetStates = new ArrayList<>(facts.getAssetStates());
+ assetStates.removeIf(as -> assetStatePredicate.negate().test(as));
+ return !assetStates.isEmpty();
+ };
+ }).collect(Collectors.toList())
+ );
+ }
+
+ if (condition.conditions != null && condition.conditions.length > 0) {
+ assetPredicates.addAll(
+ Arrays.stream(condition.conditions)
+ .map(c -> asPredicate(timerService, assetStorageService, c)).collect(Collectors.toList())
+ );
+ }
+
+ return asPredicate(assetPredicates, operator);
+ }
+
+ protected static Predicate<AssetState> asPredicate(Supplier<Long> currentMillisProducer, RuleCondition<AttributePredicate> condition) {
+ if ((condition.predicates == null || condition.predicates.length == 0)
+ && (condition.conditions == null || condition.conditions.length == 0)) {
+ return as -> true;
+ }
+
+ RuleOperator operator = condition.operator == null ? RuleOperator.AND : condition.operator;
+
+ List<Predicate<AssetState>> assetStatePredicates = new ArrayList<>();
+
+ if (condition.predicates != null && condition.predicates.length > 0) {
+ assetStatePredicates.addAll(
+ Arrays.stream(condition.predicates)
+ .map(p -> asPredicate(currentMillisProducer, p)).collect(Collectors.toList())
+ );
+ }
+
+ if (condition.conditions != null && condition.conditions.length > 0) {
+ assetStatePredicates.addAll(
+ Arrays.stream(condition.conditions)
+ .map(c -> asPredicate(currentMillisProducer, c)).collect(Collectors.toList())
+ );
+ }
+
+ return asPredicate(assetStatePredicates, operator);
+ }
+
+ public static Predicate<AssetState> asPredicate(TimerService timerService, AssetStorageService assetStorageService, AssetPredicate pred) {
+
+ return assetState -> {
+ if (pred.ids != null && pred.ids.length > 0) {
+ if (Arrays.stream(pred.ids).noneMatch(id -> assetState.getId().equals(id))) {
+ return false;
+ }
+ }
+
+ if (pred.names != null && pred.names.length > 0) {
+ if (Arrays.stream(pred.names)
+ .map(AssetQueryPredicate::asPredicate)
+ .noneMatch(np -> np.test(assetState.getName()))) {
+ return false;
+ }
+ }
+
+ if (pred.parents != null && pred.parents.length > 0) {
+ if (Arrays.stream(pred.parents)
+ .map(AssetQueryPredicate::asPredicate)
+ .noneMatch(np -> np.test(assetState))) {
+ return false;
+ }
+ }
+
+ if (pred.types != null && pred.types.length > 0) {
+ if (Arrays.stream(pred.types)
+ .map(AssetQueryPredicate::asPredicate)
+ .noneMatch(np -> np.test(assetState.getTypeString()))) {
+ return false;
+ }
+ }
+
+ if (pred.paths != null && pred.paths.length > 0) {
+ if (Arrays.stream(pred.paths)
+ .map(AssetQueryPredicate::asPredicate)
+ .noneMatch(np -> np.test(assetState.getPath()))) {
+ return false;
+ }
+ }
+
+ if (pred.tenant != null) {
+ if (!AssetQueryPredicate.asPredicate(pred.tenant).test(assetState)) {
+ return false;
+ }
+ }
+
+ if (pred.attributes != null) {
+ if (!asPredicate(timerService::getCurrentTimeMillis, pred.attributes).test(assetState)) {
+ return false;
+ }
+ }
+
+ // Apply user ID predicate last as it is the most expensive
+ if (pred.userIds != null && pred.userIds.length > 0) {
+ if (!assetStorageService.isUserAsset(Arrays.asList(pred.userIds), assetState.getId())) {
+ return false;
+ }
+ }
+
+ return true;
+ };
+ }
+
+ public static Predicate<AssetState> asPredicate(Supplier<Long> currentMillsProducer, AttributePredicate pred) {
+
+ Predicate<String> namePredicate = pred.name != null
+ ? AssetQueryPredicate.asPredicate(pred.name) : str -> true;
+
+ Predicate<Meta> metaPredicate = meta -> {
+
+ if (pred.meta == null || pred.meta.length == 0) {
+ return true;
+ }
+
+ for (AttributeMetaPredicate p : pred.meta) {
+ if (!AssetQueryPredicate.asPredicate(currentMillsProducer, p).test(meta)) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ Predicate<Value> valuePredicate = value -> {
+ if (pred.value == null) {
+ return true;
+ }
+ return AssetQueryPredicate.asPredicate(currentMillsProducer, pred.value).test(value);
+ };
+
+ Predicate<Value> oldValuePredicate = value -> {
+ if (pred.lastValue == null) {
+ return true;
+ }
+ return AssetQueryPredicate.asPredicate(currentMillsProducer, pred.lastValue).test(value);
+ };
+
+ return assetState -> namePredicate.test(assetState.getName())
+ && metaPredicate.test(assetState.getMeta())
+ && valuePredicate.test(assetState.getValue().orElse(null))
+ && oldValuePredicate.test(assetState.getOldValue().orElse(null));
+ }
+
+ public static Comparator<AssetState> asComparator(AssetPredicate.MatchOrder matchOrder) {
+
+ Function<AssetState, String> keyExtractor = AssetState::getName;
+ boolean reverse = false;
+
+ switch (matchOrder) {
+ case NAME_REVERSED:
+ reverse = true;
+ case NAME:
+ keyExtractor = AssetState::getName;
+ break;
+ case ATTRIBUTE_REVERSE:
+ reverse = true;
+ case ATTRIBUTE:
+ keyExtractor = AssetState::getAttributeName;
+ break;
+ case NAME_AND_ATTRIBUTE_REVERSED:
+ reverse = true;
+ case NAME_AND_ATTRIBUTE:
+ keyExtractor = as -> as.getName() + as.getAttributeName();
+ break;
+ case ATTRIBUTE_AND_NAME_REVERSED:
+ reverse = true;
+ case ATTRIBUTE_AND_NAME:
+ keyExtractor = as -> as.getAttributeName() + as.getName();
+ break;
+ }
+
+ Comparator<AssetState> comparator = Comparator.comparing(keyExtractor);
+
+ if (reverse) {
+ comparator = comparator.reversed();
+ }
+
+ return comparator;
+ }
+
+ protected static <T> Predicate<T> asPredicate(List<Predicate<T>> predicates, RuleOperator operator) {
+ return in -> {
+ boolean matched = false;
+
+ for (Predicate<T> p : predicates) {
+
+ if (p.test(in)) {
+ matched = true;
+
+ if (operator == RuleOperator.OR) {
+ break;
+ }
+ } else {
+ matched = false;
+
+ if (operator == RuleOperator.AND) {
+ break;
+ }
+ }
+ }
+
+ return matched;
+ };
+ }
+
+ protected static String buildResetFactName(Rule rule, AssetState assetState) {
+ return rule.name + "_" + assetState.getId() + "_" + assetState.getAttributeName();
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
index cfaff9520..34db97f67 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
@@ -31,6 +31,7 @@ import org.jeasy.rules.api.Rules;
import org.jeasy.rules.core.RuleBuilder;
import org.kohsuke.groovy.sandbox.GroovyValueFilter;
import org.kohsuke.groovy.sandbox.SandboxTransformer;
+import org.openremote.container.Container;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.rules.facade.NotificationsFacade;
@@ -38,8 +39,10 @@ import org.openremote.model.rules.Assets;
import org.openremote.model.rules.Ruleset;
import org.openremote.model.rules.RulesetStatus;
import org.openremote.model.rules.Users;
+import org.openremote.model.rules.json.JsonRulesetDefinition;
import javax.script.*;
+import java.io.IOException;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -152,10 +155,26 @@ public class RulesetDeployment {
return registerRulesJavascript(ruleset, assetsFacade, usersFacade, notificationFacade);
case GROOVY:
return registerRulesGroovy(ruleset, assetsFacade, usersFacade, notificationFacade);
+ case JSON:
+ return registerRulesJson(ruleset);
}
return false;
}
+ private boolean registerRulesJson(Ruleset ruleset) {
+ try {
+ JsonRulesetDefinition simpleRulesetDefinition = Container.JSON.readValue(ruleset.getRules(), JsonRulesetDefinition.class);
+
+ JsonRulesBuilder simpleRulesBuilder = new JsonRulesBuilder(timerService, assetStorageService);
+ return true;
+
+ } catch (IOException e) {
+ RulesEngine.LOG.log(Level.SEVERE, "Error evaluating ruleset: " + ruleset, e);
+ setError(e);
+ return false;
+ }
+ }
+
public boolean registerRulesJavascript(Ruleset ruleset, Assets assetsFacade, Users usersFacade, NotificationsFacade consolesFacade) {
// TODO https://github.com/pfisterer/scripting-sandbox/blob/master/src/main/java/de/farberg/scripting/sandbox/ScriptingSandbox.java
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn");
diff --git a/model/src/main/java/org/openremote/model/rules/Ruleset.java b/model/src/main/java/org/openremote/model/rules/Ruleset.java
index eca85261e..1698bff5f 100644
--- a/model/src/main/java/org/openremote/model/rules/Ruleset.java
+++ b/model/src/main/java/org/openremote/model/rules/Ruleset.java
@@ -19,12 +19,14 @@
*/
package org.openremote.model.rules;
+import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
+
import java.util.Date;
import java.util.Optional;
@@ -98,7 +100,31 @@ public abstract class Ruleset {
" facts.updateAssetState(\n" +
" facts.bound(\"assetId\") as String, \"someAttribute\", \"bar\"\n" +
" )\n" +
- " })");
+ " })"),
+ JSON(".json",
+ "locations: [],\n" +
+ "rules: [\n" +
+ " {\n" +
+ " name: \"Test Rule\",\n" +
+ " when: {\n" +
+ " operator: \"AND\",\n" +
+ " predicates: [\n" +
+ " {\n" +
+ " query: {\n" +
+ "\n" +
+ " }\n" +
+ " }\n" +
+ " ],\n" +
+ " conditions: []\n" +
+ " },\n" +
+ " then: {\n" +
+ " notifications: [],\n" +
+ " attributeEvents: []\n" +
+ " },\n" +
+ " reset: null // Only trigger once ever\n" +
+ " }\n" +
+ "]"
+ );
final String fileExtension;
final String emptyRulesExample;
diff --git a/model/src/main/java/org/openremote/model/rules/json/JsonRulesetDefinition.java b/model/src/main/java/org/openremote/model/rules/json/JsonRulesetDefinition.java
new file mode 100644
index 000000000..51b56bf36
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/JsonRulesetDefinition.java
@@ -0,0 +1,24 @@
+/*
+ * 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;
+
+public class JsonRulesetDefinition {
+ protected Rule[] rules;
+}
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.java
new file mode 100644
index 000000000..62ba741e7
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/Rule.java
@@ -0,0 +1,61 @@
+/*
+ * 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.rules.json.predicate.AssetPredicate;
+
+/**
+ * A declarative rule definition (a.k.a. JSON rules); consists of:
+ * <p>
+ * <h2>LHS</li>
+ * <p>
+ * {@link #when}* - This can be either a {@link RuleTrigger#timer} for time based rules or an {@link AssetPredicate}
+ * which will be used to filter {@link org.openremote.model.rules.AssetState}s currently available in the rule engine
+ * that this rule is loaded into. The {@link AssetPredicate} will evaluate to true when one or more
+ * {@link org.openremote.model.rules.AssetState}s are returned by applying the filter. The returned
+ * {@link org.openremote.model.rules.AssetState}s are then used as context for the RHS and also the
+ * {@link RuleTriggerReset} (if specified).
+ * <p>
+ * {@link #and} - Optional condition that can be used to further restrict the LHS but without affecting the
+ * {@link org.openremote.model.rules.AssetState}s that form the context for the RHS. If this is specified then the
+ * {@link #when} must evaluate to true and this condition must evaluate to true.
+ * <h2>RHS</h2>
+ * <p>
+ * {@link #then}* - Defines a series of {@link RuleAction}s to perform when the rule triggers.
+ * <h2>Reset</h2>
+ * <p>
+ * {@link #reset}* - Optional logic used to reset the rule, this is applied to each
+ * {@link org.openremote.model.rules.AssetState} that was returned by the {@link #when}. If no reset is specified then
+ * it is assumed that the rule is fire once per matched {@link org.openremote.model.rules.AssetState}.
+ * <b>NOTE: Rule trigger history is not persisted so on system restart this information is lost and a rule will be
+ * able to fire again.</b>
+ * <p>
+ * <b>* = Required</b>
+ */
+public class Rule {
+
+ public String name;
+ public String description;
+ public int priority = Integer.MAX_VALUE-1;
+ public RuleTrigger when;
+ public RuleCondition<AssetPredicate> and;
+ public RuleAction[] then;
+ public RuleTriggerReset reset;
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleAction.java b/model/src/main/java/org/openremote/model/rules/json/RuleAction.java
new file mode 100644
index 000000000..99261ef0d
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleAction.java
@@ -0,0 +1,36 @@
+/*
+ * 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 com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+
+@JsonSubTypes({
+ @JsonSubTypes.Type(value = RuleActionWait.class, name = "wait"),
+ @JsonSubTypes.Type(value = RuleActionWriteAttribute.class, name = "write-attribute"),
+ @JsonSubTypes.Type(value = RuleActionNotification.class, name = "notification")
+})
+@JsonTypeInfo(
+ use = JsonTypeInfo.Id.NAME,
+ property = "action"
+)
+public interface RuleAction {
+
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleActionNotification.java b/model/src/main/java/org/openremote/model/rules/json/RuleActionNotification.java
new file mode 100644
index 000000000..4da162fb2
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleActionNotification.java
@@ -0,0 +1,26 @@
+/*
+ * 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.notification.AbstractNotificationMessage;
+
+public class RuleActionNotification extends RuleActionWithTarget {
+ protected AbstractNotificationMessage notification;
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleActionWait.java b/model/src/main/java/org/openremote/model/rules/json/RuleActionWait.java
new file mode 100644
index 000000000..d04578e55
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleActionWait.java
@@ -0,0 +1,24 @@
+/*
+ * 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;
+
+public class RuleActionWait implements RuleAction {
+ protected long millis;
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleActionWithTarget.java b/model/src/main/java/org/openremote/model/rules/json/RuleActionWithTarget.java
new file mode 100644
index 000000000..08d288117
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleActionWithTarget.java
@@ -0,0 +1,34 @@
+/*
+ * 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.AssetQuery;
+import org.openremote.model.query.UserQuery;
+
+public abstract class RuleActionWithTarget implements RuleAction {
+
+ public static class Target {
+ protected boolean useAssetsFromWhen;
+ protected AssetQuery assets;
+ protected UserQuery users;
+ }
+
+ protected Target target;
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleActionWriteAttribute.java b/model/src/main/java/org/openremote/model/rules/json/RuleActionWriteAttribute.java
new file mode 100644
index 000000000..3c04d648a
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleActionWriteAttribute.java
@@ -0,0 +1,27 @@
+/*
+ * 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.value.Value;
+
+public class RuleActionWriteAttribute extends RuleActionWithTarget {
+ protected String attributeName;
+ protected Value value;
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java b/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java
new file mode 100644
index 000000000..e0a93cb3c
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java
@@ -0,0 +1,38 @@
+/*
+ * 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;
+
+public class RuleCondition<T> {
+
+ /**
+ * 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;
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleOperator.java b/model/src/main/java/org/openremote/model/rules/json/RuleOperator.java
new file mode 100644
index 000000000..18b81de3f
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleOperator.java
@@ -0,0 +1,25 @@
+/*
+ * 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;
+
+public enum RuleOperator {
+ AND,
+ OR
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleTemplate.java b/model/src/main/java/org/openremote/model/rules/json/RuleTemplate.java
new file mode 100644
index 000000000..6ad722d93
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleTemplate.java
@@ -0,0 +1,26 @@
+/*
+ * 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;
+
+public class RuleTemplate<T> {
+
+ protected String name;
+ protected T value;
+}
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.java
new file mode 100644
index 000000000..fb053becb
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleTrigger.java
@@ -0,0 +1,36 @@
+/*
+ * 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.rules.json.predicate.AssetPredicate;
+
+/**
+ * There are two types of trigger supported and only one should be specified if both are specified then {@link #asset}
+ * trigger will be used.
+ * <ul>
+ * <li>{@link #asset} see {@link AssetPredicate}</li>
+ * <li>{@link #timer} Allows timer expressions to be specified and thus creating a time based rule (e.g. "1h")</li>
+ * </ul>
+ */
+public class RuleTrigger {
+
+ public AssetPredicate asset;
+ public String timer;
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleTriggerReset.java b/model/src/main/java/org/openremote/model/rules/json/RuleTriggerReset.java
new file mode 100644
index 000000000..d9320e76d
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleTriggerReset.java
@@ -0,0 +1,53 @@
+/*
+ * 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.filter.StringPredicate;
+
+/**
+ * This defines when an {@link org.openremote.model.rules.AssetState} becomes eligible for triggering the rule again once
+ * if has triggered a rule.
+ * <p>
+ * There is an implicit OR condition between each option.
+ */
+public class RuleTriggerReset {
+
+ /**
+ * Simple timer expression e.g. '1h'
+ */
+ public String timer;
+
+ /**
+ * When the {@link Rule#when} {@link org.openremote.model.rules.json.predicate.AssetPredicate} evaluates to true.
+ */
+ public boolean triggerNoLongerMatches;
+
+ /**
+ * When the timestamp of the {@link org.openremote.model.rules.AssetState} changes in comparison to the timestamp
+ * at the time the rule fired.
+ */
+ public StringPredicate attributeTimestampChange;
+
+ /**
+ * When the value of the {@link org.openremote.model.rules.AssetState} changes in comparison to the value at the
+ * time the rule fired.
+ */
+ public StringPredicate attributeValueChange;
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/predicate/AssetPredicate.java b/model/src/main/java/org/openremote/model/rules/json/predicate/AssetPredicate.java
new file mode 100644
index 000000000..bdb92730a
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/predicate/AssetPredicate.java
@@ -0,0 +1,73 @@
+/*
+ * 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.predicate;
+
+import org.openremote.model.query.filter.ParentPredicate;
+import org.openremote.model.query.filter.PathPredicate;
+import org.openremote.model.query.filter.StringPredicate;
+import org.openremote.model.query.filter.TenantPredicate;
+import org.openremote.model.rules.json.RuleCondition;
+
+/**
+ * <p>
+ * This predicate is designed to filter the {@link org.openremote.model.rules.AssetState}s and will evaluate to true
+ * if after applying the filtering one or more {@link org.openremote.model.rules.AssetState}s are returned.
+ * <p>
+ * The {@link org.openremote.model.asset.Asset}s associated with the returned {@link org.openremote.model.rules.AssetState}s
+ * are then used as the context for any {@link org.openremote.model.rules.json.RuleTriggerReset} to control when the
+ * {@link AssetPredicate} is allowed to be applied again to the same asset. They can also optionally be used as context
+ * in the {@link org.openremote.model.rules.json.RuleActionWithTarget.Target}, to apply an action to the matched
+ * {@link org.openremote.model.asset.Asset}s.
+ * <p>
+ * There is an implicit AND between properties and an implicit OR between each value of a property.
+ */
+public class AssetPredicate {
+
+ public enum MatchOrder {
+ NAME,
+ NAME_REVERSED,
+ ATTRIBUTE,
+ ATTRIBUTE_REVERSE,
+ NAME_AND_ATTRIBUTE,
+ NAME_AND_ATTRIBUTE_REVERSED,
+ ATTRIBUTE_AND_NAME,
+ ATTRIBUTE_AND_NAME_REVERSED
+ }
+
+ public String[] ids;
+ public StringPredicate[] names;
+ public ParentPredicate[] parents;
+ public PathPredicate[] paths;
+ public TenantPredicate tenant;
+ public String[] userIds;
+ public StringPredicate[] types;
+ public RuleCondition<AttributePredicate> attributes;
+
+ /**
+ * To be used in combination with {@link #matchLimit} to control the ordering of {@link org.openremote.model.rules.AssetState}s
+ * before applying the limit.
+ */
+ public MatchOrder matchOrder;
+
+ /**
+ * Means that only this number of matching {@link org.openremote.model.rules.AssetState} will be passed through as the context.
+ */
+ public int matchLimit;
+}
diff --git a/model/src/main/java/org/openremote/model/rules/json/predicate/AttributePredicate.java b/model/src/main/java/org/openremote/model/rules/json/predicate/AttributePredicate.java
new file mode 100644
index 000000000..ea5d2ff69
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/json/predicate/AttributePredicate.java
@@ -0,0 +1,37 @@
+/*
+ * 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.predicate;
+
+import org.openremote.model.query.filter.AttributeMetaPredicate;
+import org.openremote.model.query.filter.DateTimePredicate;
+import org.openremote.model.query.filter.StringPredicate;
+import org.openremote.model.query.filter.ValuePredicate;
+
+/**
+ * There is an implicit AND condition between each value
+ */
+// TODO: Introduce value converter functionality and merge with existing AttributePredicate
+public class AttributePredicate {
+ public StringPredicate name;
+ public AttributeMetaPredicate[] meta;
+ public ValuePredicate value;
+ public ValuePredicate lastValue;
+ public DateTimePredicate valueTimestamp;
+}
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceLightsOnGeofenceTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceLightsOnGeofenceTest.groovy
new file mode 100644
index 000000000..ce6a19409
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceLightsOnGeofenceTest.groovy
@@ -0,0 +1,176 @@
+package org.openremote.test.rules.residence
+
+import org.junit.Ignore
+import org.openremote.manager.asset.AssetProcessingService
+import org.openremote.manager.asset.AssetStorageService
+import org.openremote.manager.rules.RulesEngine
+import org.openremote.manager.rules.RulesService
+import org.openremote.manager.rules.RulesetStorageService
+import org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapter
+import org.openremote.manager.setup.SetupService
+import org.openremote.manager.setup.builtin.KeycloakDemoSetup
+import org.openremote.manager.setup.builtin.ManagerDemoSetup
+import org.openremote.model.asset.AssetResource
+import org.openremote.model.console.ConsoleProvider
+import org.openremote.model.console.ConsoleRegistration
+import org.openremote.model.console.ConsoleResource
+import org.openremote.model.geo.GeoJSONPoint
+import org.openremote.model.rules.Ruleset
+import org.openremote.model.rules.TenantRuleset
+import org.openremote.model.value.ObjectValue
+import org.openremote.test.ManagerContainerTrait
+import spock.lang.Specification
+import spock.util.concurrent.PollingConditions
+
+import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_CUSTOMER_A
+import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
+import static org.openremote.model.attribute.AttributeType.LOCATION
+import static org.openremote.model.value.Values.parse
+
+@Ignore
+class ResidenceLightsOnGeofenceTest extends Specification implements ManagerContainerTrait {
+
+ def "Turn all lights off when console exits the residence geofence"() {
+
+ given: "the container environment is started"
+ def conditions = new PollingConditions(timeout: 10, delay: 1)
+ def serverPort = findEphemeralPort()
+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())
+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
+ def rulesService = container.getService(RulesService.class)
+ def rulesetStorageService = container.getService(RulesetStorageService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
+ RulesEngine customerAEngine
+
+ and: "some rules"
+ Ruleset ruleset = new TenantRuleset(
+ "Demo Apartment - All Lights Off",
+ keycloakDemoSetup.customerATenant.id,
+ getClass().getResource("/org/openremote/test/rules/BasicLocationPredicates.json").text,
+ Ruleset.Lang.SIMPLE
+ )
+ rulesetStorageService.merge(ruleset)
+
+ expect: "the rule engines to become available and be running with asset states inserted"
+ conditions.eventually {
+ customerAEngine = rulesService.tenantEngines.get(keycloakDemoSetup.customerATenant.id)
+ assert customerAEngine != null
+ assert customerAEngine.isRunning()
+ assert customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A
+ }
+
+ and: "the room lights in an apartment to be on"
+ conditions.eventually {
+ def livingroomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
+ assert livingroomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()
+ def bathRoomAsset = assetStorageService.find(managerDemoSetup.apartment2BathroomId, true)
+ assert bathRoomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()
+ }
+
+ when: "a user authenticates"
+ def accessToken = authenticate(
+ container,
+ keycloakDemoSetup.customerATenant.realm,
+ KEYCLOAK_CLIENT_ID,
+ "testuser3",
+ "testuser3"
+ ).token
+
+ and: "a console is registered by that user"
+ def authenticatedConsoleResource = getClientTarget(serverUri(serverPort), keycloakDemoSetup.customerATenant.realm, accessToken).proxy(ConsoleResource.class)
+ def authenticatedAssetResource = getClientTarget(serverUri(serverPort), keycloakDemoSetup.customerATenant.realm, accessToken).proxy(AssetResource.class)
+ def consoleRegistration = new ConsoleRegistration(null,
+ "Test Console",
+ "1.0",
+ "Android 7.0",
+ new HashMap<String, ConsoleProvider>() {
+ {
+ put("geofence", new ConsoleProvider(
+ ORConsoleGeofenceAssetAdapter.NAME,
+ true,
+ false,
+ false,
+ null
+ ))
+ put("push", new ConsoleProvider(
+ "fcm",
+ true,
+ true,
+ false,
+ (ObjectValue) parse("{token: \"23123213ad2313b0897efd\"}").orElse(null)
+ ))
+ }
+ })
+ consoleRegistration = authenticatedConsoleResource.register(null, consoleRegistration)
+
+ then: "the console should have been registered"
+ assert consoleRegistration.id != null
+
+ when: "the console location is set to the apartment"
+ authenticatedAssetResource.writeAttributeValue(null, consoleRegistration.id, LOCATION.name, ManagerDemoSetup.SMART_HOME_LOCATION.toValue().toJson())
+
+ then: "the consoles location should have been updated"
+ conditions.eventually {
+ def testUser3Console = assetStorageService.find(consoleRegistration.id, true)
+ assert testUser3Console != null
+ def assetLocation = testUser3Console.getAttribute(LOCATION).flatMap { it.value }.flatMap {
+ GeoJSONPoint.fromValue(it)
+ }.orElse(null)
+ assert assetLocation != null
+ assert assetLocation.x == ManagerDemoSetup.SMART_HOME_LOCATION.x
+ assert assetLocation.y == ManagerDemoSetup.SMART_HOME_LOCATION.y
+ assert assetLocation.z == ManagerDemoSetup.SMART_HOME_LOCATION.z
+ }
+
+ then: "the console location asset state should be in the rule engine"
+ conditions.eventually {
+ assert customerAEngine.assetStates.find {
+ it.id == consoleRegistration.id && it.value.flatMap { GeoJSONPoint.fromValue(it) }.map {
+ it.x == ManagerDemoSetup.SMART_HOME_LOCATION.x && it.y == ManagerDemoSetup.SMART_HOME_LOCATION.y ? it : null
+ }.isPresent()
+ } != null
+ }
+
+ when: "the console moves more than 50m away from the apartment"
+ authenticatedAssetResource.writeAttributeValue(null, consoleRegistration.id, LOCATION.name, new GeoJSONPoint(0d,0d).toValue().toJson())
+
+ then: ""
+
+// when: "the ALL LIGHTS OFF push-button is pressed for an apartment"
+// def lightsOffEvent = new AttributeEvent(
+// managerDemoSetup.apartment2Id, "allLightsOffSwitch", Values.create(true), getClockTimeOf(container)
+// )
+// assetProcessingService.sendAttributeEvent(lightsOffEvent)
+//
+// then: "the room lights in the apartment should be off"
+// conditions.eventually {
+// assert apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2
+// assert apartment2Engine.assetEvents.size() == 1
+// def livingroomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
+// assert !livingroomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()
+// def bathRoomAsset = assetStorageService.find(managerDemoSetup.apartment2BathroomId, true)
+// assert !bathRoomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()
+// }
+//
+// when: "time advanced by 15 seconds"
+// advancePseudoClock(15, SECONDS, container)
+//
+// and: "we turn the light on again in a room"
+// assetProcessingService.sendAttributeEvent(
+// new AttributeEvent(managerDemoSetup.apartment2LivingroomId, "lightSwitch", Values.create(true))
+// )
+//
+// then: "the light should still be on after a few seconds (the all lights off event expires after 3 seconds)"
+// new PollingConditions(initialDelay: 3).eventually {
+// assert apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2
+// assert apartment2Engine.assetEvents.size() == 0
+// def livingroomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
+// assert livingroomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()
+// }
+
+ cleanup: "stop the container"
+ stopContainer(container)
+ }
+}
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates.json b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates.json
new file mode 100644
index 000000000..11c7d0a7f
--- /dev/null
+++ b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates.json
@@ -0,0 +1,49 @@
+{
+ "rules": [
+ {
+ "name": "Test Rule",
+ "when": {
+ "asset": {
+ "type": {
+ "predicateType": "string",
+ "match": "EXACT",
+ "value": "urn:openremote:asset:console"
+ },
+ "attributes": {
+ "predicates": [
+ {
+ "name": {
+ "predicateType": "string",
+ "match": "EXACT",
+ "value": "location"
+ },
+ "value": {
+ "predicateType": "radial",
+ "radius": 50,
+ "lat": 51.438000,
+ "lng": 5.470945,
+ "negated": true
+ }
+ }
+ ]
+ }
+ }
+ },
+ "then": [
+ {
+ "action": "notification",
+ "target": {
+ "useAssetsFromWhen": true
+ },
+ "notification": {
+ "name": "test",
+ "message": {
+ "type": "push",
+ "title": "Test title"
+ }
+ }
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file