Skip to content

armgit / core

Public Imported from GitHub
0

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

Added residence auto ventilation rules and test, unified temporary facts in rules engine and refactored AssetState

Christian Bauer8c961a3a3022
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
index 3458a817d..c0b8ff718 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
@@ -41,7 +41,6 @@ import org.openremote.model.asset.*;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeEvent.Source;
import org.openremote.model.attribute.AttributeExecuteStatus;
-import org.openremote.model.rules.AssetEvent;
import org.openremote.model.rules.AssetState;
import org.openremote.model.security.ClientRole;
import org.openremote.model.value.Value;
@@ -108,16 +107,16 @@ import static org.openremote.model.attribute.AttributeEvent.Source.*;
* and the transport layer it uses etc.
* <h2>Rules Service processing logic</h2>
* <p>
- * Checks if attribute is {@link AssetAttribute#isRuleState} or {@link AssetAttribute#isRuleEvent}, and if
+ * Checks if attribute is {@link AssetAttribute#isRuleState} and {@link AssetAttribute#isRuleEvent}, and if
* so the message is passed through the rule engines that are in scope for the asset.
* <p>
* For {@link AssetState} messages, the rules service keeps the facts and thus the state of rule facts
* are in sync with the asset state changes that occur. If an asset attribute value changes,
* the {@link AssetState} in the rules engines will be updated to reflect the change.
* <p>
- * For {@link AssetEvent} messages (obtained by converting the {@link AssetState}), they are inserted in the rules
+ * For temporary {@link AssetState} event messages, they are inserted in the rules
* engines in scope and expired automatically if the event lifetime set in
- * {@link RulesService#RULE_EVENT_EXPIRES} is reached, or by the rules service if the event lifetime set in the
+ * {@link RulesService#RULE_EVENT_EXPIRES} is reached, or if the event lifetime set in the
* attribute {@link AssetMeta#RULE_EVENT_EXPIRES} is reached.
* <h2>Asset Storage Service processing logic</h2>
* <p>
@@ -506,6 +505,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
}
protected void publishClientEvent(Asset asset, AssetAttribute attribute) {
+ // TODO Catch "queue full" exception (e.g. when producing thousands of INFO messages in rules)?
clientEventService.publishEvent(new AttributeEvent(
asset.getId(), attribute.getNameOrThrow(), attribute.getValue().orElse(null), timerService.getCurrentTimeMillis()
));
diff --git a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
index 9aff029a0..ac5cb68a0 100644
--- a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
+++ b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
@@ -98,7 +98,7 @@ public class ClientEventService implements ContainerService {
// TODO: Some of these options should be configurable depending on expected load etc.
public static final String CLIENT_EVENT_TOPIC = "seda://ClientEventTopic?multipleConsumers=true&concurrentConsumers=1&waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=true&limitConcurrentConsumers=false&size=1000";
- public static final String CLIENT_EVENT_QUEUE = "seda://ClientEventQueue?multipleConsumers=false&waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=true&size=1000";
+ public static final String CLIENT_EVENT_QUEUE = "seda://ClientEventQueue?multipleConsumers=false&waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=true&size=25000";
final protected Collection<EventSubscriptionAuthorizer> eventSubscriptionAuthorizers = new CopyOnWriteArraySet<>();
protected TimerService timerService;
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
index 9f6ce3707..e72d8de62 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
@@ -113,7 +113,7 @@ public class RulesEngine<T extends Ruleset> {
/**
* @return a shallow copy of the asset event facts.
*/
- public List<AssetEvent> getAssetEvents() {
+ public List<TemporaryFact<AssetState>> getAssetEvents() {
synchronized (deployments) {
return new ArrayList<>(facts.getAssetEvents());
}
@@ -293,25 +293,12 @@ public class RulesEngine<T extends Ruleset> {
facts.setClock(clock);
// Remove any expired temporary facts
- facts.removeExpiredTemporaryFacts();
+ boolean factsExpired = facts.removeExpiredTemporaryFacts();
- // If we still have temporary facts and there is no firing scheduled
- if (facts.hasTemporaryFacts() && eventsTimer == null && !disableTemporaryFactExpiration) {
- // Schedule firing again so temporary facts can be expired
- // TODO: Optimized algo:
- // 1. Check when the next temporary fact expires
- // 2. Schedule repeated check with GUARANTEED_MIN_EXPIRATION_MILLIS running on wall clock
- // 3. Check if rules clock == next temporary fact expires
- // 3a. If true, cancel schedule and fire
- // 3b. If false, keep checking
- eventsTimer = executorService.schedule(
- this::fire, AssetEvent.GUARANTEED_MIN_EXPIRATION_MILLIS, TimeUnit.MILLISECONDS
- );
- } else if (eventsTimer != null) {
- // If we don't have temporary facts but there is a scheduled firing, cancel it
- eventsTimer.cancel(true);
- eventsTimer = null;
- }
+ // TODO Optimize:
+ // Add fire(scheduledFiring) boolean
+ // Add enableTimer() as rule declaration option, each rule which uses time windows must set it
+ // Only fire if factsExpired || deployment.isAnyRuleEnabledTimer()
for (RulesetDeployment deployment : deployments.values()) {
try {
@@ -341,6 +328,21 @@ public class RulesEngine<T extends Ruleset> {
break;
}
}
+
+ // If we still have temporary facts, schedule a new firing so expired facts are removed eventually
+ if (facts.hasTemporaryFacts() && eventsTimer == null && !disableTemporaryFactExpiration) {
+ LOG.fine("Temporary facts present, scheduling new firing of rules on: " + this);
+ eventsTimer = executorService.scheduleAtFixedRate(
+ this::fire,
+ TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS,
+ TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS,
+ TimeUnit.MILLISECONDS
+ );
+ } else if (!facts.hasTemporaryFacts() && eventsTimer != null) {
+ LOG.fine("No temporary facts present, cancel scheduled firing of rules on: " + this);
+ eventsTimer.cancel(false);
+ eventsTimer = null;
+ }
}
});
}
@@ -365,9 +367,7 @@ public class RulesEngine<T extends Ruleset> {
public void updateFact(AssetState assetState, boolean fireImmediately) {
synchronized (deployments) {
- RULES_LOG.finest("Fact change (UPDATE): " + assetState + " - on: " + this);
- facts.getAssetStates().remove(assetState);
- facts.getAssetStates().add(assetState);
+ facts.putAssetState(assetState);
if (fireImmediately) {
fire();
}
@@ -376,18 +376,14 @@ public class RulesEngine<T extends Ruleset> {
public void removeFact(AssetState assetState) {
synchronized (deployments) {
- RULES_LOG.finest("Fact change (DELETE): " + assetState + " - on: " + this);
- synchronized (deployments) {
- facts.getAssetStates().remove(assetState);
- fire();
- }
+ facts.removeAssetState(assetState);
+ fire();
}
}
- public void insertFact(AssetEvent assetEvent) {
+ public void insertFact(String expires, AssetState assetState) {
synchronized (deployments) {
- RULES_LOG.finest("Fact change (INSERT): " + assetEvent + " - on: " + this);
- facts.getAssetEvents().add(assetEvent);
+ facts.insertAssetEvent(expires, assetState);
fire();
}
}
@@ -428,7 +424,7 @@ public class RulesEngine<T extends Ruleset> {
protected void printSessionStats() {
synchronized (deployments) {
Collection<AssetState> assetStateFacts = facts.getAssetStates();
- Collection<AssetEvent> assetEventFacts = facts.getAssetEvents();
+ Collection<TemporaryFact<AssetState>> assetEventFacts = facts.getAssetEvents();
Map<String, Object> namedFacts = facts.getNamedFacts();
Collection<Object> anonFacts = facts.getAnonymousFacts();
long total = assetStateFacts.size() + assetEventFacts.size() + namedFacts.size() + anonFacts.size();
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
index 2a5c95e55..ba4b760b8 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
@@ -20,12 +20,11 @@
package org.openremote.manager.rules;
import org.jeasy.rules.api.*;
-import org.openremote.model.rules.AssetEvent;
import org.openremote.model.asset.AssetQuery;
-import org.openremote.model.rules.AssetQueryPredicate;
-import org.openremote.model.rules.AssetState;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeExecuteStatus;
+import org.openremote.model.rules.AssetQueryPredicate;
+import org.openremote.model.rules.AssetState;
import org.openremote.model.rules.Assets;
import org.openremote.model.rules.TemporaryFact;
import org.openremote.model.util.TimeUtil;
@@ -65,7 +64,7 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen
this.LOG = logger;
asMap().put(ASSET_STATES, new HashSet<AssetState>());
- asMap().put(ASSET_EVENTS, new ArrayList<AssetEvent>());
+ asMap().put(ASSET_EVENTS, new ArrayList<TemporaryFact<AssetState>>());
asMap().put(EXECUTION_VARS, new HashMap<String, Object>());
asMap().put(ANONYMOUS_FACTS, new HashSet<>());
}
@@ -85,8 +84,8 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen
}
@SuppressWarnings("unchecked")
- public List<AssetEvent> getAssetEvents() {
- return (List<AssetEvent>) get(ASSET_EVENTS);
+ public List<TemporaryFact<AssetState>> getAssetEvents() {
+ return (List<TemporaryFact<AssetState>>) get(ASSET_EVENTS);
}
@SuppressWarnings("unchecked")
@@ -143,16 +142,52 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen
case CLOCK:
throw new IllegalArgumentException("Reserved internal fact name: " + name);
}
+ if (LOG.isLoggable(Level.FINEST)) {
+ LOG.finest("Fact change (UPDATE): " + name + " => " + fact + " - on: " + loggingContext);
+ }
super.put(name, fact);
return this;
}
public RulesFacts put(Object o) {
+ if (LOG.isLoggable(Level.FINEST)) {
+ LOG.finest("Fact change (UPDATE): " + o + " - on: " + loggingContext);
+ }
getAnonymousFacts().remove(o);
getAnonymousFacts().add(o);
return this;
}
+ public RulesFacts putAssetState(AssetState assetState) {
+ if (LOG.isLoggable(Level.FINEST)) {
+ LOG.finest("Fact change (UPDATE): " + assetState + " - on: " + loggingContext);
+ }
+ getAssetStates().remove(assetState);
+ getAssetStates().add(assetState);
+ return this;
+ }
+
+ public RulesFacts removeAssetState(AssetState assetState) {
+ if (LOG.isLoggable(Level.FINEST)) {
+ LOG.finest("Fact change (DELETE): " + assetState + " - on: " + loggingContext);
+ }
+ getAssetStates().remove(assetState);
+ return this;
+ }
+
+ public RulesFacts insertAssetEvent(String expires, AssetState assetState) {
+ return insertAssetEvent(TimeUtil.parseTimeString(expires), assetState);
+ }
+
+ public RulesFacts insertAssetEvent(long expiresMilliSeconds, AssetState assetState) {
+ TemporaryFact<AssetState> fact = new TemporaryFact<>(assetState.getTimestamp(), expiresMilliSeconds, assetState);
+ if (LOG.isLoggable(Level.FINEST)) {
+ LOG.finest("Fact change (INSERT): " + fact + " - on: " + loggingContext);
+ }
+ getAssetEvents().add(fact);
+ return this;
+ }
+
public RulesFacts putTemporary(String expires, Object value) {
return putTemporary(TimeUtil.parseTimeString(expires), value);
}
@@ -162,7 +197,7 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen
}
public RulesFacts putTemporary(long expires, Object value) {
- getAnonymousFacts().add(new TemporaryFactImpl<>((long) getClock().getTimestamp(), expires, value));
+ getAnonymousFacts().add(new TemporaryFact<>((long) getClock().getTimestamp(), expires, value));
return this;
}
@@ -175,14 +210,22 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen
}
public RulesFacts putTemporary(String name, long expires, Object value) {
- put(name, new TemporaryFactImpl<>((long) getClock().getTimestamp(), expires, value));
+ put(name, new TemporaryFact<>((long) getClock().getTimestamp(), expires, value));
return this;
}
public boolean hasTemporaryFacts() {
- return getAssetEvents().size() > 0
- || getNamedFacts().entrySet().stream().anyMatch(entry -> entry.getValue() instanceof TemporaryFact)
- || getAnonymousFacts().stream().anyMatch(fact -> fact instanceof TemporaryFact);
+ return getTemporaryFacts().count() > 0;
+ }
+
+ public Stream<TemporaryFact> getTemporaryFacts() {
+ return Stream.concat(
+ Stream.concat(
+ getAssetEvents().stream(),
+ getNamedFacts().values().stream().filter(fact -> fact instanceof TemporaryFact).map(fact -> (TemporaryFact) fact)
+ ),
+ getAnonymousFacts().stream().filter(fact -> fact instanceof TemporaryFact).map(fact -> (TemporaryFact) fact)
+ );
}
@Override
@@ -193,8 +236,8 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen
public RulesFacts remove(Object fact) {
getAnonymousFacts().removeIf(anonFact -> {
- if (anonFact instanceof TemporaryFactImpl) {
- anonFact = ((TemporaryFactImpl) anonFact).getFact();
+ if (anonFact instanceof TemporaryFact) {
+ anonFact = ((TemporaryFact) anonFact).getFact();
}
return anonFact.equals(fact);
});
@@ -260,8 +303,8 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen
protected <T> Optional<T> matchFact(Object fact, Class<T> factType, Predicate<T> predicate) {
if (fact == null)
return Optional.empty();
- if (fact instanceof TemporaryFactImpl) {
- TemporaryFactImpl temporaryFact = (TemporaryFactImpl) fact;
+ if (fact instanceof TemporaryFact) {
+ TemporaryFact temporaryFact = (TemporaryFact) fact;
fact = temporaryFact.getFact();
}
Optional<T> result = Optional.empty();
@@ -312,8 +355,8 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen
return getAllFacts()
.filter(fact -> matchFact(fact, factType, predicate).isPresent())
.map(fact -> {
- if (fact instanceof TemporaryFactImpl) {
- return ((TemporaryFactImpl) fact).getFact();
+ if (fact instanceof TemporaryFact) {
+ return ((TemporaryFact) fact).getFact();
}
return fact;
})
@@ -326,16 +369,16 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen
public Stream<AssetState> matchAssetState(AssetQuery assetQuery) {
return getAssetStates().stream()
- .filter(fact -> matchFact(fact, AssetState.class, new AssetQueryPredicate(assetQuery)::test).isPresent());
+ .filter(fact -> matchFact(fact, AssetState.class, new AssetQueryPredicate(assetQuery)).isPresent());
}
- public Optional<AssetEvent> matchFirstAssetEvent(AssetQuery assetQuery) {
+ public Optional<TemporaryFact<AssetState>> matchFirstAssetEvent(AssetQuery assetQuery) {
return matchAssetEvent(assetQuery).findFirst();
}
- public Stream<AssetEvent> matchAssetEvent(AssetQuery assetQuery) {
+ public Stream<TemporaryFact<AssetState>> matchAssetEvent(AssetQuery assetQuery) {
return getAssetEvents().stream()
- .filter(fact -> matchFact(fact, AssetEvent.class, new AssetQueryPredicate(assetQuery)::test).isPresent());
+ .filter(fact -> matchFact(fact, AssetState.class, new AssetQueryPredicate(assetQuery)).isPresent());
}
public RulesFacts updateAssetState(String assetId, String attributeName, Value value) {
@@ -367,7 +410,7 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen
getAssetStates()
.removeIf(assetState -> {
boolean invalid = assetState.getId().equals(assetId) && assetState.getAttributeName().equals(attributeName);
- if (invalid) {
+ if (invalid && LOG.isLoggable(Level.FINEST)) {
LOG.finest("Fact change (INTERNAL DELETE): " + assetState + " - on: " + loggingContext);
}
return invalid;
@@ -381,25 +424,44 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen
return this;
}
- public RulesFacts removeExpiredTemporaryFacts() {
+ public boolean removeExpiredTemporaryFacts() {
long currentTimestamp = (long) getClock().getTimestamp();
- getAssetEvents().removeIf(event -> event.isExpired(currentTimestamp));
- asMap().entrySet().removeIf(entry ->
- !entry.getKey().equals(CLOCK)
- && !entry.getKey().equals(ASSET_STATES)
- && !entry.getKey().equals(ASSET_EVENTS)
- && !entry.getKey().equals(EXECUTION_VARS)
- && !entry.getKey().equals(ANONYMOUS_FACTS)
- && (entry.getValue() instanceof TemporaryFact && ((TemporaryFact) entry.getValue()).isExpired(currentTimestamp))
- );
+ long countBefore = getTemporaryFacts().count();
+ getAssetEvents().removeIf(fact -> {
+ boolean result = fact.isExpired(currentTimestamp);
+ if (result && LOG.isLoggable(Level.FINEST)) {
+ LOG.finest("Fact change (DELETE EXPIRED): " + fact + " - on: " + loggingContext);
+ }
+ return result;
+ });
+ asMap().entrySet().removeIf(entry -> {
+ if (entry.getKey().equals(CLOCK)
+ || entry.getKey().equals(ASSET_STATES)
+ || entry.getKey().equals(ASSET_EVENTS)
+ || entry.getKey().equals(EXECUTION_VARS)
+ || entry.getKey().equals(ANONYMOUS_FACTS)
+ || !(entry.getValue() instanceof TemporaryFact)) {
+ return false;
+ }
+ boolean result = ((TemporaryFact) entry.getValue()).isExpired(currentTimestamp);
+ if (result && LOG.isLoggable(Level.FINEST)) {
+ LOG.finest("Fact change (DELETE EXPIRED): " + entry.getValue() + " - on: " + loggingContext);
+ }
+ return result;
+ });
getAnonymousFacts().removeIf(fact -> {
+ boolean result = false;
if (fact instanceof TemporaryFact) {
TemporaryFact temporaryFact = (TemporaryFact) fact;
- return temporaryFact.isExpired((long) getClock().getTimestamp());
+ result = temporaryFact.isExpired((long) getClock().getTimestamp());
}
- return false;
+ if (result && LOG.isLoggable(Level.FINEST)) {
+ LOG.finest("Fact change (DELETE EXPIRED): " + fact + " - on: " + loggingContext);
+ }
+ return result;
});
- return this;
+ long countAfter = getTemporaryFacts().count();
+ return countAfter < countBefore;
}
public boolean logFacts(Logger logger) {
@@ -419,11 +481,11 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen
}
haveLog = true;
}
- List<AssetEvent> sortedAssetEvents = new ArrayList<>(getAssetEvents());
+ List<TemporaryFact<AssetState>> sortedAssetEvents = new ArrayList<>(getAssetEvents());
if (sortedAssetEvents.size() > 0) {
logger.info("--------------------------------- ASSET EVENTS (" + sortedAssetEvents.size() + ") ---------------------------------");
- sortedAssetEvents.sort(Comparator.naturalOrder());
- for (AssetEvent assetEvent : sortedAssetEvents) {
+ sortedAssetEvents.sort(Comparator.comparing(TemporaryFact::getTime));
+ for (TemporaryFact<AssetState> assetEvent : sortedAssetEvents) {
logger.info(assetEvent.toString());
}
haveLog = true;
@@ -433,7 +495,7 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen
names.sort(Comparator.naturalOrder());
if (names.size() > 0) {
logger.info("--------------------------------- NAMED FACTS (" + names.size() + ") ---------------------------------");
- for (String name: names) {
+ for (String name : names) {
logger.info(String.format("%s => %s", name, namedFacts.get(name)));
}
haveLog = true;
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
index 4527f89ed..8ed3f1dd9 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
@@ -60,7 +60,7 @@ import static org.openremote.model.asset.AssetAttribute.getAddedOrModifiedAttrib
/**
* Responsible for creating {@link RulesEngine}s for the rulesets
- * and processing {@link AssetState} and {@link AssetEvent} messages.
+ * and processing {@link AssetState} updates.
* <p>
* Each message is processed in the following order:
* <ol>
@@ -206,10 +206,9 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
// We might process two facts for a single attribute update, if that is what the user wants
// First as asset state
- AssetState assetState = new AssetState(asset, attribute, source);
if (attribute.isRuleState()) {
updateAssetState(
- assetState,
+ new AssetState(asset, attribute, source),
false, // Don't skip the error check on the rules engines
!attribute.isRuleEvent() // If it's not a rule event, fire immediately
);
@@ -217,10 +216,10 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
// Then as asset event (if there wasn't an error), this will also fire the rules engines
if (attribute.isRuleEvent()) {
- process(new AssetEvent(
- assetState,
+ insertAssetEvent(
+ new AssetState(asset, attribute, source),
attribute.getRuleEventExpires().orElse(configEventExpires)
- ));
+ );
}
return false;
@@ -561,13 +560,13 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
}
}
- protected synchronized void process(AssetEvent assetEvent) {
+ protected synchronized void insertAssetEvent(AssetState assetState, String expires) {
// Get the chain of rule engines that we need to pass through
- List<RulesEngine> rulesEngines = getEnginesInScope(assetEvent.getRealmId(), assetEvent.getPath());
+ List<RulesEngine> rulesEngines = getEnginesInScope(assetState.getRealmId(), assetState.getPath());
// Check that all engines in the scope are available
if (rulesEngines.stream().anyMatch(RulesEngine::isError)) {
- LOG.severe("At least one rules engine is in an error state, skipping: " + assetEvent);
+ LOG.severe("At least one rules engine is in an error state, skipping: " + assetState);
if (LOG.isLoggable(FINEST)) {
for (RulesEngine rulesEngine : rulesEngines) {
if (rulesEngine.isError()) {
@@ -580,7 +579,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
// Pass through each engine
for (RulesEngine rulesEngine : rulesEngines) {
- rulesEngine.insertFact(assetEvent);
+ rulesEngine.insertFact(expires, assetState);
}
}
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 3fbb835b7..d89c46457 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
@@ -111,6 +111,7 @@ public class RulesetDeployment {
scriptEngineManager = new ScriptEngineManager();
// LOG and console wrapper can be in global scope for all script engines
+ // TODO Use a different logger for each RulesEngine and show messages in Manager UI for that engine
scriptEngineManager.put("LOG", RulesEngine.RULES_LOG);
scriptEngineManager.put("console", new JsConsole(RulesEngine.RULES_LOG));
@@ -178,7 +179,8 @@ public class RulesetDeployment {
" \"java.util.stream\",\n" +
" \"org.openremote.model.asset\",\n" +
" \"org.openremote.model.attribute\",\n" +
- " \"org.openremote.model.value\"\n" +
+ " \"org.openremote.model.value\",\n" +
+ " \"org.openremote.model.rules\"\n" +
");\n" +
"var Match = Java.type(\"org.openremote.model.asset.BaseAssetQuery$Match\");\n" +
"var Operator = Java.type(\"org.openremote.model.asset.BaseAssetQuery$Operator\");\n" +
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java b/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java
index 008d02135..1c16465e8 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java
@@ -70,7 +70,7 @@ public class RulesetStorageService implements ContainerService {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
"select new org.openremote.model.rules.GlobalRuleset(" +
- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId" +
+ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.lang" +
") " +
"from GlobalRuleset rs " +
"order by rs.createdOn asc",
@@ -87,7 +87,7 @@ public class RulesetStorageService implements ContainerService {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
"select new org.openremote.model.rules.TenantRuleset(" +
- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.realmId" +
+ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.realmId, rs.lang" +
") " +
"from TenantRuleset rs " +
"where rs.realmId = :realmId " +
@@ -105,7 +105,7 @@ public class RulesetStorageService implements ContainerService {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
"select new org.openremote.model.rules.AssetRuleset(" +
- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.assetId" +
+ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.assetId, rs.lang" +
") " +
"from AssetRuleset rs, Asset a " +
"where rs.assetId = :assetId and rs.assetId = a.id and a.realmId = :realmId " +
diff --git a/manager/src/main/java/org/openremote/manager/rules/TemporaryFactImpl.java b/manager/src/main/java/org/openremote/manager/rules/TemporaryFactImpl.java
deleted file mode 100644
index 48cd0f67b..000000000
--- a/manager/src/main/java/org/openremote/manager/rules/TemporaryFactImpl.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright 2018, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.rules;
-
-import javaemul.internal.annotations.GwtIncompatible;
-import org.openremote.model.event.Event;
-import org.openremote.model.rules.TemporaryFact;
-
-import java.time.Instant;
-import java.time.LocalDateTime;
-import java.time.ZoneId;
-import java.time.temporal.ChronoUnit;
-
-/**
- * An arbitrary value as a punctual event in rules processing.
- */
-@GwtIncompatible
-public class TemporaryFactImpl<T> extends Event implements TemporaryFact {
-
- final protected long expirationMilliseconds;
- final protected T fact;
- // These are only useful for debugging, easier to read than timestamps
- final public LocalDateTime time;
- final public LocalDateTime expirationTime;
-
- public TemporaryFactImpl(long timestamp, long expirationMilliseconds, T fact) {
- super(timestamp);
- this.expirationMilliseconds = expirationMilliseconds;
- this.fact = fact;
- this.time = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
- this.expirationTime = time.plus(expirationMilliseconds, ChronoUnit.MILLIS);
- }
-
- @Override
- public long getExpirationMilliseconds() {
- return expirationMilliseconds;
- }
-
- public T getFact() {
- return fact;
- }
-
- @Override
- public String toString() {
- return TemporaryFact.class.getSimpleName() + "{" +
- "timestamp=" + timestamp +
- ", time=" + time +
- ", expirationMilliseconds=" + expirationMilliseconds +
- ", expirationTime=" + expirationTime +
- ", fact=" + fact +
- '}';
- }
-}
diff --git a/manager/src/main/java/org/openremote/manager/setup/AbstractManagerSetup.java b/manager/src/main/java/org/openremote/manager/setup/AbstractManagerSetup.java
index f8a20199a..a47c106ce 100644
--- a/manager/src/main/java/org/openremote/manager/setup/AbstractManagerSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/AbstractManagerSetup.java
@@ -185,7 +185,7 @@ public abstract class AbstractManagerSetup implements Setup {
new MetaItem(LABEL, Values.create("CO2 level")),
new MetaItem(RULE_STATE, Values.create(true)),
new MetaItem(RULE_EVENT, Values.create(true)),
- new MetaItem(RULE_EVENT_EXPIRES, Values.create("16m")),
+ new MetaItem(RULE_EVENT_EXPIRES, Values.create("45m")),
new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),
new MetaItem(READ_ONLY, Values.create(true)),
new MetaItem(STORE_DATA_POINTS, Values.create(true)),
@@ -201,6 +201,8 @@ public abstract class AbstractManagerSetup implements Setup {
.setMeta(
new MetaItem(LABEL, Values.create("Humidity")),
new MetaItem(RULE_STATE, Values.create(true)),
+ new MetaItem(RULE_EVENT, Values.create(true)),
+ new MetaItem(RULE_EVENT_EXPIRES, Values.create("45m")),
new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),
new MetaItem(READ_ONLY, Values.create(true)),
new MetaItem(STORE_DATA_POINTS, Values.create(true)),
diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
index 46186ea85..768b0f830 100644
--- a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
@@ -50,7 +50,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
final protected boolean importDemoScenes;
// Update these numbers whenever you change a RULE_STATE flag in test data
- public static final int DEMO_RULE_STATES_APARTMENT_1 = 23;
+ public static final int DEMO_RULE_STATES_APARTMENT_1 = 25;
public static final int DEMO_RULE_STATES_APARTMENT_2 = 11;
public static final int DEMO_RULE_STATES_APARTMENT_3 = 0;
public static final int DEMO_RULE_STATES_SMART_HOME = DEMO_RULE_STATES_APARTMENT_1 + DEMO_RULE_STATES_APARTMENT_2 + DEMO_RULE_STATES_APARTMENT_3;
@@ -353,6 +353,13 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
apartment1ServiceAgent = assetStorageService.merge(apartment1ServiceAgent);
apartment1ServiceAgentId = apartment1ServiceAgent.getId();
+ addDemoApartmentVentilation(apartment1, true, () -> new MetaItem[]{
+ new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()),
+ new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME))
+ });
+
+ apartment1 = assetStorageService.merge(apartment1);
+
ServerAsset apartment1Livingroom = createDemoApartmentRoom(apartment1, "Living Room");
addDemoApartmentRoomMotionSensor(apartment1Livingroom, true, () -> new MetaItem[]{
new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()),
diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/RulesDemoSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/RulesDemoSetup.java
index c72297194..a2435733a 100644
--- a/manager/src/main/java/org/openremote/manager/setup/builtin/RulesDemoSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/RulesDemoSetup.java
@@ -64,6 +64,13 @@ public class RulesDemoSetup extends AbstractManagerSetup {
);
apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();
}
+ try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoResidenceAutoVentilation.groovy")) {
+ String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));
+ Ruleset ruleset = new AssetRuleset(
+ "Demo Residence - Auto Ventilation", managerDemoSetup.apartment1Id, rules, Ruleset.Lang.GROOVY
+ );
+ apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();
+ }
// Apartment 2
try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoResidenceAllLightsOff.js")) {
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy b/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy
new file mode 100644
index 000000000..b114c1d75
--- /dev/null
+++ b/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy
@@ -0,0 +1,175 @@
+package demo.rules
+
+import org.openremote.manager.rules.RulesBuilder
+import org.openremote.manager.rules.RulesFacts
+import org.openremote.model.asset.AssetQuery
+import org.openremote.model.asset.BaseAssetQuery.Operator
+import org.openremote.model.rules.AssetState
+
+import java.util.logging.Logger
+import java.util.stream.Stream
+
+import static org.openremote.model.asset.AssetType.RESIDENCE
+import static org.openremote.model.asset.AssetType.ROOM
+import static org.openremote.model.asset.BaseAssetQuery.Operator.*
+
+Logger LOG = binding.LOG
+RulesBuilder rules = binding.rules
+
+final VENTILATION_LEVEL_LOW = 64d
+final VENTILATION_LEVEL_MEDIUM = 128d
+final VENTILATION_LEVEL_HIGH = 255d
+
+final VENTILATION_THRESHOLD_MEDIUM_CO2_TIME_WINDOW = "15m"
+final VENTILATION_THRESHOLD_MEDIUM_CO2_LEVEL = 700d
+final VENTILATION_THRESHOLD_MEDIUM_HUMIDITY_TIME_WINDOW = "1m"
+final VENTILATION_THRESHOLD_MEDIUM_HUMIDITY = 70d
+
+final VENTILATION_THRESHOLD_HIGH_CO2_TIME_WINDOW = "5m"
+final VENTILATION_THRESHOLD_HIGH_CO2_LEVEL = 1000d
+final VENTILATION_THRESHOLD_HIGH_HUMIDITY_TIME_WINDOW = "1m"
+final VENTILATION_THRESHOLD_HIGH_HUMIDITY = 85d
+
+final VENTILATION_THRESHOLD_MEDIUM_TIME_WINDOW = "30m"
+final VENTILATION_THRESHOLD_HIGH_TIME_WINDOW = "15m"
+
+Closure<Stream<AssetState>> residenceWithVentilationAutoMatch =
+ { RulesFacts facts, Operator operator, double ventilationLevelThreshold ->
+ facts.matchAssetState(
+ new AssetQuery().type(RESIDENCE).attributeValue("ventilationAuto", true)
+ ).filter({ residenceWithVentilationAuto ->
+ facts.matchFirstAssetState(
+ new AssetQuery().id(residenceWithVentilationAuto.id)
+ .attributeValue("ventilationLevel", operator, ventilationLevelThreshold)
+ ).isPresent()
+ })
+ }
+
+Closure<Optional<AssetState>> roomAboveThresholdMatch =
+ { RulesFacts facts, AssetState residence, String attribute, double threshold, String timeWindow ->
+ facts.matchAssetState(
+ new AssetQuery().type(ROOM).parent(residence.id).attributeValue(attribute, GREATER_THAN, 0)
+ ).max({ roomWithLevelAboveZero ->
+ roomWithLevelAboveZero.valueAsNumber.orElse(0)
+ }).filter({ roomWithMaxLevel ->
+ roomWithMaxLevel.valueAsNumber.filter({ v -> v > threshold }).isPresent()
+ }).filter({ roomAboveThreshold ->
+ // No value below threshold in time window
+ facts.matchAssetEvent(
+ new AssetQuery().id(roomAboveThreshold.id).attributeValue(attribute, LESS_EQUALS, threshold)
+ ).filter(facts.clock.last(timeWindow)).count() == 0
+ })
+ }
+
+Closure<Boolean> roomsBelowThresholdMatch =
+ { RulesFacts facts, AssetState residence, String attribute, double threshold, String timeWindow ->
+ facts.matchAssetEvent(
+ new AssetQuery().type(ROOM).parent(residence.id).attributeValue(attribute, GREATER_THAN, threshold)
+ ).filter(facts.clock.last(timeWindow)).count() == 0
+ }
+
+rules.add()
+ .name("Auto ventilation is on, level is below MEDIUM, CO2 or humidity above MEDIUM, set level MEDIUM")
+ .when(
+ { facts ->
+ residenceWithVentilationAutoMatch(
+ facts, LESS_THAN, VENTILATION_LEVEL_MEDIUM
+ ).filter({ residence ->
+ def roomWithTooMuchCO2 = roomAboveThresholdMatch(
+ facts, residence, "co2Level", VENTILATION_THRESHOLD_MEDIUM_CO2_LEVEL, VENTILATION_THRESHOLD_MEDIUM_CO2_TIME_WINDOW
+ )
+ def roomWithTooMuchHumidity = roomAboveThresholdMatch(
+ facts, residence, "humidity", VENTILATION_THRESHOLD_MEDIUM_HUMIDITY, VENTILATION_THRESHOLD_MEDIUM_HUMIDITY_TIME_WINDOW
+ )
+ roomWithTooMuchCO2.isPresent() || roomWithTooMuchHumidity.isPresent()
+ }).findFirst().map({ residence ->
+ facts.bind("residence", residence)
+ true
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ AssetState residence = facts.bound("residence")
+ LOG.info("Ventilation auto and too much CO2/humidity in a room, switching to MEDIUM: " + residence.name)
+ facts.updateAssetState(residence.id, "ventilationLevel", VENTILATION_LEVEL_MEDIUM)
+ })
+
+rules.add()
+ .name("Auto ventilation is on, level is above LOW, CO2 or humidity below MEDIUM, set level LOW")
+ .priority(20) // Run after "set level MEDIUM" rule
+ .when(
+ { facts ->
+ residenceWithVentilationAutoMatch(
+ facts, GREATER_THAN, VENTILATION_LEVEL_LOW
+ ).filter({ residence ->
+ def roomsBelowThresholdCO2 = roomsBelowThresholdMatch(
+ facts, residence, "co2Level", VENTILATION_THRESHOLD_MEDIUM_CO2_LEVEL, VENTILATION_THRESHOLD_MEDIUM_TIME_WINDOW
+ )
+ def roomsBelowThresholdHumidity = roomsBelowThresholdMatch(
+ facts, residence, "humidity", VENTILATION_THRESHOLD_MEDIUM_HUMIDITY, VENTILATION_THRESHOLD_MEDIUM_TIME_WINDOW
+ )
+ roomsBelowThresholdCO2 && roomsBelowThresholdHumidity
+ }).findFirst().map({ residence ->
+ facts.bind("residence", residence)
+ true
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ AssetState residence = facts.bound("residence")
+ LOG.info("Ventilation auto and low CO2/humidity in all rooms, switching to LOW: " + residence.name)
+ facts.updateAssetState(residence.id, "ventilationLevel", VENTILATION_LEVEL_LOW)
+ })
+
+rules.add()
+ .name("Auto ventilation is on, level is below HIGH, CO2 or humidity above HIGH, set level HIGH")
+ .when(
+ { facts ->
+ residenceWithVentilationAutoMatch(
+ facts, LESS_THAN, VENTILATION_LEVEL_HIGH
+ ).filter({ residence ->
+ def roomWithTooMuchCO2 = roomAboveThresholdMatch(
+ facts, residence, "co2Level", VENTILATION_THRESHOLD_HIGH_CO2_LEVEL, VENTILATION_THRESHOLD_HIGH_CO2_TIME_WINDOW
+ )
+ def roomWithTooMuchHumidity = roomAboveThresholdMatch(
+ facts, residence, "humidity", VENTILATION_THRESHOLD_HIGH_HUMIDITY, VENTILATION_THRESHOLD_HIGH_HUMIDITY_TIME_WINDOW
+ )
+ roomWithTooMuchCO2.isPresent() || roomWithTooMuchHumidity.isPresent()
+ }).findFirst().map({ residence ->
+ facts.bind("residence", residence)
+ true
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ AssetState residence = facts.bound("residence")
+ LOG.info("Ventilation auto and too much CO2/humidity in a room, switching to HIGH: " + residence.name)
+ facts.updateAssetState(residence.id, "ventilationLevel", VENTILATION_LEVEL_HIGH)
+ })
+
+rules.add()
+ .name("Auto ventilation is on, level is above MEDIUM, CO2 or humidity below MEDIUM, set level MEDIUM")
+ .priority(10) // Run before "set level LOW" rule
+ .when(
+ { facts ->
+ residenceWithVentilationAutoMatch(
+ facts, GREATER_THAN, VENTILATION_LEVEL_MEDIUM
+ ).filter({ residence ->
+ def roomsBelowThresholdCo2 = roomsBelowThresholdMatch(
+ facts, residence, "co2Level", VENTILATION_THRESHOLD_MEDIUM_CO2_LEVEL, VENTILATION_THRESHOLD_HIGH_TIME_WINDOW
+ )
+ def roomsBelowThresholdHumidity = roomsBelowThresholdMatch(
+ facts, residence, "humidity", VENTILATION_THRESHOLD_MEDIUM_HUMIDITY, VENTILATION_THRESHOLD_HIGH_TIME_WINDOW
+ )
+ roomsBelowThresholdCo2 && roomsBelowThresholdHumidity
+ }).findFirst().map({ residence ->
+ facts.bind("residence", residence)
+ true
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ AssetState residence = facts.bound("residence")
+ LOG.info("Ventilation auto and low CO2/humidity in all rooms, switching to MEDIUM: " + residence.name)
+ facts.updateAssetState(residence.id, "ventilationLevel", VENTILATION_LEVEL_MEDIUM)
+ })
diff --git a/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy b/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy
index 556e66a5c..d5ddb0803 100644
--- a/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy
+++ b/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy
@@ -50,6 +50,9 @@ rules.add()
).filter(
// in the last 12 minutes
facts.clock.last("12m")
+ ).map({ co2LevelFact ->
+ co2LevelFact.fact
+ }
).filter({ coLevel ->
// with increasing values
coLevel.isValueGreaterThanOldValue()
@@ -88,9 +91,9 @@ rules.add()
// and there are no sensor events
facts.matchAssetEvent(
new AssetQuery().id(roomWithoutMotionSensorTriggered.id).attributeName("co2Level")
- ).filter({ coLevel ->
+ ).filter({ coLevelFact ->
// with increasing values
- coLevel.isValueGreaterThanOldValue()
+ coLevelFact.getFact().isValueGreaterThanOldValue()
// in the last 12 minutes≤
}).filter(facts.clock.last("12m")).count() == 0
}).orElse(true) // or we don't have a CO2 sensor
diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
index 3dd572aaa..fef386a43 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
@@ -21,7 +21,6 @@ package org.openremote.model.asset;
import org.openremote.model.ValidationFailure;
import org.openremote.model.attribute.*;
-import org.openremote.model.rules.AssetEvent;
import org.openremote.model.rules.AssetState;
import org.openremote.model.rules.TemporaryFact;
import org.openremote.model.value.Value;
@@ -291,10 +290,10 @@ public enum AssetMeta implements MetaItemDescriptor {
/**
* Should attribute writes be processed by the rules engines as {@link AssetState} facts,
- * with a lifecycle that reflects the state of the asset attribute. The state facts are kept
- * in sync with asset changes: For an attribute there will always be a single fact that is updated
- * when the attribute is updated. If you want two types of facts in your rules for a single
- * attribute, with state and event behavior, combine this with {@link #RULE_EVENT}.
+ * with a lifecycle that reflects the state of the asset attribute. Each attribute will have one
+ * fact at all times in rules memory. These state facts are kept in sync with asset changes: When
+ * the attribute is updated, the fact will be updated (replaced). If you want evaluate the change
+ * history of an attribute, you typically need to combine this with {@link #RULE_EVENT}.
*/
RULE_STATE(
ASSET_META_NAMESPACE + ":ruleState",
@@ -306,11 +305,11 @@ public enum AssetMeta implements MetaItemDescriptor {
true),
/**
- * Should attribute writes be processed by the rules engines as event facts. Any attribute
- * update will be inserted as an {@link AssetEvent} fact in a rules engine, these events are expired
- * automatically after a defined time and/or if they can no longer be matched by rule LHS time constraints.
- * If you want two types of facts in your rules for a single attribute, with state and event
- * behavior, combine this with {@link #RULE_STATE}.
+ * Should attribute writes be processed by the rules engines as temporary facts. When an attribute
+ * is updated, the change will be inserted as a new {@link AssetState} temporary fact in rules engines.
+ * These facts expire automatically after a defined time, see {@link #RULE_EVENT_EXPIRES}. If you want
+ * to match (multiple) {@link AssetState}s for the same attribute over time, to evaluate the change
+ * history of an attribute, add this meta item.
*/
RULE_EVENT(
ASSET_META_NAMESPACE + ":ruleEvent",
@@ -322,9 +321,9 @@ public enum AssetMeta implements MetaItemDescriptor {
true),
/**
- * Set maximum lifetime of {@link AssetEvent} facts in rules, for example "1h30m5s". The rules
- * engine will remove {@link AssetEvent} facts if they are older than this value (using event source/value
- * timestamp, not event processing time).
+ * Set maximum lifetime of {@link AssetState} temporary facts in rules, for example "1h30m5s". The rules
+ * engine will remove temporary {@link AssetState} facts if they are older than this value (using event
+ * source/value timestamp, not event processing time).
* <p>
* The default expiration for asset events can be configured with environment variable <code>RULE_EVENT_EXPIRES</code>.
* <p>
diff --git a/model/src/main/java/org/openremote/model/rules/AssetEvent.java b/model/src/main/java/org/openremote/model/rules/AssetEvent.java
deleted file mode 100644
index a3f2ac314..000000000
--- a/model/src/main/java/org/openremote/model/rules/AssetEvent.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.model.rules;
-
-import org.openremote.model.util.TimeUtil;
-
-/**
- * An asset attribute value update, as a temporary event in rules processing.
- */
-public class AssetEvent extends AssetState implements TemporaryFact {
-
- final protected long expirationMilliseconds;
-
- public AssetEvent(AssetState that, String expires) {
- super(that);
- this.expirationMilliseconds = TimeUtil.parseTimeString(expires);
- }
-
- @Override
- public long getExpirationMilliseconds() {
- return expirationMilliseconds;
- }
-
-}
diff --git a/model/src/main/java/org/openremote/model/rules/AssetRuleset.java b/model/src/main/java/org/openremote/model/rules/AssetRuleset.java
index 84b016bfe..1397538c6 100644
--- a/model/src/main/java/org/openremote/model/rules/AssetRuleset.java
+++ b/model/src/main/java/org/openremote/model/rules/AssetRuleset.java
@@ -46,8 +46,8 @@ public class AssetRuleset extends Ruleset {
this.assetId = assetId;
}
- public AssetRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String assetId) {
- this(id, version, createdOn, lastModified, name, enabled, templateAssetId, null, Lang.JAVASCRIPT, null, assetId);
+ public AssetRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String assetId, Lang lang) {
+ this(id, version, createdOn, lastModified, name, enabled, templateAssetId, null, lang, null, assetId);
}
public AssetRuleset(String name, String assetId, String rules, Lang lang) {
diff --git a/model/src/main/java/org/openremote/model/rules/GlobalRuleset.java b/model/src/main/java/org/openremote/model/rules/GlobalRuleset.java
index 8f63bedef..0d488dc89 100644
--- a/model/src/main/java/org/openremote/model/rules/GlobalRuleset.java
+++ b/model/src/main/java/org/openremote/model/rules/GlobalRuleset.java
@@ -33,8 +33,8 @@ public class GlobalRuleset extends Ruleset {
public GlobalRuleset() {
}
- public GlobalRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId) {
- super(id, version, createdOn, lastModified, name, enabled, templateAssetId);
+ public GlobalRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, Lang lang) {
+ super(id, version, createdOn, lastModified, name, enabled, templateAssetId, lang);
}
public GlobalRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String rules, Lang lang) {
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 04df8f699..33a184cc0 100644
--- a/model/src/main/java/org/openremote/model/rules/Ruleset.java
+++ b/model/src/main/java/org/openremote/model/rules/Ruleset.java
@@ -152,8 +152,8 @@ public abstract class Ruleset {
public Ruleset() {
}
- public Ruleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId) {
- this(id, version, createdOn, lastModified, name, enabled, templateAssetId, null, Lang.JAVASCRIPT);
+ public Ruleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, Lang lang) {
+ this(id, version, createdOn, lastModified, name, enabled, templateAssetId, null, lang);
}
public Ruleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String rules, Lang lang) {
diff --git a/model/src/main/java/org/openremote/model/rules/TemporaryFact.java b/model/src/main/java/org/openremote/model/rules/TemporaryFact.java
index f3348b375..cd4ee9a90 100644
--- a/model/src/main/java/org/openremote/model/rules/TemporaryFact.java
+++ b/model/src/main/java/org/openremote/model/rules/TemporaryFact.java
@@ -19,10 +19,19 @@
*/
package org.openremote.model.rules;
+import javaemul.internal.annotations.GwtIncompatible;
+import org.openremote.model.event.Event;
+
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.temporal.ChronoUnit;
+
/**
* A rule fact that has a timestamp, it expires after a certain time.
*/
-public interface TemporaryFact {
+@GwtIncompatible
+public class TemporaryFact<T> extends Event {
/**
* This value defines the periodic firing of the rules engines when temporary
@@ -30,13 +39,51 @@ public interface TemporaryFact {
* fact has a shorter expiration time, it's not guaranteed to be removed within
* that time.
*/
- int GUARANTEED_MIN_EXPIRATION_MILLIS = 3000;
+ public static final int GUARANTEED_MIN_EXPIRATION_MILLIS = 3000;
+
+ final protected long expirationMilliseconds;
+ final protected T fact;
+ // These are only useful for debugging, easier to read than timestamps
+ final public LocalDateTime time;
+ final public LocalDateTime expirationTime;
+
+ public TemporaryFact(long timestamp, long expirationMilliseconds, T fact) {
+ super(timestamp);
+ this.expirationMilliseconds = expirationMilliseconds;
+ this.fact = fact;
+ this.time = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
+ this.expirationTime = time.plus(expirationMilliseconds, ChronoUnit.MILLIS);
+ }
+
+ public long getExpirationMilliseconds() {
+ return expirationMilliseconds;
+ }
- long getTimestamp();
+ public T getFact() {
+ return fact;
+ }
+
+ public LocalDateTime getTime() {
+ return time;
+ }
- long getExpirationMilliseconds();
+ public LocalDateTime getExpirationTime() {
+ return expirationTime;
+ }
- default boolean isExpired(long currentTimestamp) {
+ public boolean isExpired(long currentTimestamp) {
return getTimestamp() + getExpirationMilliseconds() < currentTimestamp;
}
+
+ @Override
+ public String toString() {
+ return TemporaryFact.class.getSimpleName() + "{" +
+ "timestamp=" + timestamp +
+ ", time=" + time +
+ ", expirationMilliseconds=" + expirationMilliseconds +
+ ", expirationTime=" + expirationTime +
+ ", fact=" + fact +
+ '}';
+ }
+
}
diff --git a/model/src/main/java/org/openremote/model/rules/TenantRuleset.java b/model/src/main/java/org/openremote/model/rules/TenantRuleset.java
index 8d23e1d69..7dad4c5a2 100644
--- a/model/src/main/java/org/openremote/model/rules/TenantRuleset.java
+++ b/model/src/main/java/org/openremote/model/rules/TenantRuleset.java
@@ -38,8 +38,8 @@ public class TenantRuleset extends Ruleset {
public TenantRuleset() {
}
- public TenantRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String realmId) {
- super(id, version, createdOn, lastModified, name, enabled, templateAssetId);
+ public TenantRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String realmId, Lang lang) {
+ super(id, version, createdOn, lastModified, name, enabled, templateAssetId, lang);
this.realmId = realmId;
}
@@ -49,7 +49,7 @@ public class TenantRuleset extends Ruleset {
}
public TenantRuleset(String realmId) {
- this(null, realmId, null, Lang.JAVASCRIPT);
+ this(null, realmId, null, Lang.GROOVY);
}
diff --git a/profile/deploy.yml b/profile/deploy.yml
index e1ca69c00..c2905f5ff 100644
--- a/profile/deploy.yml
+++ b/profile/deploy.yml
@@ -290,8 +290,8 @@ services:
# docker exec -it <container ID> psql -U openremote
# Resource limits
- mem_limit: 300m
- memswap_limit: 300m
+ mem_limit: 400m
+ memswap_limit: 400m
# Configure logging of the container
logging:
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
index 8c25e88e9..939efb5e8 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
@@ -146,7 +146,6 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets[0].id == managerDemoSetup.smartHomeId
assets[0].name == "Smart Home"
assets[1].id == managerDemoSetup.apartment1Id
- assets[1].version == 0
assets[1].createdOn == null
assets[1].name == "Apartment 1"
assets[1].type == null
@@ -158,7 +157,9 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets[1].tenantDisplayName == null
assets[1].coordinates == null
assets[1].path == null
- assets[1].getAttributesList().size() == 7
+ assets[1].getAttributesList().size() == 9
+ assets[1].getAttribute("ventilationAuto").isPresent()
+ assets[1].getAttribute("ventilationLevel").isPresent()
assets[1].getAttribute("alarmEnabled").isPresent()
assets[1].getAttribute("vacationUntil").isPresent()
assets[1].getAttribute("autoSceneSchedule").isPresent()
@@ -189,7 +190,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
then: "result should match (and some values should be empty because we need an AssetQuery to get them)"
asset.id == managerDemoSetup.apartment1Id
- asset.version == 0
+ asset.version == 1
asset.createdOn.time < System.currentTimeMillis()
asset.name == "Apartment 1"
asset.wellKnownType == AssetType.RESIDENCE
@@ -310,7 +311,6 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
then: "result should match"
assets.size() == 3
assets.get(0).id == managerDemoSetup.apartment1Id
- assets.get(0).version == 0
assets.get(0).createdOn.time < System.currentTimeMillis()
assets.get(0).name == "Apartment 1"
assets.get(0).wellKnownType == AssetType.RESIDENCE
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy
index 43424415a..f941798e5 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy
@@ -2,17 +2,15 @@ package org.openremote.test.rules
import org.openremote.container.Container
import org.openremote.manager.rules.RulesClock
+import org.openremote.manager.rules.RulesEngine
import org.openremote.manager.rules.RulesFacts
import org.openremote.model.rules.Assets
import spock.lang.Specification
-import java.util.logging.Logger
import java.util.stream.Collectors
class BasicRulesFactsTest extends Specification {
- private static final Logger LOG = Logger.getLogger(BasicRulesFactsTest.class.getName())
-
class AnonFact {
String foo
double bar
@@ -46,7 +44,7 @@ class BasicRulesFactsTest extends Specification {
def setup() {
given: "some rule facts"
assetsFacade = Mock(Assets)
- rulesFacts = new RulesFacts(assetsFacade, this, LOG)
+ rulesFacts = new RulesFacts(assetsFacade, this, RulesEngine.RULES_LOG)
and: "a rules clock"
def rulesClock = new RulesClock(0)
@@ -166,9 +164,10 @@ class BasicRulesFactsTest extends Specification {
and: "the clock is advanced and temporary facts are expired"
rulesFacts.setClock(new RulesClock(3000))
- rulesFacts.removeExpiredTemporaryFacts()
+ def factsExpired = rulesFacts.removeExpiredTemporaryFacts()
then: "all temporary facts should still be present"
+ assert !factsExpired
assert rulesFacts.hasTemporaryFacts()
assert rulesFacts.getAllFacts().count() == 3
assert rulesFacts.matchFirst("foo").isPresent()
@@ -177,9 +176,10 @@ class BasicRulesFactsTest extends Specification {
when: "the clock is advanced and temporary facts are expired"
rulesFacts.setClock(new RulesClock(6000))
- rulesFacts.removeExpiredTemporaryFacts()
+ factsExpired = rulesFacts.removeExpiredTemporaryFacts()
then: "some temporary facts should still be present"
+ assert factsExpired
assert rulesFacts.hasTemporaryFacts()
assert rulesFacts.getAllFacts().count() == 2
assert !rulesFacts.matchFirst("foo").isPresent()
@@ -188,9 +188,10 @@ class BasicRulesFactsTest extends Specification {
when: "the clock is advanced and temporary facts are expired"
rulesFacts.setClock(new RulesClock(12000))
- rulesFacts.removeExpiredTemporaryFacts()
+ factsExpired = rulesFacts.removeExpiredTemporaryFacts()
then: "some temporary facts should still be present"
+ assert factsExpired
assert rulesFacts.hasTemporaryFacts()
assert rulesFacts.getAllFacts().count() == 1
assert !rulesFacts.matchFirst("foo").isPresent()
@@ -220,9 +221,10 @@ class BasicRulesFactsTest extends Specification {
and: "the clock is advanced and temporary facts are expired"
rulesFacts.setClock(new RulesClock(3000))
- rulesFacts.removeExpiredTemporaryFacts()
+ def factsExpired = rulesFacts.removeExpiredTemporaryFacts()
then: "all temporary facts should still be present"
+ assert !factsExpired
assert rulesFacts.hasTemporaryFacts()
assert rulesFacts.match(AnonFact).count() == 3
assert rulesFacts.match(String).count() == 0
@@ -235,9 +237,10 @@ class BasicRulesFactsTest extends Specification {
when: "the clock is advanced and temporary facts are expired"
rulesFacts.setClock(new RulesClock(6000))
- rulesFacts.removeExpiredTemporaryFacts()
+ factsExpired = rulesFacts.removeExpiredTemporaryFacts()
then: "some temporary facts should still be present"
+ assert factsExpired
assert rulesFacts.hasTemporaryFacts()
assert rulesFacts.match(AnonFact).count() == 2
assert rulesFacts.match(AnonFact, { fact -> fact.foo == "FOO1" }).count() == 0
@@ -246,9 +249,10 @@ class BasicRulesFactsTest extends Specification {
when: "the clock is advanced and temporary facts are expired"
rulesFacts.setClock(new RulesClock(12000))
- rulesFacts.removeExpiredTemporaryFacts()
+ factsExpired = rulesFacts.removeExpiredTemporaryFacts()
then: "some temporary facts should still be present"
+ assert factsExpired
assert rulesFacts.hasTemporaryFacts()
assert rulesFacts.match(AnonFact).count() == 1
assert rulesFacts.match(AnonFact, { fact -> fact.foo == "FOO1" }).count() == 0
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
index d262443ca..a74366f53 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
@@ -60,6 +60,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "result should match"
ruleDefinitions.length == 2
ruleDefinitions[0].name == "Some global demo rules"
+ ruleDefinitions[0].lang == GROOVY
ruleDefinitions[0].rules == null // Don't retrieve the (large) rules data when getting a list of rule definitions
when: "some tenant rules are retrieved"
@@ -68,6 +69,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "result should match"
ruleDefinitions.length == 1
ruleDefinitions[0].name == "Some master tenant demo rules"
+ ruleDefinitions[0].lang == GROOVY
when: "some tenant rules in a non-authenticated realm are retrieved"
ruleDefinitions = rulesetResource.getTenantRulesets(null, keycloakDemoSetup.customerATenant.id)
@@ -83,6 +85,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "result should match"
ruleDefinitions.length == 1
ruleDefinitions[0].name == "Some apartment 2 demo rules"
+ ruleDefinitions[0].lang == GROOVY
/* ############################################## WRITE ####################################### */
@@ -100,6 +103,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
lastModified.time < System.currentTimeMillis()
globalRuleset.name == "Test global definition"
globalRuleset.rules == "SomeRulesCode"
+ globalRuleset.lang == GROOVY
when: "a global ruleset is updated"
globalRuleset.name = "Renamed test global definition"
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAutoVentilationTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAutoVentilationTest.groovy
new file mode 100644
index 000000000..2e4261b54
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAutoVentilationTest.groovy
@@ -0,0 +1,194 @@
+package org.openremote.test.rules.residence
+
+import org.openremote.agent.protocol.simulator.SimulatorProtocol
+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.setup.SetupService
+import org.openremote.manager.setup.builtin.ManagerDemoSetup
+import org.openremote.model.attribute.AttributeEvent
+import org.openremote.model.rules.AssetRuleset
+import org.openremote.model.rules.Ruleset
+import org.openremote.model.value.Values
+import org.openremote.test.ManagerContainerTrait
+import spock.lang.Specification
+import spock.util.concurrent.PollingConditions
+
+import static java.util.concurrent.TimeUnit.MINUTES
+import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_APARTMENT_1
+import static org.openremote.model.attribute.AttributeEvent.Source.SENSOR
+
+class ResidenceAutoVentilationTest extends Specification implements ManagerContainerTrait {
+
+ def "Auto ventilation with CO2 detection"() {
+
+ given: "the container environment is started"
+ def conditions = new PollingConditions(timeout: 20, delay: 1)
+ def serverPort = findEphemeralPort()
+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())
+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
+ def rulesService = container.getService(RulesService.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
+ def rulesetStorageService = container.getService(RulesetStorageService.class)
+ def simulatorProtocol = container.getService(SimulatorProtocol.class)
+ RulesEngine apartment1Engine = null
+
+ and: "some rules"
+ Ruleset ruleset = new AssetRuleset(
+ "Demo Apartment - Auto Ventilation",
+ managerDemoSetup.apartment1Id,
+ getClass().getResource("/demo/rules/DemoResidenceAutoVentilation.groovy").text,
+ Ruleset.Lang.GROOVY
+ )
+ rulesetStorageService.merge(ruleset)
+
+ expect: "the rule engines to become available and be running"
+ conditions.eventually {
+ apartment1Engine = rulesService.assetEngines.get(managerDemoSetup.apartment1Id)
+ assert apartment1Engine != null
+ assert apartment1Engine.isRunning()
+ assert apartment1Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_1
+ }
+
+ and: "the ventilation should be off"
+ conditions.eventually {
+ def apartment = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert !apartment.getAttribute("ventilationAuto").get().getValue().isPresent()
+ assert !apartment.getAttribute("ventilationLevel").get().getValue().isPresent()
+ }
+
+ when: "auto ventilation is turned on"
+ assetProcessingService.sendAttributeEvent(
+ new AttributeEvent(managerDemoSetup.apartment1Id, "ventilationAuto", Values.create(true))
+ )
+
+ then: "auto ventilation should be on"
+ conditions.eventually {
+ def apartment = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert apartment.getAttribute("ventilationAuto").get().getValueAsBoolean().get()
+ assert !apartment.getAttribute("ventilationLevel").get().getValue().isPresent()
+ }
+
+ when: "CO2 is increasing in a room"
+ // The CO2 level increments 3 times, 2 minutes apart
+ for (i in 1..3) {
+
+ def co2LevelIncrement = new AttributeEvent(
+ managerDemoSetup.apartment1LivingroomId, "co2Level", Values.create(700 + i)
+ )
+ simulatorProtocol.putValue(co2LevelIncrement)
+
+ // Wait for event to be processed
+ conditions.eventually {
+ assert apartment1Engine.assetEvents.any() {
+ it.fact.matches(co2LevelIncrement, SENSOR, true)
+ }
+ assert noEventProcessedIn(assetProcessingService, 500)
+ }
+
+ advancePseudoClock(2, MINUTES, container)
+ }
+
+ then: "ventilation level of the apartment should be MEDIUM"
+ conditions.eventually {
+ def apartment = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert apartment.getAttribute("ventilationLevel").get().getValueAsNumber().get() == 128d
+ }
+
+ when: "CO2 is decreasing in a room"
+ def co2LevelDecrement = new AttributeEvent(
+ managerDemoSetup.apartment1LivingroomId, "co2Level", Values.create(500)
+ )
+ simulatorProtocol.putValue(co2LevelDecrement)
+ conditions.eventually {
+ assert apartment1Engine.assetEvents.any() {
+ it.fact.matches(co2LevelDecrement, SENSOR, true)
+ }
+ assert noEventProcessedIn(assetProcessingService, 500)
+ }
+
+ and: "time advances"
+ advancePseudoClock(35, MINUTES, container)
+
+ then: "ventilation level of the apartment should be LOW"
+ conditions.eventually {
+ def apartment = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert apartment.getAttribute("ventilationLevel").get().getValueAsNumber().get() == 64d
+ }
+
+ when: "CO2 is increasing in a room"
+ // The CO2 level increments 3 times, 2 minutes apart
+ for (i in 1..3) {
+
+ def co2LevelIncrement = new AttributeEvent(
+ managerDemoSetup.apartment1LivingroomId, "co2Level", Values.create(1000 + i)
+ )
+ simulatorProtocol.putValue(co2LevelIncrement)
+
+ // Wait for event to be processed
+ conditions.eventually {
+ assert apartment1Engine.assetEvents.any() {
+ it.fact.matches(co2LevelIncrement, SENSOR, true)
+ }
+ assert noEventProcessedIn(assetProcessingService, 500)
+ }
+
+ advancePseudoClock(2, MINUTES, container)
+ }
+
+ then: "ventilation level of the apartment should be HIGH"
+ conditions.eventually {
+ def apartment = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert apartment.getAttribute("ventilationLevel").get().getValueAsNumber().get() == 255d
+ }
+
+ when: "CO2 is decreasing in a room"
+ def co2LevelDecrement2 = new AttributeEvent(
+ managerDemoSetup.apartment1LivingroomId, "co2Level", Values.create(800)
+ )
+ simulatorProtocol.putValue(co2LevelDecrement2)
+ conditions.eventually {
+ assert apartment1Engine.assetEvents.any() {
+ it.fact.matches(co2LevelDecrement2, SENSOR, true)
+ }
+ assert noEventProcessedIn(assetProcessingService, 500)
+ }
+
+ and: "time advances"
+ advancePseudoClock(20, MINUTES, container)
+
+ then: "ventilation level of the apartment should be MEDIUM"
+ conditions.eventually {
+ def apartment = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert apartment.getAttribute("ventilationLevel").get().getValueAsNumber().get() == 128d
+ }
+
+ when: "CO2 is decreasing in a room"
+ def co2LevelDecrement3 = new AttributeEvent(
+ managerDemoSetup.apartment1LivingroomId, "co2Level", Values.create(500)
+ )
+ simulatorProtocol.putValue(co2LevelDecrement3)
+ conditions.eventually {
+ assert apartment1Engine.assetEvents.any() {
+ it.fact.matches(co2LevelDecrement3, SENSOR, true)
+ }
+ assert noEventProcessedIn(assetProcessingService, 500)
+ }
+
+ and: "time advances"
+ advancePseudoClock(15, MINUTES, container)
+
+ then: "ventilation level of the apartment should be LOW"
+ conditions.eventually {
+ def apartment = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert apartment.getAttribute("ventilationLevel").get().getValueAsNumber().get() == 64d
+ }
+
+ cleanup: "the server should be stopped"
+ stopContainer(container)
+ }
+
+}
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidencePresenceDetectionTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidencePresenceDetectionTest.groovy
index 23ec74004..27dc60d54 100644
--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidencePresenceDetectionTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidencePresenceDetectionTest.groovy
@@ -222,7 +222,7 @@ class ResidencePresenceDetectionTest extends Specification implements ManagerCon
// Wait for event to be processed
conditions.eventually {
assert apartment1Engine.assetEvents.any() {
- it.matches(co2LevelIncrement, SENSOR, true)
+ it.fact.matches(co2LevelIncrement, SENSOR, true)
}
assert noEventProcessedIn(assetProcessingService, 500)
}