Skip to content

armgit / core

Public Imported from GitHub
0

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

Switched to async AttributeEvent processing, added vacation days rules test

Christian Bauer017d63b343f0
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
index 87b5bfb67..2491b95e9 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
@@ -25,17 +25,14 @@ import org.apache.camel.builder.RouteBuilder;
import org.openremote.container.Container;
import org.openremote.container.message.MessageBrokerContext;
import org.openremote.container.message.MessageBrokerSetupService;
-import org.openremote.container.observable.RetryWithDelay;
import org.openremote.model.AttributeEvent;
import org.openremote.model.AttributeRef;
import org.openremote.model.AttributeState;
import org.openremote.model.asset.thing.ThingAttribute;
-import rx.Observable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
-import java.util.function.Consumer;
import java.util.logging.Logger;
public abstract class AbstractProtocol implements Protocol {
@@ -134,12 +131,12 @@ public abstract class AbstractProtocol implements Protocol {
}
}
- protected void sendAttributeUpdate(AttributeState state) {
- producerTemplate.sendBodyAndHeader(SENSOR_TOPIC, new AttributeEvent(state, System.currentTimeMillis()), "isSensorUpdate", false);
+ protected void sendAttributeEvent(AttributeState state) {
+ producerTemplate.sendBodyAndHeader(SENSOR_QUEUE, new AttributeEvent(state, System.currentTimeMillis()), "isSensorUpdate", false);
}
protected void onSensorUpdate(AttributeState state, long timestamp) {
- producerTemplate.sendBody(SENSOR_TOPIC, new AttributeEvent(state, timestamp));
+ producerTemplate.sendBody(SENSOR_QUEUE, new AttributeEvent(state, timestamp));
}
protected void onSensorUpdate(AttributeState state) {
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java
index 1333cc3f9..6aa82baaf 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java
@@ -34,7 +34,7 @@ import java.util.Collection;
* <p>
* The protocol implementation can receive {@link AttributeEvent} messages on the
* {@link #ACTUATOR_TOPIC}. It can produce {@link AttributeEvent} messages on the
- * {@link #SENSOR_TOPIC}.
+ * {@link #SENSOR_QUEUE}.
* <p>
* The linked attributes of a protocol provide the model for the protocol to perform these operations. How
* attributes and value changes map to actual device and service calls is up to the implementation. The method
@@ -58,11 +58,11 @@ public interface Protocol extends ContainerService {
// TODO: Some of these options should be configurable depending on expected load etc.
- // Message topic for communicating from thing to protocol layer (thing attribute changed, trigger actuator)
+ // Message topic for communicating from asset/thing to protocol layer (asset attribute changed, trigger actuator)
String ACTUATOR_TOPIC = "seda://ActuatorTopic?multipleConsumers=true&concurrentConsumers=10&waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=true&limitConcurrentConsumers=false&size=1000";
- // Message topic for communicating from protocol to thing layer (sensor changed, trigger thing attribute update)
- String SENSOR_TOPIC = "seda://SensorTopic?waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=false&size=1000";
+ // Message queue for communicating from protocol to asset/thing layer (sensor changed, trigger asset attribute update)
+ String SENSOR_QUEUE = "seda://SensorQueue?waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=false&size=1000";
String getProtocolName();
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java
index a3df229a3..315266dc6 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java
@@ -113,7 +113,7 @@ public class MacroProtocol extends AbstractProtocol {
}
// send attribute event
- sendAttributeUpdate(actionState);
+ sendAttributeEvent(actionState);
});
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
index e9ab6e25e..c4267b476 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
@@ -198,7 +198,7 @@ public class AssetViewActivity
requestParams, assetId, attribute.getName(), attribute.getValue().toJson()
),
204,
- () -> showSuccess(container.getMessages().attributeValueStored(attribute.getName())),
+ () -> showSuccess(container.getMessages().attributeWriteSent(attribute.getName())),
ex -> handleRequestException(ex, environment)
);
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java
index 0a86a4e93..62c4b0ec8 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java
@@ -266,7 +266,7 @@ public class AssetViewImpl extends Composite implements AssetView {
public void setType(String type) {
AssetType assetType = AssetType.getByValue(type);
if (assetType == AssetType.CUSTOM) {
- typeLabel.setText(managerMessages.assetTypeLabel(type));
+ typeLabel.setText(type);
} else {
typeLabel.setText(managerMessages.assetTypeLabel(assetType.name()));
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/i18n/ManagerMessages.java b/manager/client/src/main/java/org/openremote/manager/client/i18n/ManagerMessages.java
index 05b398fa4..fd623326a 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/i18n/ManagerMessages.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/i18n/ManagerMessages.java
@@ -41,8 +41,6 @@ public interface ManagerMessages extends Messages {
String lastModifiedOn();
- String mapLoading();
-
String loadingDotdotdot();
String editAccount();
@@ -297,9 +295,7 @@ public interface ManagerMessages extends Messages {
String editAssetRuleset(String name);
- String attributeValueRefreshed(String name);
-
- String attributeValueStored(String name);
+ String attributeWriteSent(String name);
String invalidAttributeName();
diff --git a/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties b/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties
index da32e21cc..bdb55fff8 100644
--- a/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties
+++ b/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties
@@ -6,7 +6,6 @@ admin=System
lastModifiedOn=Last modified on
logout=Logout
fullscreen=Fullscreen
-mapLoading=Loading map, please wait...
editAccount=Edit my account
manageTenants=Manage tenants
manageUsers=Manage users
@@ -153,8 +152,7 @@ rulesetUpdated=Ruleset saved: {0}
downloadRulesFile=Download DRL file
editTenantRuleset=Edit tenant ruleset: {0}
editAssetRuleset=Edit asset ruleset: {0}
-attributeValueRefreshed=Attribute value refreshed: {0}
-attributeValueStored=Attribute value stored: {0}
+attributeWriteSent=Attribute write sent to server: {0}
invalidAttributeName=Invalid attribute name, use only alphanumeric and underscore characters.
editAsset=Edit asset
viewAsset=View asset
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java
index fa3103296..da48d0ea9 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java
@@ -40,7 +40,7 @@ import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
-import static org.openremote.agent3.protocol.Protocol.SENSOR_TOPIC;
+import static org.openremote.agent3.protocol.Protocol.SENSOR_QUEUE;
/**
* Receives {@link AttributeEvent}s and processes them.
@@ -115,6 +115,10 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
private static final Logger LOG = Logger.getLogger(AssetProcessingService.class.getName());
+ // TODO: Some of these options should be configurable depending on expected load etc.
+ // Message topic for communicating from client to asset/thing layer
+ String ASSET_QUEUE = "seda://AssetQueue?waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=false&size=1000";
+
protected ManagerIdentityService managerIdentityService;
protected RulesService rulesService;
protected AgentService agentService;
@@ -191,51 +195,58 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
public void configure() throws Exception {
// Process attribute events from protocols
- from(SENSOR_TOPIC)
+ from(SENSOR_QUEUE)
.filter(body().isInstanceOf(AttributeEvent.class))
.process(exchange -> {
+ AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
+ LOG.fine("Received on sensor queue: " + event);
// Can either come from onUpdateSensor or sendAttributeUpdate
boolean isSensorUpdate = (boolean) exchange.getIn().getHeader("isSensorUpdate", true);
if (isSensorUpdate) {
- processSensorUpdate(exchange.getIn().getBody(AttributeEvent.class));
+ processSensorUpdate(event);
} else {
- updateAttributeValue(exchange.getIn().getBody(AttributeEvent.class));
+ updateAttributeValue(event);
}
});
- // Process attribute events from clients through the message broker
- /* TODO Needs security
- from(INCOMING_EVENT_TOPIC)
+ // Process attribute events from clients
+ from(ASSET_QUEUE)
.filter(body().isInstanceOf(AttributeEvent.class))
- .process(exchange -> updateAttributeValue(exchange.getIn().getBody(AttributeEvent.class)));
- */
+ .process(exchange -> {
+ AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
+ LOG.fine("Received on asset queue: " + event);
+ updateAttributeValue(event);
+ });
+ }
+
+ public void sendAttributeEvent(AttributeEvent attributeEvent) {
+ messageBrokerService.getProducerTemplate().sendBody(ASSET_QUEUE, attributeEvent);
}
/**
- * This is the entry point for any attribute value change event in the entire system. This deals
- * with single attribute value changes and pushes them through the attribute event processing chain
- * where each consumer is given the opportunity to consume the event or allow it progress to the
- * next consumer {@link AssetState.ProcessingStatus}.
+ * This is the entry point for any attribute value change event in the entire system.
+ * <p>
+ * Ingestion is asynchronous, through either
+ * {@link org.openremote.agent3.protocol.Protocol#SENSOR_QUEUE} or {@link #ASSET_QUEUE}.
+ * <p>
+ * This deals with single attribute value changes and pushes them through the attribute event
+ * processing chain where each consumer is given the opportunity to consume the event or allow
+ * it progress to the next consumer {@link AssetState.ProcessingStatus}.
* <p>
* NOTE: An attribute value can be changed during Asset CRUD but this does not come through
* this route but is handled separately see {@link AssetResourceImpl}. Any attribute values
* assigned during Asset CRUD can be thought of as the attributes initial value and is subject
- * to change by the following actors (depending on attribute meta etc.) all actors use this
- * entry point to initiate an attribute value change:
- * <p>
- * Rules
- * Protocol
- * User
- *
- * @param attributeEvent
+ * to change by the following actors (depending on attribute meta etc.) All actors use this
+ * entry point to initiate an attribute value change: Sensor updates from protocols, attribute
+ * write requests from clients, and attribute write dispatching as rules RHS action.
*/
- public void updateAttributeValue(AttributeEvent attributeEvent) {
+ private void updateAttributeValue(AttributeEvent attributeEvent) {
// Check this event relates to a valid asset
ServerAsset asset = assetStorageService.find(attributeEvent.getEntityId(), true);
if (asset == null) {
- LOG.warning("Processing client update failed, asset not found: " + attributeEvent);
+ LOG.warning("Processing event failed, asset not found: " + attributeEvent);
return;
}
@@ -247,7 +258,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
}
// Pass attribute event through the processing chain
- LOG.fine("Processing client " + attributeEvent + " for: " + asset);
+ LOG.fine("Processing " + attributeEvent + " for: " + asset);
AssetAttributes attributes = new AssetAttributes(asset);
AssetAttribute attribute = attributes.get(attributeEvent.getAttributeName());
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
index 1d965f885..90495ac12 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
@@ -262,7 +262,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
// Process update
try {
JsonValue value = Json.instance().parse(rawJson);
- assetProcessingService.updateAttributeValue(
+ assetProcessingService.sendAttributeEvent(
new AttributeEvent(new AttributeRef(assetId, attributeName), value)
);
} catch (RuntimeException ex) {
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
index f760c6165..e98fdb3aa 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
@@ -29,7 +29,6 @@ import org.openremote.container.ContainerService;
import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.persistence.PersistenceEvent;
import org.openremote.container.persistence.PersistenceService;
-import org.openremote.model.Pair;
import org.openremote.container.web.WebService;
import org.openremote.container.web.socket.WebsocketAuth;
import org.openremote.manager.server.event.EventService;
@@ -38,6 +37,7 @@ import org.openremote.manager.shared.security.ClientRole;
import org.openremote.manager.shared.security.Tenant;
import org.openremote.model.Attribute;
import org.openremote.model.AttributeEvent;
+import org.openremote.model.Pair;
import org.openremote.model.ReadAttributesEvent;
import org.openremote.model.asset.*;
import org.postgresql.util.PGobject;
@@ -259,11 +259,6 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
});
}
- // Here for convenience - a single service to handle Asset/AssetAttribute events
- public void updateAttributeValue(AttributeEvent attributeEvent) {
- assetProcessingService.updateAttributeValue(attributeEvent);
- }
-
public boolean isUserAsset(String userId, String assetId) {
return persistenceService.doReturningTransaction(entityManager -> {
UserAsset userAsset = entityManager.find(UserAsset.class, new UserAsset(userId, assetId));
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
index 7f3630f18..1976407ea 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
@@ -57,10 +57,10 @@ import org.openremote.manager.shared.rules.TenantRuleset;
import org.openremote.model.AttributeEvent;
import org.openremote.model.Consumer;
import org.openremote.model.asset.AbstractAssetUpdate;
+import org.openremote.model.asset.AssetEvent;
import org.openremote.model.asset.AssetQuery;
import org.openremote.model.asset.AssetState;
import org.openremote.model.notification.AlertNotification;
-import org.openremote.model.asset.AssetEvent;
import org.openremote.model.rules.Assets;
import org.openremote.model.rules.Users;
@@ -88,6 +88,7 @@ public class RulesDeployment<T extends Ruleset> {
private static Long counter = 1L;
static final protected Util UTIL = new Util();
protected final Map<Long, T> rulesets = new LinkedHashMap<>();
+ protected String rulesetsDebug;
protected final RuleExecutionLogger ruleExecutionLogger = new RuleExecutionLogger();
protected KieSession knowledgeSession;
protected KieServices kieServices;
@@ -206,6 +207,7 @@ public class RulesDeployment<T extends Ruleset> {
kfs.delete("src/main/resources/" + ruleset.getId());
//noinspection SuspiciousMethodCalls
rulesets.remove(existingRuleset);
+ updateRulesetsDebug();
}
LOG.info("Adding ruleset: " + ruleset);
@@ -254,6 +256,7 @@ public class RulesDeployment<T extends Ruleset> {
// Add new ruleset
ruleset.setDeploymentStatus(addSuccessful ? Ruleset.DeploymentStatus.DEPLOYED : Ruleset.DeploymentStatus.FAILED);
rulesets.put(ruleset.getId(), ruleset);
+ updateRulesetsDebug();
return addSuccessful;
}
@@ -281,6 +284,7 @@ public class RulesDeployment<T extends Ruleset> {
// Remove this old rules file
kfs.delete("src/main/resources/" + ruleset.getId());
rulesets.remove(ruleset.getId());
+ updateRulesetsDebug();
// Update status of each ruleset
boolean anyFailed = rulesets
@@ -360,6 +364,14 @@ public class RulesDeployment<T extends Ruleset> {
try {
knowledgeSession = kieContainer.newKieSession(kieSessionConfiguration);
+
+ // If the pseudo clock is enabled (we run a test environment?) then set current
+ // time on startup of session, as real time is used in offset calculations for
+ // automatic event expiration in Drools (probably a design mistake)
+ if (clockType.getClockType().equals("pseudo")) {
+ ((PseudoClockScheduler) knowledgeSession.getSessionClock()).setStartupTime(System.currentTimeMillis());
+ }
+
running = true;
setGlobal("assets", createAssetsFacade());
@@ -593,7 +605,7 @@ public class RulesDeployment<T extends Ruleset> {
);
}
LOG.fine("Dispatching on " + RulesDeployment.this + ": " + event);
- assetProcessingService.updateAttributeValue(event);
+ assetProcessingService.sendAttributeEvent(event);
}
};
}
@@ -632,7 +644,7 @@ public class RulesDeployment<T extends Ruleset> {
@Override
public void storeAndNotify(String userId, AlertNotification alert) {
- notificationService.storeAndNotify(userId,alert);
+ notificationService.storeAndNotify(userId, alert);
}
};
}
@@ -678,8 +690,8 @@ public class RulesDeployment<T extends Ruleset> {
}
- protected synchronized String getRulesetDebug() {
- return Arrays.toString(rulesets.values().stream().map(rd ->
+ protected synchronized void updateRulesetsDebug() {
+ rulesetsDebug = Arrays.toString(rulesets.values().stream().map(rd ->
rd.getClass().getSimpleName()
+ " - "
+ rd.getName()
@@ -694,7 +706,7 @@ public class RulesDeployment<T extends Ruleset> {
"id='" + id + '\'' +
", running='" + running + '\'' +
", error='" + error + '\'' +
- ", rulesets='" + getRulesetDebug() + '\'' +
+ ", rulesets='" + rulesetsDebug + '\'' +
'}';
}
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
index 0b7e812cf..973d38574 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
@@ -37,8 +37,9 @@ import org.openremote.model.asset.agent.ProtocolConfiguration;
import org.openremote.model.units.AttributeUnits;
import org.openremote.model.units.ColorRGB;
-import java.time.*;
-import java.util.Calendar;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
import static org.openremote.model.AttributeType.*;
import static org.openremote.model.asset.AssetMeta.*;
@@ -339,6 +340,17 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
new MetaItem(AssetMeta.RULE_EVENT_EXPIRES, Json.create("10s"))
)
)
+ ).put(
+ new AssetAttribute("vacationDays", AttributeType.INTEGER, Json.createNull())
+ .setMeta(
+ new Meta().add(
+ new MetaItem(AssetMeta.LABEL, Json.create("Vacation Days"))
+ ).add(
+ new MetaItem(AssetMeta.DESCRIPTION, Json.create("Enable vacation mode for given days"))
+ ).add(
+ new MetaItem(AssetMeta.RULE_STATE, Json.create(true))
+ )
+ )
);
apartment1.setAttributes(apartment1Attributes.getJsonObject());
apartment1 = assetStorageService.merge(apartment1);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/RulesDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/RulesDemoSetup.java
index 42b56c7a1..5b314fe08 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/RulesDemoSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/RulesDemoSetup.java
@@ -59,5 +59,10 @@ public class RulesDemoSetup extends AbstractManagerSetup {
Ruleset ruleset = new TenantRuleset("Demo Apartment - Presence Detection", keycloakDemoSetup.customerATenant.getId(), rules);
apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();
}
+ try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentVacationMode.drl")) {
+ String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));
+ Ruleset ruleset = new TenantRuleset("Demo Apartment - Vacation Mode", keycloakDemoSetup.customerATenant.getId(), rules);
+ apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();
+ }
}
}
diff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentVacationMode.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentVacationMode.drl
new file mode 100644
index 000000000..bd22d34e8
--- /dev/null
+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentVacationMode.drl
@@ -0,0 +1,21 @@
+package org.openremote.test.rules;
+
+import org.openremote.model.*;
+import org.openremote.model.asset.*
+import elemental.json.Json;
+
+global java.util.logging.Logger LOG;
+global org.openremote.model.rules.Assets assets;
+
+rule "Decrement vacation days every day 1 minute after midnight until vacation is over"
+ // http://www.cronmaker.com/
+ timer (cron: 0 1 0 1/1 * ? *)
+when
+ // Vacation days are more than zero, which means vacation mode is enabled
+ $s: AssetState(attributeName == "vacationDays", type == AssetType.RESIDENCE, value.asNumber() > 0 )
+then
+ // Decrement the vacation days by one
+ assets.dispatch(
+ new AttributeEvent($s.getAttributeRef(), Json.create($s.getValue().asNumber() -1))
+ );
+end
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java
index 720b3244c..c1aa7cfa3 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java
@@ -131,9 +131,13 @@ public interface AssetResource {
* their authenticated realm, the superuser can update assets in other (all) realms. A 403 status
* is returned if a regular user tries to update an asset in a realm different than its
* authenticated realm, or if the user is restricted and the asset to update is not in the set of linked
- * assets of the restricted user. A 400 status is returned if the update was not successful, e.g. because
- * the given value does not match the attribute's type. Note that this update does not increment the version
- * of an asset entity, thus concurrent updates can overwrite data undetected ("last commit wins").
+ * assets of the restricted user.
+ * <p>
+ * This operation is ultimately asynchronous, any call will return before the actual attribute value is
+ * changed in any storage or downstream processors. Thus any constraint violation or processing error
+ * will not be returned from this method, query the system later to determine the actual state
+ * and outcome of the write operation. The version of the asset entity will not be incremented by this
+ * operation, thus concurrent updates can overwrite data undetected ("last commit wins").
*/
@PUT
@Path("{assetId}/attribute/{attributeName}")
diff --git a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
index 0a5b6eb85..aba588e43 100644
--- a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
+++ b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
@@ -1,6 +1,8 @@
package org.openremote.test
import com.google.common.collect.Lists
+import org.drools.core.time.impl.PseudoClockScheduler
+import org.kie.api.runtime.conf.ClockTypeOption
import org.openremote.agent3.protocol.Protocol
import org.openremote.container.Container
import org.openremote.container.ContainerService
@@ -16,6 +18,7 @@ import org.openremote.manager.server.event.EventService
import org.openremote.manager.server.i18n.I18NService
import org.openremote.manager.server.map.MapService
import org.openremote.manager.server.notification.NotificationService
+import org.openremote.manager.server.rules.RulesDeployment
import org.openremote.manager.server.rules.RulesService
import org.openremote.manager.server.rules.RulesetStorageService
import org.openremote.manager.server.security.ManagerIdentityService
@@ -61,4 +64,23 @@ trait ManagerContainerTrait extends ContainerTrait {
static Container startContainerWithoutDemoRules(Map<String, String> config, Iterable<ContainerService> services) {
startContainer(config << [(SETUP_IMPORT_DEMO_RULES): "false"], services)
}
+
+ static void enablePseudoClock() {
+ RulesDeployment.DefaultClockType = ClockTypeOption.get("pseudo")
+ }
+
+ static void disablePseudoClock() {
+ RulesDeployment.DefaultClockType = null
+ }
+
+ /**
+ * Execute pseudo clock operations in Rules engine in a daemon thread, simulating behavior of
+ * {@link org.kie.api.runtime.conf.TimedRuleExectionOption} "yes", which lets Drools execute
+ * time-triggered rules in the background even though the engine is in passive mode and waits
+ * for <code>fireAllRules()</code> to trigger any other rules.
+ */
+ static void withClockOf(RulesDeployment engine, Closure<PseudoClockScheduler> clockConsumer) {
+ Thread.startDaemon { clockConsumer.call(engine.sessionClock as PseudoClockScheduler) }
+ }
+
}
diff --git a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy
index dcf90856e..966b44d64 100644
--- a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy
@@ -5,6 +5,7 @@ import elemental.json.JsonArray
import elemental.json.JsonType
import org.openremote.agent3.protocol.simulator.SimulatorProtocol
import org.openremote.manager.server.asset.AssetStorageService
+import org.openremote.manager.server.asset.AssetProcessingService
import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.server.setup.builtin.ManagerDemoSetup
import org.openremote.model.AttributeEvent
@@ -27,6 +28,7 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def simulatorProtocol = container.getService(SimulatorProtocol.class)
def assetStorageService = container.getService(AssetStorageService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
then: "the simulator elements should have the initial state"
conditions.eventually {
@@ -42,7 +44,7 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
def light1DimmerChange = new AttributeEvent(
managerDemoSetup.thingId, "light1Dimmer", Json.create(66)
)
- assetStorageService.updateAttributeValue(light1DimmerChange)
+ assetProcessingService.sendAttributeEvent(light1DimmerChange)
then: "the simulator state and thing attribute value should be updated (simulator reflects actuator write as sensor read)"
conditions.eventually {
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
index cd1839632..88c6a7557 100644
--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
@@ -16,6 +16,7 @@ import org.openremote.model.asset.AssetType
import org.openremote.model.AttributeType
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
+import spock.util.concurrent.PollingConditions
import javax.ws.rs.WebApplicationException
import javax.xml.ws.WebServiceException
@@ -80,17 +81,21 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
when: "an asset attribute value is written directly"
assetResource.writeAttributeValue(null, testAsset.getId(), "foo", "\"bar2\"")
- testAsset = assetResource.get(null, testAsset.getId())
then: "the attribute value should match"
- new AssetAttributes(testAsset).get("foo").getValueAsString() == "bar2"
+ new PollingConditions(delay: 1, timeout: 5).eventually {
+ def asset = assetResource.get(null, testAsset.getId())
+ new AssetAttributes(asset).get("foo").getValueAsString() == "bar2"
+ }
when: "an asset attribute value null is written directly"
assetResource.writeAttributeValue(null, testAsset.getId(), "foo", "null")
- testAsset = assetResource.get(null, testAsset.getId())
then: "the attribute value should match"
- !new AssetAttributes(testAsset).get("foo").hasValue()
+ new PollingConditions(delay: 1, timeout: 5).eventually {
+ def asset = assetResource.get(null, testAsset.getId())
+ !new AssetAttributes(asset).get("foo").hasValue()
+ }
when: "an asset is updated with a different type"
testAsset = assetResource.get(null, testAsset.getId())
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
index 42d05fdbf..ed0511de6 100644
--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
@@ -14,6 +14,7 @@ import org.openremote.model.asset.AssetMeta
import org.openremote.model.asset.AssetType
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
+import spock.util.concurrent.PollingConditions
import javax.ws.rs.WebApplicationException
@@ -30,6 +31,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
def container = startContainerWithoutDemoRules(defaultConfig(serverPort), defaultServices())
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
+ def conditions = new PollingConditions(delay: 1, timeout: 5)
and: "an authenticated admin user"
def accessToken = authenticate(
@@ -160,10 +162,13 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "an asset attribute is written in the authenticated realm"
assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Json.create("Teststreet 123").toJson())
- def asset = assetResource.get(null, managerDemoSetup.smartOfficeId)
then: "result should match"
- new AssetAttributes(asset).get("geoStreet").getValue().toJson() == Json.create("Teststreet 123").toJson()
+ def asset
+ conditions.eventually {
+ asset = assetResource.get(null, managerDemoSetup.smartOfficeId)
+ new AssetAttributes(asset).get("geoStreet").getValue().toJson() == Json.create("Teststreet 123").toJson()
+ }
when: "an non-existent attribute is written in the authenticated realm"
assetResource.writeAttributeValue(null, "doesnotexist", "geoStreet", Json.create("Teststreet 123").toJson())
@@ -181,10 +186,12 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "an asset attribute is written in a foreign realm"
assetResource.writeAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet", Json.create("Teststreet 456").toJson())
- asset = assetResource.get(null, managerDemoSetup.smartHomeId)
then: "result should match"
- new AssetAttributes(asset).get("geoStreet").getValue().toJson() == Json.create("Teststreet 456").toJson()
+ conditions.eventually {
+ asset = assetResource.get(null, managerDemoSetup.smartHomeId)
+ new AssetAttributes(asset).get("geoStreet").getValue().toJson() == Json.create("Teststreet 456").toJson()
+ }
cleanup: "the server should be stopped"
stopContainer(container)
@@ -197,6 +204,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
def container = startContainerWithoutDemoRules(defaultConfig(serverPort), defaultServices())
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
+ def conditions = new PollingConditions(delay: 1, timeout: 5)
and: "an authenticated test user"
def accessToken = authenticate(
@@ -326,10 +334,13 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "an asset attribute is written in the authenticated realm"
assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Json.create("Teststreet 123").toJson())
- def asset = assetResource.get(null, managerDemoSetup.smartOfficeId)
then: "result should match"
- new AssetAttributes(asset).get("geoStreet").getValue().toJson() == Json.create("Teststreet 123").toJson()
+ def asset
+ conditions.eventually {
+ asset = assetResource.get(null, managerDemoSetup.smartOfficeId)
+ new AssetAttributes(asset).get("geoStreet").getValue().toJson() == Json.create("Teststreet 123").toJson()
+ }
when: "an asset attribute is written in a foreign realm"
assetResource.writeAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet", Json.create("Teststreet 456").toJson())
@@ -348,6 +359,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
def container = startContainerWithoutDemoRules(defaultConfig(serverPort), defaultServices())
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
+ def conditions = new PollingConditions(delay: 1, timeout: 5)
and: "an authenticated test user"
def accessToken = authenticate(
@@ -479,6 +491,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
def container = startContainerWithoutDemoRules(defaultConfig(serverPort), defaultServices())
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
+ def conditions = new PollingConditions(delay: 1, timeout: 5)
and: "an authenticated test user"
def accessToken = authenticate(
@@ -649,10 +662,12 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "a protected asset attribute is written on a user asset"
assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomThermostatId, "comfortTemperature", Json.create(22.123).toJson())
- def asset = assetResource.get(null, managerDemoSetup.apartment1LivingroomThermostatId)
then: "result should match"
- new AssetAttributes(asset).get("comfortTemperature").getValue().toJson() == Json.create(22.123).toJson()
+ conditions.eventually {
+ def asset = assetResource.get(null, managerDemoSetup.apartment1LivingroomThermostatId)
+ new AssetAttributes(asset).get("comfortTemperature").getValue().toJson() == Json.create(22.123).toJson()
+ }
when: "an attribute is written on a non-existent user asset"
assetResource.writeAttributeValue(null, "doesnotexist", "lightSwitch", Json.create(false).toJson())
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy
index ddebfbf04..0f3002158 100644
--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy
@@ -108,7 +108,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait
def customerAEngine = rulesService.tenantDeployments.get(keycloakDemoSetup.customerATenant.id)
assert customerAEngine != null
assert customerAEngine.isRunning()
- assert customerAEngine.rulesets.size() == 2
+ assert customerAEngine.rulesets.size() == 3
assert updatesPassedStartOfProcessingChain.size() == 0
assert updatesReachedEndOfProcessingChain.size() == 0
}
@@ -185,7 +185,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait
def light1toggleOn = new AttributeEvent(
new AttributeState(new AttributeRef(mockThing.getId(), "light1Toggle"), Json.create(true))
)
- assetProcessingService.updateAttributeValue(light1toggleOn)
+ assetProcessingService.sendAttributeEvent(light1toggleOn)
then: "the attribute event should pass the start of the processing chain, reach the mock protocol and but not reach the end of the processing chain"
conditions.eventually {
@@ -222,10 +222,9 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait
def light2toggleOn = new AttributeEvent(
new AttributeState(new AttributeRef(mockThing.getId(), "light2Toggle"), Json.create(true))
)
- assetProcessingService.updateAttributeValue(light2toggleOn)
+ assetProcessingService.sendAttributeEvent(light2toggleOn)
then: "the attribute event should pass the start of the processing chain, but not reach the mock protocol or the end of the processing chain and error should be populated"
- thrown(RuntimeException)
conditions.eventually {
assert updatesPassedStartOfProcessingChain.size() == 1
assert updatesReachedEndOfProcessingChain.size() == 0
@@ -244,7 +243,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait
def plainAttributeTest = new AttributeEvent(
new AttributeState(new AttributeRef(mockThing.getId(), "plainAttribute"), Json.create("test"))
)
- assetProcessingService.updateAttributeValue(plainAttributeTest)
+ assetProcessingService.sendAttributeEvent(plainAttributeTest)
then: "the attribute event should pass the start of the processing chain and reach the end of the processing chain"
conditions.eventually {
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy
index 9773b492c..56521e0c1 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy
@@ -1,8 +1,6 @@
package org.openremote.test.rules
import elemental.json.Json
-import org.drools.core.time.impl.PseudoClockScheduler
-import org.kie.api.runtime.conf.ClockTypeOption
import org.openremote.manager.server.asset.AssetProcessingService
import org.openremote.manager.server.asset.AssetStorageService
import org.openremote.manager.server.rules.RulesDeployment
@@ -22,14 +20,10 @@ import static java.util.concurrent.TimeUnit.*
class ApartmentActionsTest extends Specification implements ManagerContainerTrait {
def "All Lights Off"() {
- given: "expected conditions"
- def conditions = new PollingConditions(timeout: 10, delay: 1)
-
- and: "a pseudo rules engine clock"
- RulesDeployment.DefaultClockType = ClockTypeOption.get("pseudo")
- PseudoClockScheduler sessionClock
- and: "the container is started"
+ given: "the container environment is started"
+ enablePseudoClock()
+ def conditions = new PollingConditions(timeout: 10, delay: 1)
def serverPort = findEphemeralPort()
def container = startContainer(defaultConfig(serverPort), defaultServices())
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
@@ -49,55 +43,46 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
and: "the demo attributes marked with RULE_STATE = true meta should be inserted into the engines"
conditions.eventually {
- assert rulesService.assetStates.size() == 8
- assert customerAEngine.assetStates.size() == 8
- assert customerAEngine.knowledgeSession.factCount == 8
+ assert rulesService.assetStates.size() == 9
+ assert customerAEngine.assetStates.size() == 9
+ assert customerAEngine.knowledgeSession.factCount == 9
}
and: "the room lights in an apartment to be on"
def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
assert new AssetAttributes(livingRoomAsset).get("lightSwitch").valueAsBoolean
- when: "we have prepared a rules clock"
- sessionClock = customerAEngine.sessionClock as PseudoClockScheduler
- // Set the session clock to wall time, as event expiration offsets are based on wall time
- sessionClock.advanceTime(System.currentTimeMillis(), MILLISECONDS)
-
- and: "the ALL LIGHTS OFF switch is pressed for an apartment"
+ when: "the ALL LIGHTS OFF switch is pressed for an apartment"
def apartment1AllLightsOffChange = new AttributeEvent(
managerDemoSetup.apartment1Id, "allLightsOffSwitch", Json.create(false)
)
- assetProcessingService.updateAttributeValue(apartment1AllLightsOffChange)
+ assetProcessingService.sendAttributeEvent(apartment1AllLightsOffChange)
then: "the room lights in the apartment should be off"
conditions.eventually {
- assert customerAEngine.knowledgeSession.factCount == 9
+ assert customerAEngine.knowledgeSession.factCount == 10
livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
assert !new AssetAttributes(livingRoomAsset).get("lightSwitch").valueAsBoolean
}
when: "time advanced"
- sessionClock.advanceTime(15, SECONDS)
+ withClockOf(customerAEngine) { it.advanceTime(15, SECONDS) }
- then: "event expires"
+ then: "event expired"
conditions.eventually {
- assert customerAEngine.knowledgeSession.factCount == 8
+ assert customerAEngine.knowledgeSession.factCount == 9
}
- cleanup: "the server should be stopped"
- RulesDeployment.DefaultClockType = null
+ cleanup: "stop the container"
+ disablePseudoClock()
stopContainer(container)
}
def "Presence Detection"() {
- given: "expected conditions"
- def conditions = new PollingConditions(timeout: 10, delay: 1)
-
- and: "a pseudo rules engine clock"
- RulesDeployment.DefaultClockType = ClockTypeOption.get("pseudo")
- PseudoClockScheduler sessionClock
- and: "the container is started"
+ given: "the container environment is started"
+ enablePseudoClock()
+ def conditions = new PollingConditions(timeout: 10, delay: 1)
def serverPort = findEphemeralPort()
def container = startContainer(defaultConfig(serverPort), defaultServices())
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
@@ -113,7 +98,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
customerAEngine = rulesService.tenantDeployments.get(keycloakDemoSetup.customerATenant.id)
assert customerAEngine != null
assert customerAEngine.isRunning()
- assert customerAEngine.knowledgeSession.factCount == 8
+ assert customerAEngine.knowledgeSession.factCount == 9
}
and: "the presence latch of the room should not be set"
@@ -124,18 +109,17 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
def otherLivingRoomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
assert !new AssetAttributes(otherLivingRoomAsset.getAttributes()).get("presenceDetected").valueAsBoolean
- when: "we have prepared a rules clock"
- sessionClock = customerAEngine.sessionClock as PseudoClockScheduler
- // Set the session clock to wall time, as event expiration offsets are based on wall time
- sessionClock.advanceTime(System.currentTimeMillis(), MILLISECONDS)
-
and: "several presence sensor events are triggered in the room"
for (i in 0..2) {
def livingroomPresenceChange = new AttributeEvent(
managerDemoSetup.apartment1LivingroomId, "presenceSensor", Json.create(true)
)
- assetProcessingService.updateAttributeValue(livingroomPresenceChange)
- sessionClock.advanceTime(2, MINUTES)
+ assetProcessingService.sendAttributeEvent(livingroomPresenceChange)
+ conditions.eventually {
+ // Wait until we have the facts
+ assert customerAEngine.knowledgeSession.factCount == 10 + i
+ }
+ withClockOf(customerAEngine) { it.advanceTime(2, MINUTES) }
}
and: "several presence sensor events are triggered in the other room (but not enough to trigger 'detection')"
@@ -143,11 +127,15 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
def livingroomPresenceChange = new AttributeEvent(
managerDemoSetup.apartment1LivingroomId, "presenceSensor", Json.create(true)
)
- assetProcessingService.updateAttributeValue(livingroomPresenceChange)
- sessionClock.advanceTime(10, MINUTES)
+ assetProcessingService.sendAttributeEvent(livingroomPresenceChange)
+ conditions.eventually {
+ // Wait until we have the facts
+ assert customerAEngine.knowledgeSession.factCount == 13 + i
+ }
+ withClockOf(customerAEngine) { it.advanceTime(10, MINUTES) }
}
- then: "the presence latch of the room should be set"
+ and: "the presence latch of the room should be set"
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
assert new AssetAttributes(asset.getAttributes()).get("presenceDetected").valueAsBoolean
@@ -160,16 +148,92 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
}
when: "time is advanced enough to trigger event expiration"
- sessionClock.advanceTime(1, HOURS)
- customerAEngine.knowledgeSession.fireAllRules()
+ withClockOf(customerAEngine) { it.advanceTime(1, HOURS) }
then: "the events should have been expired and retracted automatically from the knowledge session"
conditions.eventually {
- assert customerAEngine.knowledgeSession.factCount == 8
+ assert customerAEngine.knowledgeSession.factCount == 9
+ }
+
+ cleanup: "the server should be stopped"
+ disablePseudoClock()
+ stopContainer(container)
+ }
+
+ def "Vacation Mode"() {
+
+ given: "the container environment is started"
+ enablePseudoClock()
+ def conditions = new PollingConditions(timeout: 10, delay: 1)
+ def serverPort = findEphemeralPort()
+ def container = startContainer(defaultConfig(serverPort), defaultServices())
+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
+ def rulesDemoSetup = container.getService(SetupService.class).getTaskOfType(RulesDemoSetup.class)
+ def rulesService = container.getService(RulesService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
+ RulesDeployment customerAEngine
+
+ expect: "the rule engines to become available and be running"
+ conditions.eventually {
+ customerAEngine = rulesService.tenantDeployments.get(keycloakDemoSetup.customerATenant.id)
+ assert customerAEngine != null
+ assert customerAEngine.isRunning()
+ }
+
+ and: "the demo attributes marked with RULE_STATE = true meta should be inserted into the engines"
+ conditions.eventually {
+ assert rulesService.assetStates.size() == 9
+ assert customerAEngine.assetStates.size() == 9
+ assert customerAEngine.knowledgeSession.factCount == 9
+ }
+
+ when: "the vacation days are set to 5"
+ assetProcessingService.sendAttributeEvent(new AttributeEvent(
+ managerDemoSetup.apartment1Id, "vacationDays", Json.create(5)
+ ))
+
+ then: "that value should be stored"
+ conditions.eventually {
+ def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert new AssetAttributes(asset).get("vacationDays").valueAsInteger == 5
+ }
+
+ when: "time advanced to the next day, which should trigger the cron rule"
+ withClockOf(customerAEngine) { it.advanceTime(24, HOURS) }
+
+ then: "the vacation days should be decremented"
+ conditions.eventually {
+ def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert new AssetAttributes(asset).get("vacationDays").valueAsInteger == 4
+ }
+
+ when: "time advanced again (to test that the rule only fires once per day)"
+ withClockOf(customerAEngine) { it.advanceTime(10, SECONDS) }
+
+ then: "the vacation days should NOT be decremented"
+ new PollingConditions(initialDelay: 2).eventually {
+ def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert new AssetAttributes(asset).get("vacationDays").valueAsInteger == 4
+ }
+
+ expect: "the remaining vacation days to be decremented with each passing day"
+ int remainingDays = 4
+ while (remainingDays > 0) {
+
+ remainingDays--
+
+ withClockOf(customerAEngine) { it.advanceTime(1, DAYS) }
+
+ conditions.eventually {
+ def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert new AssetAttributes(asset).get("vacationDays").valueAsInteger == remainingDays
+ }
}
cleanup: "the server should be stopped"
- RulesDeployment.DefaultClockType = null
+ disablePseudoClock()
stopContainer(container)
}
}
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy
index faf4cfd0e..3525e5eda 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy
@@ -59,7 +59,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
def "Check firing of rules"() {
given: "expected conditions"
- def conditions = new PollingConditions(timeout: 10)
+ def conditions = new PollingConditions(timeout: 10, delay: 0.5)
and: "the container is started"
def serverPort = findEphemeralPort()
@@ -75,17 +75,17 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
def rulesImport = new BasicRulesImport(rulesetStorageService, keycloakDemoSetup, managerDemoSetup)
expect: "the rules engines to be ready"
- new PollingConditions(initialDelay: 3, timeout: 10, delay: 1).eventually {
+ new PollingConditions(initialDelay: 3, timeout: 20, delay: 1).eventually {
rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)
}
and: "the demo attributes marked with RULE_STATE = true meta should be inserted into the engines"
conditions.eventually {
- assert rulesService.assetStates.size() == 8
- assert rulesImport.globalEngine.assetStates.size() == 8
+ assert rulesService.assetStates.size() == 9
+ assert rulesImport.globalEngine.assetStates.size() == 9
assert rulesImport.masterEngine.assetStates.size() == 0
- assert rulesImport.customerAEngine.assetStates.size() == 8
- assert rulesImport.apartment1Engine.assetStates.size() == 4
+ assert rulesImport.customerAEngine.assetStates.size() == 9
+ assert rulesImport.apartment1Engine.assetStates.size() == 5
assert rulesImport.apartment3Engine.assetStates.size() == 2
}
@@ -100,7 +100,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
def apartment1LivingRoomPresenceDetectedChange = new AttributeEvent(
managerDemoSetup.apartment1LivingroomId, "presenceDetected", Json.create(true)
)
- assetProcessingService.updateAttributeValue(apartment1LivingRoomPresenceDetectedChange)
+ assetProcessingService.sendAttributeEvent(apartment1LivingRoomPresenceDetectedChange)
then: "the rule engines in scope should fire the 'All' and 'All changed' rules"
conditions.eventually {
@@ -121,7 +121,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
def apartment1LivingRoomCO2Change = new AttributeEvent(
managerDemoSetup.apartment1LivingroomId, "co2Level", Json.create(500)
)
- assetProcessingService.updateAttributeValue(apartment1LivingRoomCO2Change)
+ assetProcessingService.sendAttributeEvent(apartment1LivingRoomCO2Change)
then: "no rule engines should have fired after a few seconds"
new PollingConditions(initialDelay: 3).eventually assertNoRulesFired
@@ -131,14 +131,14 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
def apartment1LivingRoomWindowOpenChange = new AttributeEvent(
managerDemoSetup.apartment1LivingroomId, "windowOpen", Json.create(true)
)
- assetProcessingService.updateAttributeValue(apartment1LivingRoomWindowOpenChange)
+ assetProcessingService.sendAttributeEvent(apartment1LivingRoomWindowOpenChange)
then: "no rule engines should have fired after a few seconds"
new PollingConditions(initialDelay: 3).eventually assertNoRulesFired
when: "an old (stale) attribute event is pushed into the system"
resetRuleExecutionLoggers()
- assetProcessingService.updateAttributeValue(apartment1LivingRoomPresenceDetectedChange)
+ assetProcessingService.sendAttributeEvent(apartment1LivingRoomPresenceDetectedChange)
then: "no rule engines should have fired after a few seconds"
new PollingConditions(initialDelay: 3).eventually assertNoRulesFired
@@ -148,7 +148,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
apartment1LivingRoomPresenceDetectedChange = new AttributeEvent(
managerDemoSetup.apartment1LivingroomId, "presenceDetected", Json.create(true)
)
- assetProcessingService.updateAttributeValue(apartment1LivingRoomPresenceDetectedChange)
+ assetProcessingService.sendAttributeEvent(apartment1LivingRoomPresenceDetectedChange)
then: "the rule engines in scope should fire the 'All' rule but not the 'All changed' rule"
conditions.eventually {
@@ -178,7 +178,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
smartHomeEngine = rulesService.assetDeployments.get(managerDemoSetup.smartHomeId)
assert smartHomeEngine != null
assert smartHomeEngine.isRunning()
- assert smartHomeEngine.assetStates.size() == 8
+ assert smartHomeEngine.assetStates.size() == 9
assert smartHomeEngine.allRulesets.length == 1
assert smartHomeEngine.allRulesets[0].enabled
assert smartHomeEngine.allRulesets[0].name == "Some smart home asset rules"
@@ -193,7 +193,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
def apartment3LivingRoomPresenceDetectedChange = new AttributeEvent(
managerDemoSetup.apartment3LivingroomId, "presenceDetected", Json.create(true)
)
- assetProcessingService.updateAttributeValue(apartment3LivingRoomPresenceDetectedChange)
+ assetProcessingService.sendAttributeEvent(apartment3LivingRoomPresenceDetectedChange)
then: "the engines in scope should have fired the matched rules"
conditions.eventually {
@@ -213,7 +213,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
def apartment1LivingRoomComfortTemperatureChange = new AttributeEvent(
managerDemoSetup.apartment1LivingroomThermostatId, "comfortTemperature", Json.create(22.5)
)
- assetProcessingService.updateAttributeValue(apartment1LivingRoomComfortTemperatureChange)
+ assetProcessingService.sendAttributeEvent(apartment1LivingRoomComfortTemperatureChange)
then: "the engines in scope should have fired the matched rules"
conditions.eventually {
@@ -247,7 +247,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
rulesImport.globalEngine = rulesService.globalDeployment
assert rulesImport.globalEngine != null
assert rulesImport.globalEngine.isRunning()
- assert rulesImport.globalEngine.assetStates.size() == 8
+ assert rulesImport.globalEngine.assetStates.size() == 9
assert rulesImport.globalEngine.allRulesets.length == 2
assert rulesImport.globalEngine.allRulesets[1].enabled
assert rulesImport.globalEngine.allRulesets[1].name == "Some global test rules"
@@ -262,7 +262,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
apartment1LivingRoomComfortTemperatureChange = new AttributeEvent(
managerDemoSetup.apartment1LivingroomThermostatId, "comfortTemperature", Json.create(20.3)
)
- assetProcessingService.updateAttributeValue(apartment1LivingRoomComfortTemperatureChange)
+ assetProcessingService.sendAttributeEvent(apartment1LivingRoomComfortTemperatureChange)
then: "after a few seconds only the global engine should have fired the All, All changed and Prevent Livingroom Thermostat Change rules"
conditions.eventually {
@@ -279,7 +279,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
apartment3LivingRoomPresenceDetectedChange = new AttributeEvent(
managerDemoSetup.apartment3LivingroomId, "presenceDetected", Json.create(false)
)
- assetProcessingService.updateAttributeValue(apartment3LivingRoomPresenceDetectedChange)
+ assetProcessingService.sendAttributeEvent(apartment3LivingRoomPresenceDetectedChange)
then: "all the engines in scope should have fired the matched rules"
conditions.eventually {
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy
index f6e85b76a..853a6bb46 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy
@@ -1,7 +1,5 @@
package org.openremote.test.rules
-import org.drools.core.time.impl.PseudoClockScheduler
-import org.kie.api.runtime.conf.ClockTypeOption
import org.openremote.manager.server.rules.RulesDeployment
import org.openremote.manager.server.rules.RulesService
import org.openremote.manager.server.rules.RulesetStorageService
@@ -11,7 +9,6 @@ import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import static java.util.concurrent.TimeUnit.MILLISECONDS
import static java.util.concurrent.TimeUnit.SECONDS
import static org.openremote.test.RulesTestUtil.attachRuleExecutionLogger
@@ -65,14 +62,9 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerConta
def "Check firing of timer rules with pseudo clock"() {
- given: "expected conditions"
- def conditions = new PollingConditions(timeout: 10)
-
- and: "a pseudo rules engine clock"
- RulesDeployment.DefaultClockType = ClockTypeOption.get("pseudo")
- PseudoClockScheduler sessionClock = null
-
- and: "the container is started"
+ given: "the container environment is started"
+ enablePseudoClock()
+ def conditions = new PollingConditions(timeout: 10, delay: 1)
def serverPort = findEphemeralPort()
def container = startContainerWithoutDemoRules(defaultConfig(serverPort), defaultServices())
def rulesService = container.getService(RulesService.class)
@@ -92,10 +84,7 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerConta
assert globalEngine.isRunning()
}
- when: "we have prepared a rules clock"
- sessionClock = globalEngine.sessionClock as PseudoClockScheduler
-
- and: "the execution logger is attached"
+ when: "the execution logger is attached"
attachRuleExecutionLogger(globalEngine, globalEngineFiredRules)
then: "after a few seconds the rule engines should not have fired any rules"
@@ -104,7 +93,7 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerConta
}
when: "the clock is advanced by a few seconds"
- sessionClock.advanceTime(5, SECONDS)
+ withClockOf(globalEngine) { it.advanceTime(5, SECONDS) }
then: "the rule engines should have fire the timed execution rule in the background"
new PollingConditions().eventually {
@@ -114,7 +103,7 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerConta
}
cleanup: "the server should be stopped"
- RulesDeployment.DefaultClockType = null
+ disablePseudoClock()
stopContainer(container)
}
}
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
index e5976af44..a413864c5 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
@@ -47,7 +47,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
def rulesetResource = getClientTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(RulesetResource.class)
expect: "the rules engines to be ready"
- new PollingConditions(initialDelay: 3, timeout: 10, delay: 1).eventually {
+ new PollingConditions(initialDelay: 3, timeout: 20, delay: 1).eventually {
rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)
}
@@ -317,7 +317,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
def rulesetResource = getClientTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(RulesetResource.class)
expect: "the rules engines to be ready"
- new PollingConditions(initialDelay: 3, timeout: 10, delay: 1).eventually {
+ new PollingConditions(initialDelay: 3, timeout: 20, delay: 1).eventually {
rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)
}
@@ -547,7 +547,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
def rulesetResource = getClientTarget(serverUri(serverPort), keycloakDemoSetup.customerATenant.realm, accessToken).proxy(RulesetResource.class)
expect: "the rules engines to be ready"
- new PollingConditions(initialDelay: 3, timeout: 10, delay: 1).eventually {
+ new PollingConditions(initialDelay: 3, timeout: 20, delay: 1).eventually {
rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)
}
@@ -695,7 +695,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
def rulesetResource = getClientTarget(serverUri(serverPort), keycloakDemoSetup.customerATenant.realm, accessToken).proxy(RulesetResource.class)
expect: "the rules engines to be ready"
- new PollingConditions(initialDelay: 3, timeout: 10, delay: 1).eventually {
+ new PollingConditions(initialDelay: 3, timeout: 20, delay: 1).eventually {
rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)
}
diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
index fb0ac90b7..c569a268f 100644
--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
@@ -20,6 +20,7 @@
package org.openremote.model.asset;
import elemental.json.JsonValue;
+import org.openremote.model.AttributeRef;
import org.openremote.model.AttributeType;
import org.openremote.model.util.JsonUtil;
@@ -230,6 +231,10 @@ public abstract class AbstractAssetUpdate {
return !JsonUtil.equals(attribute.getValue(), oldValue);
}
+ public AttributeRef getAttributeRef() {
+ return attribute.getReference();
+ }
+
/**
* This is here because {@link #attribute} is not always publicly accessible
*/