100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Added TimerService pseudo clock for container, allowed combining RULE_STATE and RULE_EVENT, improved presence detection demo rule
Christian Bauer631e0bf6dbd7
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.javaindex 78ed5942d..00199bcd0 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java@@ -26,6 +26,7 @@ import org.openremote.container.Container;import org.openremote.container.message.MessageBrokerContext;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.message.MessageBrokerSetupService;+import org.openremote.container.timer.TimerService;import org.openremote.model.AttributeEvent;import org.openremote.model.AttributeRef;import org.openremote.model.AttributeState;@@ -52,11 +53,13 @@ public abstract class AbstractProtocol implements Protocol {final protected Map<AttributeRef, AssetAttribute> linkedAttributes = new HashMap<>();protected MessageBrokerContext messageBrokerContext;protected ProducerTemplate producerTemplate;+ protected TimerService timerService;protected ProtocolExecutorService executorService;@Overridepublic void init(Container container) throws Exception {LOG.info("Initializing protocol: " + getProtocolName());+ timerService = container.getService(TimerService.class);executorService = container.getService(ProtocolExecutorService.class);}@@ -141,7 +144,11 @@ public abstract class AbstractProtocol implements Protocol {}protected void sendAttributeEvent(AttributeState state) {- producerTemplate.sendBodyAndHeader(SENSOR_QUEUE, new AttributeEvent(state, System.currentTimeMillis()), "isSensorUpdate", false);+ producerTemplate.sendBodyAndHeader(+ SENSOR_QUEUE,+ new AttributeEvent(state, timerService.getCurrentTimeMillis()),+ "isSensorUpdate", false+ );}protected void onSensorUpdate(AttributeState state, long timestamp) {@@ -149,7 +156,7 @@ public abstract class AbstractProtocol implements Protocol {}protected void onSensorUpdate(AttributeState state) {- onSensorUpdate(state, System.currentTimeMillis());+ onSensorUpdate(state, timerService.getCurrentTimeMillis());}@Overridediff --git a/container/src/main/java/org/openremote/container/message/MessageBrokerSetupService.java b/container/src/main/java/org/openremote/container/message/MessageBrokerSetupService.javaindex c86bee7c1..0cecd043b 100644--- a/container/src/main/java/org/openremote/container/message/MessageBrokerSetupService.java+++ b/container/src/main/java/org/openremote/container/message/MessageBrokerSetupService.java@@ -21,6 +21,7 @@ package org.openremote.container.message;import org.apache.camel.Processor;import org.apache.camel.builder.LoggingErrorHandlerBuilder;+import org.apache.camel.impl.DefaultShutdownStrategy;import org.apache.camel.impl.DefaultStreamCachingStrategy;import org.apache.camel.spi.*;import org.apache.camel.util.ObjectHelper;@@ -103,8 +104,9 @@ public class MessageBrokerSetupService implements ContainerService {// Don't use JMS, we do our own correlationcontext.setUseBreadcrumb(false);- // TODO: Wait 1 second before forcing a route to stop?+ // Force a quick shutdown of routes with in-flight exchangescontext.getShutdownStrategy().setTimeout(1);+ context.getShutdownStrategy().setSuppressLoggingOnTimeout(true);context.setStreamCaching(true);StreamCachingStrategy streamCachingStrategy = new DefaultStreamCachingStrategy();diff --git a/container/src/main/java/org/openremote/container/security/IdentityService.java b/container/src/main/java/org/openremote/container/security/IdentityService.javaindex ad809b209..ff54a0aac 100644--- a/container/src/main/java/org/openremote/container/security/IdentityService.java+++ b/container/src/main/java/org/openremote/container/security/IdentityService.java@@ -344,7 +344,7 @@ public abstract class IdentityService implements ContainerService {if (enableDirectAccess) {// We need direct access for integration tests- LOG.warning("### Allowing direct access grants for client app '" + appName + "', this must NOT be used in production! ###");+ LOG.info("### Allowing direct access grants for client app '" + appName + "', this must NOT be used in production! ###");client.setDirectAccessGrantsEnabled(true);}diff --git a/container/src/main/java/org/openremote/container/timer/TimerService.java b/container/src/main/java/org/openremote/container/timer/TimerService.javanew file mode 100644index 000000000..9d6429f09--- /dev/null+++ b/container/src/main/java/org/openremote/container/timer/TimerService.java@@ -0,0 +1,101 @@+/*+ * 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.container.timer;++import org.openremote.container.Container;+import org.openremote.container.ContainerService;++import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicLong;++import static org.openremote.container.util.MapAccess.getString;++/**+ * Wall real clock timer or pseudo clock time (for testing).+ */+public class TimerService implements ContainerService {++ public static final String TIMER_CLOCK_TYPE = "TIMER_CLOCK_TYPE";+ public static final String TIMER_CLOCK_TYPE_DEFAULT = Clock.REAL.toString();++ public enum Clock {+ REAL {+ @Override+ public long getCurrentTimeMillis() {+ return System.currentTimeMillis();+ }++ @Override+ public long advanceTime(long amount, TimeUnit unit) {+ throw new UnsupportedOperationException("Wall clock can not be advanced manually");+ }+ },+ PSEUDO {+ AtomicLong timer = new AtomicLong(System.currentTimeMillis()); // Init to wall clock time!++ @Override+ public long getCurrentTimeMillis() {+ return timer.get();+ }++ @Override+ public long advanceTime(long amount, TimeUnit unit) {+ return timer.addAndGet(unit.toMillis(amount));+ }+ };++ public abstract long getCurrentTimeMillis();+ public abstract long advanceTime(long amount, TimeUnit unit);+ }++ protected Clock clock;++ @Override+ public void init(Container container) throws Exception {+ this.clock = Clock.valueOf(+ getString(container.getConfig(), TIMER_CLOCK_TYPE, TIMER_CLOCK_TYPE_DEFAULT)+ );+ }++ @Override+ public void start(Container container) throws Exception {++ }++ @Override+ public void stop(Container container) throws Exception {++ }++ public Clock getClock() {+ return clock;+ }++ public long getCurrentTimeMillis() {+ return getClock().getCurrentTimeMillis();+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "clock=" + clock ++ '}';+ }+}diff --git a/deployment/manager/logging.properties b/deployment/manager/logging.propertiesindex 9b1818060..4c083e38d 100644--- a/deployment/manager/logging.properties+++ b/deployment/manager/logging.properties@@ -20,6 +20,7 @@ javax.management.level=WARNINGorg.xnio.level=WARNINGorg.apache.camel.management.level=WARNINGorg.apache.camel.impl.converter.DefaultTypeConverter.level=WARNING+org.apache.camel.impl.DefaultShutdownStrategy.level=SEVERE# Set to SEVERE to log invalid access tokensorg.keycloak.adapters.BearerTokenRequestAuthenticator.level=OFFdiff --git a/manager/server/src/main/java/org/openremote/manager/server/Main.java b/manager/server/src/main/java/org/openremote/manager/server/Main.javaindex 0436b58c3..9a9a19934 100644--- a/manager/server/src/main/java/org/openremote/manager/server/Main.java+++ b/manager/server/src/main/java/org/openremote/manager/server/Main.java@@ -25,6 +25,7 @@ import org.openremote.container.ContainerService;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.message.MessageBrokerSetupService;import org.openremote.container.persistence.PersistenceService;+import org.openremote.container.timer.TimerService;import org.openremote.manager.server.agent.AgentService;import org.openremote.manager.server.apps.ConsoleAppService;import org.openremote.manager.server.asset.AssetProcessingService;@@ -52,6 +53,7 @@ public class Main {List<ContainerService> services = new ArrayList<ContainerService>() {{addAll(Arrays.asList(+ new TimerService(),new ManagerExecutorService(),new I18NService(),new PersistenceService(),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.javaindex 2ef9f8ea7..16ecb6cb7 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@@ -26,6 +26,7 @@ import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.message.MessageBrokerSetupService;+import org.openremote.container.timer.TimerService;import org.openremote.container.web.socket.WebsocketAuth;import org.openremote.manager.server.agent.AgentService;import org.openremote.manager.server.datapoint.AssetDatapointService;@@ -38,6 +39,7 @@ import org.openremote.model.AttributeExecuteStatus;import org.openremote.model.asset.*;import java.util.ArrayList;+import java.util.Date;import java.util.List;import java.util.Optional;import java.util.function.Consumer;@@ -125,6 +127,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer// Message topic for communicating from client to asset/thing layerString ASSET_QUEUE = "seda://AssetQueue?waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=false&size=1000";+ protected TimerService timerService;protected ManagerIdentityService managerIdentityService;protected RulesService rulesService;protected AgentService agentService;@@ -137,6 +140,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer@Overridepublic void init(Container container) throws Exception {+ timerService = container.getService(TimerService.class);managerIdentityService = container.getService(ManagerIdentityService.class);rulesService = container.getService(RulesService.class);agentService = container.getService(AgentService.class);@@ -389,9 +393,12 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer// Ensure timestamp of event is not in the future as that would essentially block access to// the attribute until after that time (maybe that is desirable behaviour)// Allow a leniency of 1s- if (attributeEvent.getTimestamp() - System.currentTimeMillis() > 1000) {+ long currentMillis = timerService.getCurrentTimeMillis();+ if (attributeEvent.getTimestamp() - currentMillis > 1000) {// TODO: Decide how to handle update events in the future - ignore or change timestamp- LOG.warning("Ignoring " + attributeEvent + ", event-time is in the future in:" + asset);+ LOG.warning("Ignoring future " + attributeEvent+ + ", current time: " + new Date(currentMillis) + "/" + currentMillis+ + ", event time: " + new Date(attributeEvent.getTimestamp()) + "/" + attributeEvent.getTimestamp() + " in: " + asset);return;}@@ -401,7 +408,10 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer// Check the last update timestamp of the attribute, ignoring any event that is older than last update// TODO: This means we drop out-of-sequence events, we might need better at-least-once handlingif (lastStateEvent.getTimestamp() >= 0 && attributeEvent.getTimestamp() <= lastStateEvent.getTimestamp()) {- LOG.warning("Ignoring " + attributeEvent + ", event-time is older than attribute's last state " + lastStateEvent + " in: " + asset);+ LOG.warning("Ignoring outdated " + attributeEvent+ + ", last asset state time: " + new Date(lastStateEvent.getTimestamp()) + "/" + lastStateEvent.getTimestamp()+ + ", event time: " + new Date(attributeEvent.getTimestamp()) + "/" + attributeEvent.getTimestamp() + " in: " + asset);+return;}@@ -425,14 +435,18 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerprotected void processUpdate(AssetState assetState) {try {- LOG.fine(">>> Processing start: " + assetState);+ long currentMillis = timerService.getCurrentTimeMillis();+ LOG.fine(">>> Processing start " ++ "(event time: " + new Date(assetState.getValueTimestamp()) + "/" + assetState.getValueTimestamp() ++ ", processing time: " + new Date(currentMillis) + "/" + currentMillis+ + ") : " + assetState);processorLoop:for (Consumer<AssetState> processor : processors) {try {LOG.fine("==> Processor " + processor + " accepts: " + assetState);processor.accept(assetState);} catch (Throwable t) {- LOG.log(Level.SEVERE, "Asset update consumer '" + processor + "' threw an exception whilst consuming the update:" + assetState, t);+ LOG.log(Level.SEVERE, "Asset update consumer '" + processor + "' threw an exception whilst consuming: " + assetState, t);assetState.setProcessingStatus(AssetState.ProcessingStatus.ERROR);assetState.setError(t);}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.javaindex 5f6b1bc13..633f871a6 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,6 +29,7 @@ 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.container.timer.TimerService;import org.openremote.container.web.WebService;import org.openremote.container.web.socket.WebsocketAuth;import org.openremote.manager.server.event.EventService;@@ -55,6 +56,7 @@ import static org.openremote.manager.server.event.EventService.*;public class AssetStorageService extends RouteBuilder implements ContainerService, Consumer<AssetState> {private static final Logger LOG = Logger.getLogger(AssetStorageService.class.getName());+ protected TimerService timerService;protected PersistenceService persistenceService;protected ManagerIdentityService managerIdentityService;protected AssetProcessingService assetProcessingService;@@ -62,6 +64,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic@Overridepublic void init(Container container) throws Exception {+ timerService = container.getService(TimerService.class);persistenceService = container.getService(PersistenceService.class);managerIdentityService = container.getService(ManagerIdentityService.class);assetProcessingService = container.getService(AssetProcessingService.class);@@ -124,7 +127,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic// Some sanity checking, of course the timestamp should never be -1 if we store updated attribute statelong timestamp = assetState.getAttribute().getValueTimestamp();String valueTimestamp = Long.toString(- timestamp >= 0 ? timestamp : System.currentTimeMillis()+ timestamp >= 0 ? timestamp : timerService.getCurrentTimeMillis());if (!storeAttributeValue(assetId, attributeName, value, valueTimestamp)) {throw new RuntimeException("Database update failed, no rows updated");diff --git a/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java b/manager/server/src/main/java/org/openremote/manager/server/event/EventService.javaindex 4ce44c7d9..31e3a1aab 100644--- a/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java@@ -25,6 +25,7 @@ import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.message.MessageBrokerSetupService;+import org.openremote.container.timer.TimerService;import org.openremote.container.web.socket.WebsocketAuth;import org.openremote.container.web.socket.WebsocketConstants;import org.openremote.manager.server.concurrent.ManagerExecutorService;@@ -105,7 +106,10 @@ public class EventService implements ContainerService {public void init(Container container) throws Exception {messageBrokerService = container.getService(MessageBrokerService.class);- eventSubscriptions = new EventSubscriptions(container.getService(ManagerExecutorService.class));+ eventSubscriptions = new EventSubscriptions(+ container.getService(TimerService.class),+ container.getService(ManagerExecutorService.class)+ );MessageBrokerSetupService messageBrokerSetupService = container.getService(MessageBrokerSetupService.class);messageBrokerSetupService.getContext().getTypeConverterRegistry().addTypeConverters(diff --git a/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptions.java b/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptions.javaindex 64d8c32db..8f258d55d 100644--- a/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptions.java+++ b/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptions.java@@ -22,6 +22,7 @@ package org.openremote.manager.server.event;import org.apache.camel.Exchange;import org.apache.camel.Message;import org.apache.camel.impl.DefaultMessage;+import org.openremote.container.timer.TimerService;import org.openremote.container.web.socket.WebsocketConstants;import org.openremote.manager.server.concurrent.ManagerExecutorService;import org.openremote.model.event.shared.CancelEventSubscription;@@ -38,6 +39,7 @@ public class EventSubscriptions {private static final Logger LOG = Logger.getLogger(EventSubscriptions.class.getName());+ final protected TimerService timerService;final protected Map<String, SessionSubscriptions> sessionSubscriptions = new HashMap<>();class SessionSubscriptions extends HashSet<SessionSubscription> {@@ -46,7 +48,7 @@ public class EventSubscriptions {boolean expired =sessionSubscription.timestamp+ (EventSubscription.RENEWAL_PERIOD_SECONDS * 1000)- < System.currentTimeMillis();+ < timerService.getCurrentTimeMillis();if (expired) {LOG.fine("Removing expired; " + sessionSubscription.subscription);}@@ -57,8 +59,7 @@ public class EventSubscriptions {public void update(EventSubscription eventSubscription) {cancel(eventSubscription.getEventType());- SessionSubscription sessionSubscription = new SessionSubscription(System.currentTimeMillis(), eventSubscription);- add(sessionSubscription);+ add(new SessionSubscription(timerService.getCurrentTimeMillis(), eventSubscription));}public void cancel(String eventType) {@@ -80,8 +81,9 @@ public class EventSubscriptions {}}- public EventSubscriptions(ManagerExecutorService executorService) {+ public EventSubscriptions(TimerService timerService, ManagerExecutorService executorService) {LOG.info("Starting background task checking for expired event subscriptions from clients");+ this.timerService = timerService;executorService.scheduleAtFixedRate(() -> {synchronized (this.sessionSubscriptions) {for (SessionSubscriptions subscriptions : sessionSubscriptions.values()) {diff --git a/manager/server/src/main/java/org/openremote/manager/server/notification/NotificationService.java b/manager/server/src/main/java/org/openremote/manager/server/notification/NotificationService.javaindex 350b45e80..94e8a5bec 100644--- a/manager/server/src/main/java/org/openremote/manager/server/notification/NotificationService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/notification/NotificationService.java@@ -54,7 +54,7 @@ public class NotificationService implements ContainerService {fcmKey = container.getConfig().get("FCM_KEY");if (fcmKey == null) {- LOG.severe("FCM_KEY not defined, notification service cannot send fcm notification");+ LOG.info("FCM_KEY not defined, notification service cannot send fcm notification");}this.persistenceService = container.getService(PersistenceService.class);@@ -104,25 +104,24 @@ public class NotificationService implements ContainerService {alertNotification.setDeliveryStatus(DeliveryStatus.PENDING);persistenceService.doTransaction((EntityManager entityManager) -> {entityManager.merge(alertNotification);- if (fcmKey != null) {- List<DeviceNotificationToken> allTokenForUser = findAllTokenForUser(userId);- for (DeviceNotificationToken notificationToken : allTokenForUser) {-- try {- Invocation.Builder builder = target.request().header("Authorization", "key=" + fcmKey);- Response response = builder.post(Entity.entity(new FCMMessage(notificationToken.getToken()), "application/json"));- if (response.getStatus() != 200) {- LOG.severe("Error send FCM notification status=[" + response.getStatus() + "], statusInformation=[" + response.getStatusInfo() + "]");- }- response.close();- } catch (Exception e) {- LOG.log(Level.SEVERE, "Error sending notiifcation to FCM", e);+ if (fcmKey == null) {+ LOG.info("No FCM key configured, can't send to '" + userId + "', not sending: " + alertNotification);+ return;+ }+ List<DeviceNotificationToken> allTokenForUser = findAllTokenForUser(userId);+ for (DeviceNotificationToken notificationToken : allTokenForUser) {+ try {+ Invocation.Builder builder = target.request().header("Authorization", "key=" + fcmKey);+ Response response = builder.post(Entity.entity(new FCMMessage(notificationToken.getToken()), "application/json"));+ if (response.getStatus() != 200) {+ LOG.severe("Error send FCM notification status=[" + response.getStatus() + "], statusInformation=[" + response.getStatusInfo() + "]");}+ response.close();+ } catch (Exception e) {+ LOG.log(Level.SEVERE, "Error sending notification to FCM", e);}}});--}public List<AlertNotification> getPendingAlertForUserId(String userId) {diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RuleExecutionLogger.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RuleExecutionLogger.javaindex fd68dedbf..4c95ab04f 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RuleExecutionLogger.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RuleExecutionLogger.java@@ -60,20 +60,20 @@ public class RuleExecutionLogger extends DefaultAgendaEventListener {}if (ruleName.startsWith("\"--")) {- LOG.finest(String.format("*** On " + contextSupplier.get() + "\n\nRule %s\n" ++ LOG.finest(String.format("*** On " + contextSupplier.get() + "\nRule %s\n" +"\tDeclarations \n%s" +"\tLHS objects(antecedents)\n%s", ruleName, declarationLog, objectLog));return;}if (ruleName.startsWith("\"-")) {- LOG.fine(String.format("*** On " + contextSupplier.get() + "\n\nRule %s\n" ++ LOG.fine(String.format("*** On " + contextSupplier.get() + "\nRule %s\n" +"\tDeclarations \n%s" +"\tLHS objects(antecedents)\n%s", ruleName, declarationLog, objectLog));return;}- LOG.info(String.format("*** On " + contextSupplier.get() + "\n\nRule %s\n" ++ LOG.info(String.format("*** On " + contextSupplier.get() + "\nRule %s\n" +"\tDeclarations \n%s" +"\tLHS objects(antecedents)\n%s", ruleName, declarationLog, objectLog));}diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.javaindex 1a03dffcb..1d5e11f30 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java@@ -34,6 +34,7 @@ import org.kie.api.builder.model.KieModuleModel;import org.kie.api.builder.model.KieSessionModel;import org.kie.api.conf.EqualityBehaviorOption;import org.kie.api.conf.EventProcessingOption;+import org.kie.api.event.process.*;import org.kie.api.event.rule.ObjectDeletedEvent;import org.kie.api.event.rule.ObjectInsertedEvent;import org.kie.api.event.rule.ObjectUpdatedEvent;@@ -44,6 +45,7 @@ import org.kie.api.runtime.KieSessionConfiguration;import org.kie.api.runtime.conf.ClockTypeOption;import org.kie.api.runtime.rule.FactHandle;import org.kie.api.time.SessionClock;+import org.openremote.container.timer.TimerService;import org.openremote.container.util.Util;import org.openremote.manager.server.asset.AssetProcessingService;import org.openremote.manager.server.asset.AssetStorageService;@@ -74,6 +76,7 @@ public class RulesEngine<T extends Ruleset> {public static final Logger LOG = Logger.getLogger(RulesEngine.class.getName());+ final protected TimerService timerService;final protected ManagerExecutorService executorService;final protected NotificationService notificationService;final protected AssetStorageService assetStorageService;@@ -81,8 +84,6 @@ public class RulesEngine<T extends Ruleset> {final protected Class<T> rulesetType;final protected String id;- // This is here so Clock Type can be set to pseudo from tests- protected static ClockTypeOption DefaultClockType;private static final int AUTO_START_DELAY_SECONDS = 2;private static Long counter = 1L;static final protected Util UTIL = new Util();@@ -99,11 +100,13 @@ public class RulesEngine<T extends Ruleset> {final protected Map<AssetState, FactHandle> assetStates = new HashMap<>();protected ScheduledFuture startTimer;- public RulesEngine(ManagerExecutorService executorService,+ public RulesEngine(TimerService timerService,+ ManagerExecutorService executorService,AssetStorageService assetStorageService,NotificationService notificationService,AssetProcessingService assetProcessingService,Class<T> rulesetType, String id) {+ this.timerService = timerService;this.executorService = executorService;this.assetStorageService = assetStorageService;this.notificationService = notificationService; // shouldBeUser service or Identity Service ?@@ -354,8 +357,13 @@ public class RulesEngine<T extends Ruleset> {KieSessionConfiguration kieSessionConfiguration = kieServices.newKieSessionConfiguration();// Which clock to use ("pseudo" for testing, "realtime" otherwise)- ClockTypeOption clockType = DefaultClockType != null ? DefaultClockType : ClockTypeOption.get("realtime");- kieSessionConfiguration.setOption(clockType);+ switch (timerService.getClock()) {+ case PSEUDO:+ kieSessionConfiguration.setOption(ClockTypeOption.get("pseudo"));+ break;+ default:+ kieSessionConfiguration.setOption(ClockTypeOption.get("realtime"));+ }try {knowledgeSession = kieContainer.newKieSession(kieSessionConfiguration);@@ -363,8 +371,9 @@ public class RulesEngine<T extends Ruleset> {// 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());+ if (timerService.getClock() == TimerService.Clock.PSEUDO) {+ ((PseudoClockScheduler) knowledgeSession.getSessionClock())+ .setStartupTime(timerService.getCurrentTimeMillis());}setGlobal("assets", createAssetsFacade());@@ -503,7 +512,9 @@ public class RulesEngine<T extends Ruleset> {protected synchronized void insertAssetEvent(long expirationOffset, AssetEvent assetEvent) {FactHandle factHandle = insertIntoSession(assetEvent);- scheduleExpiration(assetEvent, factHandle, expirationOffset);+ if (factHandle != null) {+ scheduleExpiration(assetEvent, factHandle, expirationOffset);+ }}protected synchronized FactHandle insertIntoSession(AbstractAssetUpdate update) {@@ -511,7 +522,9 @@ public class RulesEngine<T extends Ruleset> {LOG.fine("On " + this + ", engine is in error state or not running, ignoring: " + update);return null;}- return knowledgeSession.insert(update);+ FactHandle fh = knowledgeSession.insert(update);+ LOG.fine("On " + this + ", fact count after insert: " + knowledgeSession.getFactCount());+ return fh;}protected Assets createAssetsFacade() {@@ -583,17 +596,23 @@ public class RulesEngine<T extends Ruleset> {}@Override- public void dispatch(AttributeEvent event) {- // Check if the asset ID of the event can be found in the original query- AssetQuery checkQuery = query();- checkQuery.id = event.getEntityId();- if (assetStorageService.find(checkQuery) == null) {- throw new IllegalArgumentException(- "Access to asset not allowed for this rule engine scope: " + event- );+ public void dispatch(AttributeEvent... events) {+ if (events != null) {+ for (AttributeEvent event : events) {+ // Set event time to current container timer+ event.timestamp = timerService.getCurrentTimeMillis();+ // Check if the asset ID of the event can be found in the original query+ AssetQuery checkQuery = query();+ checkQuery.id = event.getEntityId();+ if (assetStorageService.find(checkQuery) == null) {+ throw new IllegalArgumentException(+ "Access to asset not allowed for this rule engine scope: " + event+ );+ }+ LOG.fine("Dispatching on " + RulesEngine.this + ": " + event);+ assetProcessingService.sendAttributeEvent(event);+ }}- LOG.fine("Dispatching on " + RulesEngine.this + ": " + event);- assetProcessingService.sendAttributeEvent(event);}};}@@ -649,6 +668,8 @@ public class RulesEngine<T extends Ruleset> {* Yes, this is a hack.*/protected void scheduleExpiration(AssetEvent assetEvent, FactHandle factHandle, long expirationOffset) {+ if (!isRunning())+ return;InternalSchedulerService sessionScheduler = knowledgeSession.getSessionClock();JobHandle jobHandle = new JDKTimerService.JDKJobHandle(assetEvent.getId().hashCode());class AssetEventExpireJobContext implements JobContext {diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.javaindex 817204c28..722122d53 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java@@ -27,6 +27,7 @@ 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.container.timer.TimerService;import org.openremote.manager.server.asset.AssetProcessingService;import org.openremote.manager.server.asset.AssetStorageService;import org.openremote.manager.server.asset.ServerAsset;@@ -75,6 +76,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Conspublic static final String RULE_EVENT_EXPIRES = "RULE_EVENT_EXPIRES";public static final String RULE_EVENT_EXPIRES_DEFAULT = "1h";+ protected TimerService timerService;protected ManagerExecutorService executorService;protected PersistenceService persistenceService;protected RulesetStorageService rulesetStorageService;@@ -96,6 +98,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons@Overridepublic void init(Container container) throws Exception {+ timerService = container.getService(TimerService.class);executorService = container.getService(ManagerExecutorService.class);persistenceService = container.getService(PersistenceService.class);rulesetStorageService = container.getService(RulesetStorageService.class);@@ -194,12 +197,12 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons@Overridepublic void accept(AssetState assetState) {+ // We might process two facts for a single attribute update, if that is what the user wantsif (assetState.getAttribute().isRuleState()) {updateAssetState(assetState, false);- } else if (assetState.getAttribute().isRuleEvent()) {+ }+ if (assetState.getAttribute().isRuleEvent()) {process(new AssetEvent(assetState));- } else {- LOG.finest("Ignoring asset state as attribute is not a rules state or event: " + assetState);}}@@ -412,6 +415,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons// Global rules have access to everything in the systemif (globalDeployment == null) {globalDeployment = new RulesEngine<>(+ timerService,executorService,assetStorageService,notificationService,@@ -445,6 +449,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons.computeIfAbsent(ruleset.getRealmId(), (realmId) -> {created[0] = true;return new RulesEngine<>(+ timerService,executorService,assetStorageService,notificationService,@@ -508,6 +513,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons.computeIfAbsent(ruleset.getAssetId(), (assetId) -> {created[0] = true;return new RulesEngine<>(+ timerService,executorService,assetStorageService,notificationService,diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerCleanSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerCleanSetup.javaindex d2d9d1428..6dd19a1d0 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerCleanSetup.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerCleanSetup.java@@ -36,6 +36,6 @@ public class ManagerCleanSetup extends AbstractManagerSetup {public void execute() throws Exception {LOG.info("Dropping database schema and all data");persistenceService.dropSchema();- LOG.info("### NOTE: The message 'PSQLException: ERROR: relation ... does not exist' is normal and can be ignored!");+ LOG.info("### NOTE: The message 'relation ... does not exist' is normal and can be ignored!");}}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.javaindex 8894063f6..5cfc90917 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@@ -54,8 +54,8 @@ import static org.openremote.model.asset.agent.ProtocolConfiguration.initProtocopublic class ManagerDemoSetup extends AbstractManagerSetup {// Update these numbers whenever you change a RULE_STATE flag in test data- public static final int DEMO_RULE_STATES_APARTMENT_1 = 6;- public static final int DEMO_RULE_STATES_APARTMENT_2 = 2;+ public static final int DEMO_RULE_STATES_APARTMENT_1 = 8;+ public static final int DEMO_RULE_STATES_APARTMENT_2 = 3;public static final int DEMO_RULE_STATES_APARTMENT_3 = 2;public static final int DEMO_RULE_STATES_SMART_HOME = DEMO_RULE_STATES_APARTMENT_1 + DEMO_RULE_STATES_APARTMENT_2 + DEMO_RULE_STATES_APARTMENT_3;public static final int DEMO_RULE_STATES_CUSTOMER_A = DEMO_RULE_STATES_SMART_HOME;@@ -400,29 +400,31 @@ public class ManagerDemoSetup extends AbstractManagerSetup {new MetaItem(AssetMeta.DESCRIPTION, Json.create("PIR sensor that sends 'true' when motion is sensed"))+ ).add(+ new MetaItem(AssetMeta.RULE_STATE, Json.create(true))).add(new MetaItem(AssetMeta.RULE_EVENT, Json.create(true)))),- new AssetAttribute("motionCounter", AttributeType.INTEGER, Json.create(0))+ new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false)).setMeta(new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Motion Counter"))+ new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected"))).add(new MetaItem(AssetMeta.DESCRIPTION, Json.create(- "Sensor that increments a counter when motion is sensed"+ "Someone is currently present in the room"))).add(- new MetaItem(AssetMeta.RULE_EVENT, Json.create(true))+ new MetaItem(AssetMeta.RULE_STATE, Json.create(true)))),- new AssetAttribute("presenceDetected", AttributeType.DECIMAL, Json.createNull())+ new AssetAttribute("lastPresenceDetected", AttributeType.DECIMAL, Json.createNull()).setMeta(new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected Timestamp"))+ new MetaItem(AssetMeta.LABEL, Json.create("Last Presence Timestamp"))).add(new MetaItem(AssetMeta.DESCRIPTION, Json.create(- "Timestamp of last detected presence, empty if nobody is present"+ "Timestamp of last detected presence"))).add(new MetaItem(AssetMeta.RULE_STATE, Json.create(true))@@ -539,37 +541,37 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment2Livingroom.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment2Livingroom.setType(ROOM);List<AssetAttribute> apartment2LivingroomAttributes = Arrays.asList(- new AssetAttribute("motionSensor", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("motionCounter", AttributeType.INTEGER, Json.create(0)).setMeta(new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Motion Sensor"))+ new MetaItem(AssetMeta.LABEL, Json.create("Motion Counter"))).add(new MetaItem(AssetMeta.DESCRIPTION, Json.create(- "PIR sensor that sends 'true' when motion is sensed"+ "Sensor that increments a counter when motion is sensed"))).add(new MetaItem(AssetMeta.RULE_EVENT, Json.create(true)))),- new AssetAttribute("motionCounter", AttributeType.INTEGER, Json.create(0))+ new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false)).setMeta(new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Motion Counter"))+ new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected"))).add(new MetaItem(AssetMeta.DESCRIPTION, Json.create(- "Sensor that increments a counter when motion is sensed"+ "Someone is currently present in the room"))).add(- new MetaItem(AssetMeta.RULE_EVENT, Json.create(true))+ new MetaItem(AssetMeta.RULE_STATE, Json.create(true)))),- new AssetAttribute("presenceDetected", AttributeType.DECIMAL, Json.createNull())+ new AssetAttribute("lastPresenceDetected", AttributeType.DECIMAL, Json.createNull()).setMeta(new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected Timestamp"))+ new MetaItem(AssetMeta.LABEL, Json.create("Last Presence Timestamp"))).add(new MetaItem(AssetMeta.DESCRIPTION, Json.create(- "Timestamp of last detected presence, empty if nobody is present"+ "Timestamp of last detected presence"))).add(new MetaItem(AssetMeta.RULE_STATE, Json.create(true))@@ -619,37 +621,13 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment3Livingroom.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment3Livingroom.setType(ROOM);List<AssetAttribute> apartment3LivingroomAttributes = Arrays.asList(- new AssetAttribute("motionSensor", AttributeType.BOOLEAN, Json.create(false))- .setMeta(- new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Motion Sensor"))- ).add(- new MetaItem(AssetMeta.DESCRIPTION, Json.create(- "PIR sensor that sends 'true' when motion is sensed"- ))- ).add(- new MetaItem(AssetMeta.RULE_EVENT, Json.create(true))- )- ),- new AssetAttribute("motionCounter", AttributeType.INTEGER, Json.create(0))- .setMeta(- new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Motion Counter"))- ).add(- new MetaItem(AssetMeta.DESCRIPTION, Json.create(- "Sensor that increments a counter when motion is sensed"- ))- ).add(- new MetaItem(AssetMeta.RULE_EVENT, Json.create(true))- )- ),- new AssetAttribute("presenceDetected", AttributeType.DECIMAL, Json.createNull())+ new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false)).setMeta(new Meta().add(- new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected Timestamp"))+ new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected"))).add(new MetaItem(AssetMeta.DESCRIPTION, Json.create(- "Timestamp of last detected presence, empty if nobody is present"+ "Someone is currently present in the room"))).add(new MetaItem(AssetMeta.RULE_STATE, Json.create(true))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.javaindex 5b314fe08..f700d09d5 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@@ -22,6 +22,7 @@ package org.openremote.manager.server.setup.builtin;import org.apache.commons.io.IOUtils;import org.openremote.container.Container;import org.openremote.manager.server.setup.AbstractManagerSetup;+import org.openremote.manager.shared.rules.AssetRuleset;import org.openremote.manager.shared.rules.Ruleset;import org.openremote.manager.shared.rules.TenantRuleset;@@ -49,19 +50,27 @@ public class RulesDemoSetup extends AbstractManagerSetup {// ################################ Rules demo data ###################################+ // See ApartmentActionsTest.groovytry (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentAllLightsOff.drl")) {String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));Ruleset ruleset = new TenantRuleset("Demo Apartment - All Lights Off", keycloakDemoSetup.customerATenant.getId(), rules);apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();}- try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentPresenceDetection.drl")) {+ 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 - Presence Detection", keycloakDemoSetup.customerATenant.getId(), rules);+ Ruleset ruleset = new TenantRuleset("Demo Apartment - Vacation Mode", keycloakDemoSetup.customerATenant.getId(), rules);apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();}- try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentVacationMode.drl")) {++ // See ApartmentPresenceDetectionTest.groovy, these are conflicting rules and therefore we need two different apartments+ try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentPresenceDetectionPIR.drl")) {String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));- Ruleset ruleset = new TenantRuleset("Demo Apartment - Vacation Mode", keycloakDemoSetup.customerATenant.getId(), rules);+ Ruleset ruleset = new AssetRuleset("Demo Apartment - Presence Detection with motion PIR", managerDemoSetup.apartment1Id, rules);+ apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();+ }+ try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentPresenceDetectionCounter.drl")) {+ String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));+ Ruleset ruleset = new AssetRuleset("Demo Apartment - Presence Detection with motion counter", managerDemoSetup.apartment2Id, rules);apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();}}diff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drldeleted file mode 100644index d12cb6b69..000000000--- a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl+++ /dev/null@@ -1,89 +0,0 @@-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;--/*--Calculate and set the "presenceDetected" timestamp attribute of a ROOM when either motion sensor-is triggered several times within a defined time window, or a motion counter is incremented-several times within a time window. The timestamp will be cleared if no motion is sensed in-a defined time window or a motion counter has not been incremented within a time window.-All time windows and the number of matches required can be configured.--*/--/* ####################################### MOTION SENSOR ###################################### */--rule "Set presence detected timestamp if motion sensor is triggered in time window"-when- // The motion sensor in a room is triggered- $roomEvent : AssetEvent(type == AssetType.ROOM, attributeName == "motionSensor", value.asBoolean)- // More than 2 times in the last 15 minutes- Number(intValue > 2) from accumulate(- $roomEvent2 : AssetEvent(id == $roomEvent.id, attributeName == "motionSensor", value.asBoolean) over window:time(15m),- count($roomEvent2)- )- // And the presence detected timestamp is not set already- AssetState(id == $roomEvent.getId(), attributeName == "presenceDetected", valueNull)-then- // Set the presence detected timestamp of the room- long currentTime = drools.getWorkingMemory().getSessionClock().getCurrentTime();- assets.dispatch(- new AttributeEvent($roomEvent.getId(), "presenceDetected", Json .create(currentTime))- );-end--rule "Clear presence detected timestamp if motion sensor was not triggered in a while"-when- // The motion sensor in a room as not been triggered in the last 15 minutes- $roomEvent : AssetEvent(type == AssetType.ROOM, attributeName == "motionSensor", value.asBoolean)- not(AssetEvent(id == $roomEvent.id, attributeName == "motionSensor", value.asBoolean, this != $roomEvent, this after[0s,15m] $roomEvent ))- // And the presence detected timestamp is set- AssetState(id == $roomEvent.getId(), attributeName == "presenceDetected", !valueNull)-then- // Clear the presence detected timestamp of the room- assets.dispatch(- new AttributeEvent($roomEvent.getId(), "presenceDetected", Json .createNull())- );-end--/* ####################################### MOTION COUNTER ###################################### */--rule "Set presence detected timestamp if motion counter is incremented in time window"-when- // The motion counter in a room is incremented more than 2 times in the last 15 minutes- $roomEvent : AssetEvent(type == AssetType.ROOM, attributeName == "motionCounter", $orgMC: value.asNumber > 0)- accumulate(- AssetEvent(id == $roomEvent.id, attributeName == "motionCounter", $newMC: value.asNumber > 0) over window:time(15m);- $count: count(1),- $maxMC: max($newMC);- $maxMC > $orgMC, $count > 2- )- // And the presence detected timestamp is not set already- AssetState(id == $roomEvent.getId(), attributeName == "presenceDetected", valueNull)-then- // Set the presence detected timestamp of the room- long currentTime = drools.getWorkingMemory().getSessionClock().getCurrentTime();- assets.dispatch(- new AttributeEvent($roomEvent.getId(), "presenceDetected", Json .create(currentTime))- );-end--rule "Clear presence detected timestamp if motion counter was not incremented in a while"-when- // The motion counter in a room as not been incremented in the last 15 minutes- $roomEvent : AssetEvent(type == AssetType.ROOM, attributeName == "motionCounter", $orgMC: value.asNumber() > 0)- not(AssetEvent(id == $roomEvent.id, attributeName == "motionCounter", value.asNumber > $orgMC, this != $roomEvent, this after[0s,15m] $roomEvent ))- // And the presence detected timestamp is set- AssetState(id == $roomEvent.getId(), attributeName == "presenceDetected", !valueNull)-then- // Clear the presence detected timestamp of the room- assets.dispatch(- new AttributeEvent($roomEvent.getId(), "presenceDetected", Json .createNull())- );-enddiff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drlnew file mode 100644index 000000000..e100a3c86--- /dev/null+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl@@ -0,0 +1,52 @@+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;++/*+Calculate and set the "presenceDetected" flag and the "lastPresenceDetected" timestamp attributes+of a ROOM when a motion counter is incremented several times within a time window. The flag will be+removed if the motion counter has not been incremented within a time window. All time windows and+the number of matches required can be configured.+*/+/* TODO This needs more work++rule "Set presence detected timestamp if motion counter is incremented in time window"+when+ // The motion counter in a room is incremented more than 2 times in the last 15 minutes+ $roomEvent : AssetEvent(type == AssetType.ROOM, attributeName == "motionCounter", $orgMC: value.asNumber > 0)+ accumulate(+ AssetEvent(id == $roomEvent.id, attributeName == "motionCounter", $newMC: value.asNumber > 0) over window:time(15m);+ $count: count(1),+ $maxMC: max($newMC);+ $maxMC > $orgMC, $count > 2+ )+ // And the presence detected flag is not set already+ AssetState(id == $roomEvent.getId(), attributeName == "presenceDetected", !value.asBoolean)+then+ // Set the presence detected flag and last presence detected timestamp of the room+ long currentTime = drools.getWorkingMemory().getSessionClock().getCurrentTime();+ assets.dispatch(+ new AttributeEvent($roomEvent.getId(), "presenceDetected", Json.create(true)),+ new AttributeEvent($roomEvent.getId(), "lastPresenceDetected", Json .create(currentTime))+ );+end++rule "Clear presence detected timestamp if motion counter was not incremented in a while"+when+ // The motion counter in a room as not been incremented in the last 15 minutes+ $roomEvent : AssetEvent(type == AssetType.ROOM, attributeName == "motionCounter", $orgMC: value.asNumber() > 0)+ not(AssetEvent(id == $roomEvent.id, attributeName == "motionCounter", value.asNumber > $orgMC, this != $roomEvent, this after[0s,15m] $roomEvent ))+ // And the presence detected flag is set+ AssetState(id == $roomEvent.getId(), attributeName == "presenceDetected", value.asBoolean)+then+ // Clear the presence detected flag of the room+ assets.dispatch(+ new AttributeEvent($roomEvent.getId(), "presenceDetected", Json .create(false))+ );+end+*/\ No newline at end of filediff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drlnew file mode 100644index 000000000..676a64c16--- /dev/null+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drl@@ -0,0 +1,67 @@+package org.openremote.test.rules;++import org.openremote.model.*;+import org.openremote.model.asset.*+import elemental.json.Json+import java.util.Date;++global java.util.logging.Logger LOG;+global org.openremote.model.rules.Assets assets;++/*+Calculate and set the "presenceDetected" flag and the "lastPresenceDetected" timestamp attributes+of a ROOM when a motion sensor triggers several times within a time window. The flag will be+removed if the motion sensor has not been triggered within a time window. All time windows and+the number of matches required can be configured.+*/++rule "Set presence detected flag if motion sensor is triggered in time window"+when+ // A room has a motion sensor+ $room : AssetState(type == AssetType.ROOM, attributeName == "motionSensor")+ // And at least 5 motion sensor triggers have been received in the last 10 minutes+ accumulate(+ AssetEvent(id == $room.id, attributeName == "motionSensor", value.asBoolean) over window:time(10m);+ $count: count(1);+ $count >= 5+ )+ // And the presence detected flag is not set already+ AssetState(id == $room.id, attributeName == "presenceDetected", !value.asBoolean)+then+ // Set the presence detected flag of the room+ assets.dispatch(+ new AttributeEvent($room.getId(), "presenceDetected", Json.create(true))+ );+end++rule "Update the presence detected timestamp if motion sensor is triggered and we have already detected presence"+when+ // The presence detected flag is set in a room+ $room: AssetState(type == AssetType.ROOM, attributeName == "presenceDetected", value.asBoolean)+ // And the motion sensor is triggered+ $sensor: AssetState(id == $room.id, attributeName == "motionSensor", value.asBoolean)+then+ // Update the last presence detected timestamp of the room+ assets.dispatch(+ new AttributeEvent($room.getId(), "lastPresenceDetected", Json.create($sensor.getValueTimestamp()))+ );+end++rule "Clear presence detected flag if motion sensor was not triggered in a while"+when+ // A room has a motion sensor+ $room: AssetState(type == AssetType.ROOM, attributeName == "motionSensor")+ // And the presence detected flag is set+ AssetState(id == $room.id, attributeName == "presenceDetected", value.asBoolean)+ // And no motion sensor triggers have been received in the last 10 minutes+ accumulate(+ AssetEvent(id == $room.id, attributeName == "motionSensor", value.asBoolean) over window:time(10m);+ $count: count(1);+ $count == 0+ )+then+ // Clear the presence detected flag of the room+ assets.dispatch(+ new AttributeEvent($room.getId(), "presenceDetected", Json.create(false))+ );+enddiff --git a/manager/server/src/main/resources/logging.properties b/manager/server/src/main/resources/logging.propertiesindex 7132c0515..0069380c9 100644--- a/manager/server/src/main/resources/logging.properties+++ b/manager/server/src/main/resources/logging.properties@@ -20,6 +20,8 @@ javax.management.level=WARNINGorg.xnio.level=WARNINGorg.apache.camel.management.level=WARNINGorg.apache.camel.impl.converter.DefaultTypeConverter.level=WARNING+org.apache.camel.impl.DefaultShutdownStrategy.level=SEVERE+com.google.gwt.place.shared.PlaceHistoryHandler.level=SEVERE# Set to SEVERE to log invalid access tokensorg.keycloak.adapters.BearerTokenRequestAuthenticator.level=SEVEREdiff --git a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovyindex f9963d37e..3b95f9390 100644--- a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy+++ b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy@@ -9,6 +9,7 @@ import org.openremote.container.ContainerServiceimport org.openremote.container.message.MessageBrokerServiceimport org.openremote.container.message.MessageBrokerSetupServiceimport org.openremote.container.persistence.PersistenceService+import org.openremote.container.timer.TimerServiceimport org.openremote.manager.server.agent.AgentServiceimport org.openremote.manager.server.apps.ConsoleAppServiceimport org.openremote.manager.server.asset.AssetProcessingService@@ -26,12 +27,17 @@ import org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.concurrent.ManagerExecutorServiceimport org.openremote.manager.server.web.ManagerWebService+import java.util.concurrent.TimeUnit++import static org.openremote.container.timer.TimerService.Clock.PSEUDO+import static org.openremote.container.timer.TimerService.TIMER_CLOCK_TYPEimport static org.openremote.manager.server.setup.builtin.BuiltinSetupTasks.SETUP_IMPORT_DEMO_RULEStrait ManagerContainerTrait extends ContainerTrait {static Iterable<ContainerService> defaultServices(Iterable<ContainerService> additionalServices) {[+ new TimerService(),new ManagerExecutorService(),new I18NService(),new PersistenceService(),@@ -67,12 +73,11 @@ trait ManagerContainerTrait extends ContainerTrait {startContainer(config << [(SETUP_IMPORT_DEMO_RULES): "false"], services)}- static void enablePseudoClock() {- RulesEngine.DefaultClockType = ClockTypeOption.get("pseudo")- }-- static void disablePseudoClock() {- RulesEngine.DefaultClockType = null+ /**+ * Use pseudo clock instead of wall clock.+ */+ static Container startContainerWithPseudoClock(Map<String, String> config, Iterable<ContainerService> services) {+ startContainer(config << [(TIMER_CLOCK_TYPE): PSEUDO.name()], services)}/**@@ -86,4 +91,25 @@ trait ManagerContainerTrait extends ContainerTrait {(engine.sessionClock as PseudoClockScheduler).currentTime}+ /**+ * Execute pseudo clock operations in Container.+ */+ static void withClockOf(Container container, Closure<TimerService.Clock> clockConsumer) {+ clockConsumer.call(container.getService(TimerService.class).getClock())+ }++ static long getClockTimeOf(Container container) {+ container.getService(TimerService.class).getClock().getCurrentTimeMillis()+ }++ static void advancePseudoClocks(long amount, TimeUnit unit, Container container, RulesEngine[] engine) {+ withClockOf(container) { it.advanceTime(amount, unit)}+ engine.each { withClockOf(it) { it.advanceTime(amount, unit)} }+ }++ static void setPseudoClocksToRealTime(Container container, RulesEngine[] engine) {+ withClockOf(container) { it.advanceTime(System.currentTimeMillis() - it.currentTimeMillis, TimeUnit.MILLISECONDS) }+ engine.each { withClockOf(it) { it.advanceTime(System.currentTimeMillis() - it.currentTime, TimeUnit.MILLISECONDS)} }+ }+}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.groovyindex 2e74ad656..8aa3376bf 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@@ -27,12 +27,9 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitdef "Check processing of asset updates"() {- //region given: "expected conditions"given: "expected conditions"def conditions = new PollingConditions(timeout: 10, delay: 1)- //endregion- //region and: "a mock protocol"// TODO: Update this to use Simulator Protocoland: "a mock protocol"def mockProtocolName = Constants.PROTOCOL_NAMESPACE + ":mockProtocol"@@ -73,9 +70,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitreturn mockProtocolName}}- //endregion- //region and: "a mock attribute event consumer"and: "a mock attribute event consumer"List<AssetState> updatesPassedStartOfProcessingChain = []List<AssetState> updatesReachedEndOfProcessingChain = []@@ -87,9 +82,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitConsumer<AssetState> mockStartConsumer = { assetUpdate ->updatesPassedStartOfProcessingChain.add(assetUpdate)}- //endregion- //region and: "the container is started with the mock consumers and mock protocol"and: "the container is started with the mock consumers and mock protocol"def serverPort = findEphemeralPort()def container = startContainer(defaultConfig(serverPort), defaultServices(mockProtocol))@@ -100,16 +93,14 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitdef keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)assetProcessingService.processors.add(0, mockStartConsumer)assetProcessingService.processors.add(mockEndConsumer)- //endregion// The conditions here depend on how we handle the initial insert of facts into the rule engines- //expect: "the demo rule engine should start and trigger the 'Switch room lights off when apartment ALL LIGHTS OFF switch is off' rule and cause attribute events to go through the system"expect: "the demo rule engine should start and trigger the 'Switch room lights off when apartment ALL LIGHTS OFF switch is off' rule and cause attribute events to go through the system"conditions.eventually {def customerAEngine = rulesService.tenantDeployments.get(keycloakDemoSetup.customerATenant.id)assert customerAEngine != nullassert customerAEngine.isRunning()- assert customerAEngine.rulesets.size() == 3+ assert customerAEngine.rulesets.size() == 2assert updatesPassedStartOfProcessingChain.size() == 0assert updatesReachedEndOfProcessingChain.size() == 0}@@ -118,7 +109,6 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitupdatesPassedStartOfProcessingChain.clear()updatesReachedEndOfProcessingChain.clear()- //region and: "a mock agent that uses the mock protocol is created"and: "a mock agent that uses the mock protocol is created"def mockAgent = new ServerAsset()mockAgent.setName("Mock Agent")@@ -127,9 +117,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitmockAgent.setAttributeList(Collections.singletonList(mockProtocolConfig))mockAgent.setRealmId(keycloakDemoSetup.masterTenant.id)mockAgent = assetStorageService.merge(mockAgent)- //endregion- //region and: "a mock thing asset is created with a valid protocol attribute, an invalid protocol attribute and a plain attribute"and: "a mock thing asset is created with a valid protocol attribute, an invalid protocol attribute and a plain attribute"def mockThing = new ServerAsset(mockAgent)mockThing.setName("Mock Thing Asset")@@ -171,8 +159,6 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait]mockThing.setAttributeList(mockThingAttributes)mockThing = assetStorageService.merge(mockThing)- //endregion-then: "the mock thing to be deployed to the protocol"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.groovyindex 0307fa6bd..e3341ccd5 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@@ -21,10 +21,9 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTraidef "All Lights Off"() {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 container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)def rulesService = container.getService(RulesService.class)@@ -51,8 +50,9 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTraiassert livingRoomAsset.getAttribute("lightSwitch").get().valueAsBooleanwhen: "the ALL LIGHTS OFF push-button is pressed for an apartment"+ setPseudoClocksToRealTime(container, customerAEngine)def apartment1AllLightsOffChange = new AttributeEvent(- managerDemoSetup.apartment1Id, "allLightsOffSwitch", Json.create(true)+ managerDemoSetup.apartment1Id, "allLightsOffSwitch", Json.create(true), getClockTimeOf(container))assetProcessingService.sendAttributeEvent(apartment1AllLightsOffChange)@@ -64,7 +64,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai}when: "time advanced"- withClockOf(customerAEngine) { it.advanceTime(15, SECONDS) }+ advancePseudoClocks(15, SECONDS, container, customerAEngine)then: "event expired"conditions.eventually {@@ -72,17 +72,15 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai}cleanup: "stop the container"- disablePseudoClock()stopContainer(container)}def "Vacation Mode"() {given: "the container environment is started"- enablePseudoClock()def conditions = new PollingConditions(timeout: 15, delay: 1)def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)def rulesService = container.getService(RulesService.class)@@ -105,8 +103,9 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai}when: "the vacation days are set to 5"+ setPseudoClocksToRealTime(container, customerAEngine)assetProcessingService.sendAttributeEvent(new AttributeEvent(- managerDemoSetup.apartment1Id, "vacationDays", Json.create(5)+ managerDemoSetup.apartment1Id, "vacationDays", Json.create(5), getClockTimeOf(container)))then: "that value should be stored"@@ -117,7 +116,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai}when: "time advanced to the next day, which should trigger the cron rule"- withClockOf(customerAEngine) { it.advanceTime(24, HOURS) }+ advancePseudoClocks(24, HOURS, container, customerAEngine)then: "the vacation days should be decremented"conditions.eventually {@@ -127,7 +126,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai}when: "time advanced again (to test that the rule only fires once per day)"- withClockOf(customerAEngine) { it.advanceTime(10, SECONDS) }+ advancePseudoClocks(10, SECONDS, container, customerAEngine)then: "the vacation days should NOT be decremented"new PollingConditions(initialDelay: 2).eventually {@@ -142,21 +141,22 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrairemainingDays--- withClockOf(customerAEngine) { it.advanceTime(1, DAYS) }+ advancePseudoClocks(1, DAYS, container, customerAEngine)conditions.eventually {def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)assert asset.getAttribute("vacationDays").get().valueAsInteger == remainingDaysassert asset.getAttribute("lastScene").get().valueAsString == "AWAY"}}- withClockOf(customerAEngine) { it.advanceTime(8, HOURS) }++ and: "after some more time to switch to HOME status"+ advancePseudoClocks(8, HOURS, container, customerAEngine)conditions.eventually {def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)assert asset.getAttribute("lastScene").get().valueAsString == "HOME"}cleanup: "the server should be stopped"- disablePseudoClock()stopContainer(container)}}diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentPresenceDetectionTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentPresenceDetectionTest.groovyindex 66e6821aa..9f3a6259c 100644--- a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentPresenceDetectionTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentPresenceDetectionTest.groovy@@ -10,11 +10,18 @@ import org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.server.setup.builtin.ManagerDemoSetupimport org.openremote.model.AttributeEvent+import org.openremote.model.asset.AssetStateimport org.openremote.test.ManagerContainerTrait+import spock.lang.Ignoreimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions-import static java.util.concurrent.TimeUnit.*+import java.util.function.Consumer++import static java.util.concurrent.TimeUnit.HOURS+import static java.util.concurrent.TimeUnit.MINUTES+import static java.util.concurrent.TimeUnit.SECONDS+import static org.openremote.manager.server.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_APARTMENT_1import static org.openremote.manager.server.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_CUSTOMER_Aclass ApartmentPresenceDetectionTest extends Specification implements ManagerContainerTrait {@@ -22,100 +29,141 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCondef "Set and clear presence detection timestamp depending on motion sensor"() {given: "the container environment is started"- enablePseudoClock()- def conditions = new PollingConditions(timeout: 5, delay: 1)+ def conditions = new PollingConditions(timeout: 5, delay: 0.2)def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)- def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)def rulesService = container.getService(RulesService.class)def assetProcessingService = container.getService(AssetProcessingService.class)def assetStorageService = container.getService(AssetStorageService.class)- RulesEngine customerAEngine = null+ RulesEngine apartment1Engine = null++ and: "a mock attribute event consumer"+ List<AssetState> updatesCompletedProcessing = []+ Consumer<AssetState> assetProcessingCompleteConsumer = { assetUpdate ->+ updatesCompletedProcessing.add(assetUpdate)+ }+ assetProcessingService.processors.add(assetProcessingCompleteConsumer)+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()- assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A+ apartment1Engine = rulesService.assetDeployments.get(managerDemoSetup.apartment1Id)+ assert apartment1Engine != null+ assert apartment1Engine.isRunning()+ assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1}- and: "the presence detected timestamp of the room should not be set"+ and: "the presence detected flag and timestamp of the room should not be set"def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)- assert livingRoomAsset.getAttribute("presenceDetected").get().value.getType() == JsonType.NULL+ assert !livingRoomAsset.getAttribute("presenceDetected").get().valueAsBoolean+ assert livingRoomAsset.getAttribute("lastPresenceDetected").get().value.getType() == JsonType.NULL++ when: "several motion sensor events are triggered in the room, but not enough for presence detection"+ updatesCompletedProcessing = []+ setPseudoClocksToRealTime(container, apartment1Engine)+ // Send 5 triggers each 3 minutes apart+ for (i in 1..5) {+ def motionSensorTrigger = new AttributeEvent(+ managerDemoSetup.apartment1LivingroomId, "motionSensor", Json.create(true), getClockTimeOf(apartment1Engine)+ )+ assetProcessingService.sendAttributeEvent(motionSensorTrigger)+ conditions.eventually {+ assert updatesCompletedProcessing.findAll { it.attributeName == "motionSensor" }.size() == i+ }+ advancePseudoClocks(3, MINUTES, container, apartment1Engine)+ }- and: "the presence detected timestamp of the other room should not be set"- def otherLivingRoomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)- assert otherLivingRoomAsset.getAttribute("presenceDetected").get().value.getType() == JsonType.NULL+ then: "presence should not be detected"+ new PollingConditions(initialDelay: 5).eventually {+ def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)+ assert !asset.getAttribute("presenceDetected").get().valueAsBoolean+ assert asset.getAttribute("lastPresenceDetected").get().value.getType() == JsonType.NULL+ }- when: "several presence sensor events are triggered in the room"- double expectedPresenceTimestampStart = getClockTimeOf(customerAEngine)- for (i in 0..2) {+ when: "time is advanced enough for event expiration"+ advancePseudoClocks(2, HOURS, container, apartment1Engine)++ then: "the events should have been expired and retracted automatically from the knowledge session"+ conditions.eventually {+ assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1+ }++ when: "several motion sensor events are triggered in the room, fast enough for presence detection"+ updatesCompletedProcessing = []+ double expectedLastPresenceTimestamp = 0+ // Send 5 triggers each 1 minute apart+ for (i in 1..5) {def motionSensorTrigger = new AttributeEvent(- managerDemoSetup.apartment1LivingroomId, "motionSensor", Json.create(true)+ managerDemoSetup.apartment1LivingroomId, "motionSensor", Json.create(true), getClockTimeOf(apartment1Engine))+ expectedLastPresenceTimestamp = motionSensorTrigger.timestampassetProcessingService.sendAttributeEvent(motionSensorTrigger)conditions.eventually {- // Wait until we have the facts- assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A + 1 + i+ assert updatesCompletedProcessing.findAll { it.attributeName == "motionSensor" }.size() == i}- withClockOf(customerAEngine) { it.advanceTime(2, MINUTES) }+ advancePseudoClocks(1, MINUTES, container, apartment1Engine)}- double expectedPresenceTimestampEnd = getClockTimeOf(customerAEngine)- then: "the presence detected timestamp of the room should be set"+ then: "presence should be detected"conditions.eventually {def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)- def presenceDetectedTimestamp = asset.getAttribute("presenceDetected").get().value.asNumber()- assert presenceDetectedTimestamp > expectedPresenceTimestampStart && presenceDetectedTimestamp < expectedPresenceTimestampEnd+ assert asset.getAttribute("presenceDetected").get().valueAsBoolean+ assert asset.getAttribute("lastPresenceDetected").get().value.asNumber() == expectedLastPresenceTimestamp}- when: "several presence sensor events are triggered in the other room (but not enough to trigger 'detection')"- for (i in 0..2) {+ when: "time moves on and we keep triggering the motion sensor in short intervals "+ updatesCompletedProcessing = []+ // Send 20 triggers each 90 seconds apart+ for (i in 1..20) {def motionSensorTrigger = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "motionSensor", Json.create(true)+ managerDemoSetup.apartment1LivingroomId, "motionSensor", Json.create(true), getClockTimeOf(apartment1Engine))+ expectedLastPresenceTimestamp = motionSensorTrigger.timestampassetProcessingService.sendAttributeEvent(motionSensorTrigger)conditions.eventually {- // Wait until we have the facts- assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A + 4 + i+ assert updatesCompletedProcessing.findAll { it.attributeName == "motionSensor" }.size() == i}- withClockOf(customerAEngine) { it.advanceTime(10, MINUTES) }+ advancePseudoClocks(10, SECONDS, container, apartment1Engine)}- then: "the presence detected timestamp of the other room should NOT be set"+ then: "presence should still be detected and the timestamp updated"conditions.eventually {- def asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)- assert asset.getAttribute("presenceDetected").get().value.getType() == JsonType.NULL+ def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)+ assert asset.getAttribute("presenceDetected").get().valueAsBoolean+ assert asset.getAttribute("lastPresenceDetected").get().value.asNumber() == expectedLastPresenceTimestamp}- and: "meanwhile presence detected timestamp of the first room should have been cleared"+ when: "time moves on without the motion sensor being triggered"+ advancePseudoClocks(20, MINUTES, container, apartment1Engine)++ then: "presence should be gone but the last timestamp still available"conditions.eventually {def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)- assert asset.getAttribute("presenceDetected").get().value.getType() == JsonType.NULL+ assert !asset.getAttribute("presenceDetected").get().valueAsBoolean+ assert asset.getAttribute("lastPresenceDetected").get().value.asNumber() == expectedLastPresenceTimestamp}- when: "time is advanced enough to trigger event expiration"- withClockOf(customerAEngine) { it.advanceTime(1, HOURS) }+ when: "time is advanced enough for event expiration"+ advancePseudoClocks(2, HOURS, container, apartment1Engine)then: "the events should have been expired and retracted automatically from the knowledge session"conditions.eventually {- assert customerAEngine.knowledgeSession.factCount == DEMO_RULE_STATES_CUSTOMER_A+ assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1}cleanup: "the server should be stopped"- disablePseudoClock()stopContainer(container)}+ // TODO This needs more work+ @Ignoredef "Set and clear presence detection timestamp depending on motion counter"() {given: "the container environment is started"- enablePseudoClock()def conditions = new PollingConditions(timeout: 5, delay: 1)def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)def rulesService = container.getService(RulesService.class)@@ -143,7 +191,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCondouble expectedPresenceTimestampStart = getClockTimeOf(customerAEngine)for (i in 0..2) {def motionCounterIncrement = new AttributeEvent(- managerDemoSetup.apartment1LivingroomId, "motionCounter", Json.create(i+1)+ managerDemoSetup.apartment1LivingroomId, "motionCounter", Json.create(i + 1))assetProcessingService.sendAttributeEvent(motionCounterIncrement)conditions.eventually {@@ -164,7 +212,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerConwhen: "the motion counter sensor in the other room is incremented (but not enough to trigger 'detection')"for (i in 0..2) {def motionCounterIncrement = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "motionCounter", Json.create(i+1)+ managerDemoSetup.apartment2LivingroomId, "motionCounter", Json.create(i + 1))assetProcessingService.sendAttributeEvent(motionCounterIncrement)conditions.eventually {@@ -195,7 +243,6 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon}cleanup: "the server should be stopped"- 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.groovyindex ddbb06d82..fb85bfacf 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@@ -96,9 +96,8 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerattachRuleExecutionLogger(rulesImport.apartment3Engine, apartment3EngineFiredRules)and: "an attribute event is pushed into the system for an attribute with RULE_STATE meta set to true"- def presenceDetectedTimestamp = System.currentTimeMillis()def apartment1LivingRoomPresenceDetectedChange = new AttributeEvent(- managerDemoSetup.apartment1LivingroomId, "presenceDetected", Json.create(presenceDetectedTimestamp)+ managerDemoSetup.apartment1LivingroomId, "presenceDetected", Json.create(true))assetProcessingService.sendAttributeEvent(apartment1LivingRoomPresenceDetectedChange)@@ -146,7 +145,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "an attribute event with the same value as current value is pushed into the system"resetRuleExecutionLoggers()apartment1LivingRoomPresenceDetectedChange = new AttributeEvent(- managerDemoSetup.apartment1LivingroomId, "presenceDetected", Json.create(presenceDetectedTimestamp)+ managerDemoSetup.apartment1LivingroomId, "presenceDetected", Json.create(true))assetProcessingService.sendAttributeEvent(apartment1LivingRoomPresenceDetectedChange)@@ -191,7 +190,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerand: "an apartment 3 living room attribute event occurs"def apartment3LivingRoomPresenceDetectedChange = new AttributeEvent(- managerDemoSetup.apartment3LivingroomId, "presenceDetected", Json.create(System.currentTimeMillis())+ managerDemoSetup.apartment3LivingroomId, "presenceDetected", Json.create(true))assetProcessingService.sendAttributeEvent(apartment3LivingRoomPresenceDetectedChange)@@ -202,7 +201,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassert customerAEngineFiredRules.size() == 2assert customerAEngineFiredRules.containsAll(["All", "All changed"])assert smartHomeEngineFiredRules.size() == 5- assert smartHomeEngineFiredRules.containsAll(["Living Room All", "Current Asset Update", "Parent Type Residence", "Asset Type Room", "JSON Number value types"])+ assert smartHomeEngineFiredRules.containsAll(["Living Room All", "Current Asset Update", "Parent Type Residence", "Asset Type Room", "Boolean Attributes"])assert apartment3EngineFiredRules.size() == 2assert apartment3EngineFiredRules.containsAll(["All", "All changed"])assert apartment1EngineFiredRules.size() == 0diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovyindex f449072d2..931e77ec4 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@@ -10,6 +10,8 @@ import spock.lang.Specificationimport spock.util.concurrent.PollingConditionsimport static java.util.concurrent.TimeUnit.SECONDS+import static org.openremote.container.timer.TimerService.Clock.PSEUDO+import static org.openremote.container.timer.TimerService.TIMER_CLOCK_TYPEimport static org.openremote.test.RulesTestUtil.attachRuleExecutionLoggerimport static org.openremote.manager.server.setup.builtin.ManagerDemoSetup.*@@ -65,10 +67,9 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerContadef "Check firing of timer rules with pseudo clock"() {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 container = startContainerWithoutDemoRules(defaultConfig(serverPort) << [(TIMER_CLOCK_TYPE): PSEUDO.name()], defaultServices())def rulesService = container.getService(RulesService.class)def rulesetStorageService = container.getService(RulesetStorageService.class)@@ -96,7 +97,7 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerConta}when: "the clock is advanced by a few seconds"- withClockOf(globalEngine) { it.advanceTime(10, SECONDS) }+ advancePseudoClocks(10, SECONDS, container, globalEngine)// TODO Weird behavior of timer rules, pseudo clock, and active mode: More than 5 seconds is needed to fire rule twicethen: "the rule engines should have fired the timed execution rule in the background"@@ -107,7 +108,6 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerConta}cleanup: "the server should be stopped"- disablePseudoClock()stopContainer(container)}}diff --git a/model/src/main/java/org/openremote/model/AttributeEvent.java b/model/src/main/java/org/openremote/model/AttributeEvent.javaindex 6b5cbbf4d..b96b63cd1 100644--- a/model/src/main/java/org/openremote/model/AttributeEvent.java+++ b/model/src/main/java/org/openremote/model/AttributeEvent.java@@ -99,6 +99,10 @@ public class AttributeEvent extends SharedEvent {this(new AttributeState(new AttributeRef(entityId, attributeName), value));}+ public AttributeEvent(String entityId, String attributeName, JsonValue value, long timestamp) {+ this(new AttributeState(new AttributeRef(entityId, attributeName), value), timestamp);+ }+public AttributeEvent(AttributeRef attributeRef, JsonValue value) {this(new AttributeState(attributeRef, value));}diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.javaindex 8dcb7d423..05ed29453 100644--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java@@ -119,7 +119,8 @@ public enum AssetMeta {/*** Should attribute writes be processed by the rules engines as facts in knowledge sessions, with a lifecycle* that reflects the state of the asset attribute (the {@link AssetState} facts in the rules sessions are kept- * in sync with asset changes).+ * in sync with asset changes). If you want two types of facts in your rules knowledge session for a single+ * attribute, with state and event behavior, combine this with {@link #RULE_EVENT}.*/RULE_STATE(ASSET_META_NAMESPACE + ":ruleState", new Access(true, false, true), JsonType.BOOLEAN),@@ -127,7 +128,8 @@ public enum AssetMeta {* Should attribute writes be processed by the rules engines as events in knowledge sessions with limited* lifecycle that reflects how the event is processed (the {@link AssetEvent} facts* in the rules sessions are expired automatically after a certain time and/or if they can no longer be matched- * by time operations).+ * by time operations). If you want two types of facts in your rules knowledge session for a single attribute,+ * with state and event behavior, combine this with {@link #RULE_STATE\}.*/RULE_EVENT(ASSET_META_NAMESPACE + ":ruleEvent", new Access(true, false, true), JsonType.BOOLEAN),diff --git a/model/src/main/java/org/openremote/model/rules/Assets.java b/model/src/main/java/org/openremote/model/rules/Assets.javaindex dde31c0af..3f6082b80 100644--- a/model/src/main/java/org/openremote/model/rules/Assets.java+++ b/model/src/main/java/org/openremote/model/rules/Assets.java@@ -45,6 +45,6 @@ public abstract class Assets {abstract public RestrictedQuery query();- abstract public void dispatch(AttributeEvent event);+ abstract public void dispatch(AttributeEvent... event);}