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
Implemented tracking of location predicate rules and geofence adapter interface with test
Rich Turner46531800131f
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.javaindex 1c9e42efe..fccf38c64 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java@@ -29,11 +29,14 @@ import org.openremote.manager.notification.NotificationService;import org.openremote.manager.rules.facade.AssetsFacade;import org.openremote.manager.rules.facade.UsersFacade;import org.openremote.manager.security.ManagerIdentityService;+import org.openremote.model.asset.AssetMeta;+import org.openremote.model.asset.BaseAssetQuery;import org.openremote.model.rules.*;import java.util.*;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;+import java.util.function.BiConsumer;import java.util.logging.Level;import java.util.logging.Logger;@@ -57,12 +60,14 @@ public class RulesEngine<T extends Ruleset> {final protected RulesEngineId<T> id;final protected Assets assetsFacade;final protected Users usersFacade;+ final protected BiConsumer<RulesEngine, Map<AssetState, Set<BaseAssetQuery.LocationPredicate>>> assetLocationPredicateMapConsumer;final protected Map<Long, RulesetDeployment> deployments = new LinkedHashMap<>();final protected RulesFacts facts;final protected InferenceRulesEngine engine;protected boolean running;+ protected boolean trackLocationPredicates;protected ScheduledFuture fireTimer;protected ScheduledFuture statsTimer;@@ -78,13 +83,15 @@ public class RulesEngine<T extends Ruleset> {AssetStorageService assetStorageService,AssetProcessingService assetProcessingService,NotificationService notificationService,- RulesEngineId<T> id) {+ RulesEngineId<T> id,+ BiConsumer<RulesEngine, Map<AssetState, Set<BaseAssetQuery.LocationPredicate>>> assetLocationPredicateMapConsumer) {this.timerService = timerService;this.executorService = executorService;this.assetStorageService = assetStorageService;this.id = id;this.assetsFacade = new AssetsFacade<>(id, assetStorageService, assetProcessingService::sendAttributeEvent);this.usersFacade = new UsersFacade<>(id, assetStorageService, notificationService, identityService);+ this.assetLocationPredicateMapConsumer = assetLocationPredicateMapConsumer;this.facts = new RulesFacts(assetsFacade, this, RULES_LOG);engine = new InferenceRulesEngine(@@ -245,6 +252,7 @@ public class RulesEngine<T extends Ruleset> {LOG.info("Starting: " + this);running = true;+ trackLocationPredicates = true;fire();// Start a background stats printer if INFO level logging is enabled@@ -297,6 +305,10 @@ public class RulesEngine<T extends Ruleset> {return;}+ if (trackLocationPredicates && assetLocationPredicateMapConsumer != null) {+ facts.startTrackingLocationRules();+ }+// Set the current clockRulesClock clock = new RulesClock(timerService);facts.setClock(clock);@@ -338,9 +350,20 @@ public class RulesEngine<T extends Ruleset> {facts.reset();}}++ if (trackLocationPredicates) {+ trackLocationPredicates = false;+ if (assetLocationPredicateMapConsumer != null) {+ processLocationRules(facts.stopTrackingLocationRules());+ }+ }}public void stop() {+ stop(false);+ }++ public void stop(boolean systemShutdownInProgress) {if (!isRunning()) {return;}@@ -354,10 +377,15 @@ public class RulesEngine<T extends Ruleset> {statsTimer = null;}running = false;++ if (!systemShutdownInProgress && assetLocationPredicateMapConsumer != null) {+ assetLocationPredicateMapConsumer.accept(this, null);+ }}public void updateFact(AssetState assetState, boolean fireImmediately) {facts.putAssetState(assetState);+ trackLocationPredicates = assetState.getAttributeName().equals("location");if (fireImmediately) {fire();}@@ -365,11 +393,13 @@ public class RulesEngine<T extends Ruleset> {public void removeFact(AssetState assetState) {facts.removeAssetState(assetState);+ trackLocationPredicates = assetState.getAttributeName().equals("location");fire();}public void insertFact(String expires, AssetState assetState) {facts.insertAssetEvent(expires, assetState);+ trackLocationPredicates = assetState.getAttributeName().equals("location");fire();}@@ -403,6 +433,16 @@ public class RulesEngine<T extends Ruleset> {});}+ /**+ * This is called with all the asset's that have a location attribute marked with {@link AssetMeta#RULE_STATE} and+ * that are in the scope of a rule containing a location predicate.+ */+ protected void processLocationRules(Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> assetStateLocationPredicateMap) {+ if (assetLocationPredicateMapConsumer != null) {+ assetLocationPredicateMapConsumer.accept(this, assetStateLocationPredicateMap);+ }+ }+@Overridepublic String toString() {return getClass().getSimpleName() + "{" +diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.javaindex 682d977c6..d9930e700 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java@@ -23,6 +23,7 @@ import org.jeasy.rules.api.Facts;import org.jeasy.rules.api.Rule;import org.jeasy.rules.api.RuleListener;import org.openremote.model.asset.AssetQuery;+import org.openremote.model.asset.BaseAssetQuery;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeExecuteStatus;import org.openremote.model.rules.AssetQueryPredicate;@@ -65,6 +66,8 @@ public class RulesFacts extends Facts implements RuleListener {final protected Map<String, Collection<AssetState>> assetTypeIndex = new HashMap<>();protected int triggerCount;+ protected boolean trackLocationRules;+ protected Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> assetStateLocationPredicateMap = null;public RulesFacts(Assets assetsFacade, Object loggingContext, Logger logger) {this.assetsFacade = assetsFacade;@@ -77,6 +80,17 @@ public class RulesFacts extends Facts implements RuleListener {asMap().put(ANONYMOUS_FACTS, new ArrayDeque(INITIAL_CAPACITY));}+ protected void startTrackingLocationRules() {+ trackLocationRules = true;+ }++ protected Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> stopTrackingLocationRules() {+ trackLocationRules = false;+ Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> assetStateLocationPredicateMap = this.assetStateLocationPredicateMap;+ this.assetStateLocationPredicateMap = null;+ return assetStateLocationPredicateMap;+ }+public void setClock(RulesClock clock) {this.clock = clock;asMap().put(CLOCK, clock);@@ -407,6 +421,23 @@ public class RulesFacts extends Facts implements RuleListener {}public Stream<AssetState> matchAssetState(AssetQuery assetQuery) {++ if (trackLocationRules) {+ if (assetQuery.location != null) {+ LOG.fine("Location predicate found");+ // Collect asset states only where the attribute is location (location predicates only make sense when the location+ // attribute is exposed to rules - we don't support RULE_EVENT facts just RULE_STATE+ if (assetStateLocationPredicateMap == null) {+ // TODO: Use static reference to well known location attribute when it is implemented+ Collection<AssetState> locationAssetStates = getAssetStates().stream().filter(assetState -> assetState.getAttributeName().equalsIgnoreCase("location")).collect(Collectors.toSet());+ assetStateLocationPredicateMap = new HashMap<>(locationAssetStates.size());+ locationAssetStates.forEach(assetState -> assetStateLocationPredicateMap.put(assetState, new HashSet<>()));+ }++ assetStateLocationPredicateMap.forEach((assetState, locationPredicates) -> locationPredicates.add(assetQuery.location));+ }+ }+Predicate<AssetState> p = new AssetQueryPredicate(assetQuery);// Match against all asset states by defaultdiff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.javaindex 95f9777ab..c193675e1 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java@@ -29,11 +29,9 @@ import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.*;import org.openremote.manager.concurrent.ManagerExecutorService;import org.openremote.manager.notification.NotificationService;+import org.openremote.manager.rules.geofence.GeofenceAssetAdapter;import org.openremote.manager.security.ManagerIdentityService;-import org.openremote.model.asset.Asset;-import org.openremote.model.asset.AssetAttribute;-import org.openremote.model.asset.AssetMeta;-import org.openremote.model.asset.AssetQuery;+import org.openremote.model.asset.*;import org.openremote.model.attribute.AttributeEvent.Source;import org.openremote.model.rules.*;import org.openremote.model.security.Tenant;@@ -42,6 +40,8 @@ import org.openremote.model.value.ObjectValue;import javax.persistence.EntityManager;import java.util.*;+import java.util.concurrent.ScheduledFuture;+import java.util.function.BiConsumer;import java.util.function.BiFunction;import java.util.logging.Logger;import java.util.stream.Collectors;@@ -60,16 +60,15 @@ import static org.openremote.model.asset.AssetAttribute.getAddedOrModifiedAttrib/*** Manages {@link RulesEngine}s for stored {@link Ruleset}s and processes asset attribute updates.* <p>- * If an updated attribute {@link AssetAttribute#isRuleState}, this implementation of- * {@link AssetUpdateProcessor} converts the update message to an {@link AssetState} fact.- * This service keeps the facts and thus the state of rule facts are in sync with the asset state- * changes that occur. If an asset attribute value changes, the {@link AssetState} in the rules- * engines will be updated to reflect the change.+ * If an updated attribute {@link AssetAttribute#isRuleState}, this implementation of {@link AssetUpdateProcessor}+ * converts the update message to an {@link AssetState} fact. This service keeps the facts and thus the state of rule+ * facts are in sync with the asset state changes that occur. If an asset attribute value changes, the {@link+ * AssetState} in the rules engines will be updated to reflect the change.* <p>- * If an updated attribute {@link AssetAttribute#isRuleEvent}, another temporary {@link AssetState}- * fact is inserted in the rules engines in scope. This fact expires automatically if the lifetime- * set in {@link RulesService#RULE_EVENT_EXPIRES} is reached, or if the lifetime set in the- * attribute {@link AssetMeta#RULE_EVENT_EXPIRES} is reached.+ * If an updated attribute {@link AssetAttribute#isRuleEvent}, another temporary {@link AssetState} fact is inserted in+ * the rules engines in scope. This fact expires automatically if the lifetime set in {@link+ * RulesService#RULE_EVENT_EXPIRES} is reached, or if the lifetime set in the attribute {@link+ * AssetMeta#RULE_EVENT_EXPIRES} is reached.* <p>* Each asset attribute update is processed in the following order:* <ol>@@ -85,6 +84,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Assepublic static final String RULE_EVENT_EXPIRES = "RULE_EVENT_EXPIRES";public static final String RULE_EVENT_EXPIRES_DEFAULT = "1h";+ public static int GEOFENCE_PROCESSING_DEBOUNCE_MILLIS = 10000;protected TimerService timerService;protected ManagerExecutorService executorService;@@ -100,6 +100,13 @@ public class RulesService extends RouteBuilder implements ContainerService, Asseprotected final Map<String, RulesEngine<AssetRuleset>> assetEngines = new HashMap<>();protected String[] activeTenantIds;+ protected Collection<GeofenceAssetAdapter> geofenceAssetAdapters;+ protected BiConsumer<RulesEngine, Map<AssetState, Set<BaseAssetQuery.LocationPredicate>>> locationPredicateRulesConsumer;+ protected Map<RulesEngine, Map<AssetState, Set<BaseAssetQuery.LocationPredicate>>> engineAssetLocationPredicateMap = new HashMap<>();+ protected Set<AssetState> modifiedAssetLocationPredicates = new HashSet<>();+ protected ScheduledFuture scheduledGeofenceProcessor;+ protected boolean firstGeofenceProcessorRun = true;+// Keep global list of asset states that have been pushed to any engines// The objects are already in memory inside the rule engines but keeping them// here means we can quickly insert facts into newly started engines@@ -157,6 +164,15 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse@Overridepublic void start(Container container) throws Exception {+ geofenceAssetAdapters = container.getServices(GeofenceAssetAdapter.class)+ .stream()+ .sorted(Comparator.comparingInt(GeofenceAssetAdapter::getPriority).reversed())+ .collect(Collectors.toSet());+ if (!geofenceAssetAdapters.isEmpty()) {+ LOG.info("GeoefenceAssetAdapters found: " + geofenceAssetAdapters.size());+ locationPredicateRulesConsumer = this::onEngineLocationRulesChanged;+ }+LOG.info("Deploying global rulesets");rulesetStorageService.findEnabledGlobalRulesets().forEach(this::deployGlobalRuleset);@@ -165,8 +181,8 @@ public class RulesService extends RouteBuilder implements ContainerService, AsserulesetStorageService.findEnabledTenantRulesets().stream().filter(rd ->- Arrays.stream(activeTenantIds)- .anyMatch(tenantId -> rd.getRealmId().equals(tenantId))+ Arrays.stream(activeTenantIds)+ .anyMatch(tenantId -> rd.getRealmId().equals(tenantId))).forEach(this::deployTenantRuleset);LOG.info("Deploying asset rulesets");@@ -191,13 +207,14 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse@Overridepublic void stop(Container container) throws Exception {withLock(getClass().getSimpleName() + "::stop", () -> {- assetEngines.forEach((assetId, rulesEngine) -> rulesEngine.stop());+ // TODO: Do rule engines need to be stopped on shutdown+ assetEngines.forEach((assetId, rulesEngine) -> rulesEngine.stop(true));assetEngines.clear();- tenantEngines.forEach((realm, rulesEngine) -> rulesEngine.stop());+ tenantEngines.forEach((realm, rulesEngine) -> rulesEngine.stop(true));tenantEngines.clear();if (globalEngine != null) {- globalEngine.stop();+ globalEngine.stop(true);globalEngine = null;}});@@ -255,7 +272,8 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse.filter(re -> re.getId().getRealmId().map(id -> id.equals(tenant.getId())).orElse(false)).forEach(RulesEngine::stop);assetEngines.entrySet().removeIf(entry ->- entry.getValue().getId().getRealmId().map(id -> id.equals(tenant.getId())).orElse(false)+ entry.getValue().getId().getRealmId().map(id -> id.equals(tenant.getId())).orElse(+ false));} else {@@ -326,7 +344,9 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse).filter(AssetAttribute::isRuleState).collect(Collectors.toList());// Retract facts for attributes that are obsolete- getAddedOrModifiedAttributes(newRuleStateAttributes, oldRuleStateAttributes, key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME))+ getAddedOrModifiedAttributes(newRuleStateAttributes,+ oldRuleStateAttributes,+ key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME)).forEach(obsoleteFactAttribute -> {AssetState update = buildAssetState.apply(loadedAsset, obsoleteFactAttribute);LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting: " + update);@@ -334,7 +354,9 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse});// Insert facts for attributes that are new- getAddedOrModifiedAttributes(oldRuleStateAttributes, newRuleStateAttributes, key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME))+ getAddedOrModifiedAttributes(oldRuleStateAttributes,+ newRuleStateAttributes,+ key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME)).forEach(newFactAttribute -> {AssetState assetState = buildAssetState.apply(loadedAsset, newFactAttribute);LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), updating: " + assetState);@@ -410,8 +432,8 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse}/**- * Deploy the ruleset into the global engine creating the engine if necessary; if the engine was created then it- * is returned from the method.+ * Deploy the ruleset into the global engine creating the engine if necessary; if the engine was created then it is+ * returned from the method.*/protected RulesEngine<GlobalRuleset> deployGlobalRuleset(GlobalRuleset ruleset) {return withLockReturning(getClass().getSimpleName() + "::deployGlobalRuleset", () -> {@@ -426,7 +448,8 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseassetStorageService,assetProcessingService,notificationService,- new RulesEngineId<>()+ new RulesEngineId<>(),+ this::onEngineLocationRulesChanged);}@@ -462,7 +485,8 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseassetStorageService,assetProcessingService,notificationService,- new RulesEngineId<>(realmId)+ new RulesEngineId<>(realmId),+ this::onEngineLocationRulesChanged);});@@ -492,7 +516,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse.entrySet().stream().map(es ->- new Pair<>(assetStorageService.find(es.getKey(), true), es.getValue())+ new Pair<>(assetStorageService.find(es.getKey(), true), es.getValue())).filter(assetAndRules -> assetAndRules.key != null).collect(Collectors.groupingBy(assetAndRules -> assetAndRules.key.getRealmId()))@@ -528,7 +552,8 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseassetStorageService,assetProcessingService,notificationService,- new RulesEngineId<>(ruleset.getRealmId(), assetId)+ new RulesEngineId<>(ruleset.getRealmId(), assetId),+ this::onEngineLocationRulesChanged);});@@ -665,10 +690,116 @@ public class RulesService extends RouteBuilder implements ContainerService, Assereturn assets.stream().map((ServerAsset asset) ->- new Pair<>(asset, asset.getAttributesStream().filter(AssetAttribute::isRuleState))+ new Pair<>(asset, asset.getAttributesStream().filter(AssetAttribute::isRuleState)));}+ /**+ * Called when an engine's rules change identifying assets with location attributes marked with {@link+ * AssetMeta#RULE_STATE} that also have {@link BaseAssetQuery.LocationPredicate} in the rules. The job here is to+ * identify the asset's (via {@link AssetState}) that have modified {@link BaseAssetQuery.LocationPredicate}s and to+ * notify the {@link GeofenceAssetAdapter}s.+ */+ protected void onEngineLocationRulesChanged(RulesEngine rulesEngine, Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> newAssetStateLocationPredicateMap) {+ withLock(getClass().getSimpleName() + "::onEngineLocationRulesChanged", () -> {+ int initialModifiedCount = modifiedAssetLocationPredicates.size();++ if (newAssetStateLocationPredicateMap == null) {+ engineAssetLocationPredicateMap.computeIfPresent(rulesEngine,+ (re, existingAssetStateLocationPredicateMap) -> {+ // All location predicates have been removed so record each asset state as modified+ modifiedAssetLocationPredicates.addAll(+ existingAssetStateLocationPredicateMap.keySet());+ // Remove this engine from the map+ return null;+ });+ } else {+ engineAssetLocationPredicateMap.compute(rulesEngine, (re, existingAssetStateLocationPredicateMap) -> {+ // Check if this not the first time this engine has been seen with location predicates so we can check+ // for any removed asset states+ if (existingAssetStateLocationPredicateMap == null) {+ // All asset states are new so record them all as modified+ modifiedAssetLocationPredicates.addAll(newAssetStateLocationPredicateMap.keySet());+ } else {+ // Find obsolete and modified asset states+ existingAssetStateLocationPredicateMap.forEach((existingAssetState, existingLocationPredicates) -> {+ // Check if there are no longer any location predicates for this asset+ newAssetStateLocationPredicateMap.compute(existingAssetState,+ (as, newLocationPredicates) -> {+ if (newLocationPredicates == null) {+ // This means that there are no longer any location predicates so old ones are obsolete+ modifiedAssetLocationPredicates.add(+ existingAssetState);+ } else {+ // Compare existing and new location predicate sets if there is any change then record it+ if (!newLocationPredicates.equals(+ existingLocationPredicates)) {+ modifiedAssetLocationPredicates.add(+ existingAssetState);+ }+ }+ return newLocationPredicates;+ });+ });+ // Check for asset states in the new map but not in the old one+ newAssetStateLocationPredicateMap.forEach((newAssetState, newLocationPredicates) -> existingAssetStateLocationPredicateMap.computeIfAbsent(+ newAssetState,+ as -> {+ // This means that all predicates for this asset are new+ modifiedAssetLocationPredicates.add(newAssetState);+ return null;+ }));+ }+ return newAssetStateLocationPredicateMap;+ });+ }++ if (modifiedAssetLocationPredicates.size() != initialModifiedCount) {+ if (scheduledGeofenceProcessor != null) {+ scheduledGeofenceProcessor.cancel(false);+ }+ scheduledGeofenceProcessor = executorService.schedule(this::processModifiedGeofences,+ GEOFENCE_PROCESSING_DEBOUNCE_MILLIS);+ }+ });+ }++ protected void processModifiedGeofences() {+ withLock(getClass().getSimpleName() + "::processModifiedGeofences", () -> {+ boolean isFirstRun = firstGeofenceProcessorRun;+ firstGeofenceProcessorRun = false;++ // Find all location predicates associated with modified asset states and pass through to geofence adapters+ Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> assetLocationPredicateMap = new HashMap<>(+ modifiedAssetLocationPredicates.size());++ modifiedAssetLocationPredicates.forEach(assetState -> {+ Set<BaseAssetQuery.LocationPredicate> locationPredicates = new HashSet<>();+ engineAssetLocationPredicateMap.forEach((rulesEngine, assetStateSetMap) ->+ assetStateSetMap.computeIfPresent(assetState,+ (as, engineLocationPredicates) -> {+ locationPredicates.addAll(+ engineLocationPredicates);+ return engineLocationPredicates;+ }));++ assetLocationPredicateMap.put(assetState, locationPredicates);+ });++ // Clear modified assets ready for next batch+ modifiedAssetLocationPredicates.clear();+ scheduledGeofenceProcessor = null;++ Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> unmodifiableAssetStateLocationPredicateMap =+ Collections.unmodifiableMap(assetLocationPredicateMap);++ LOG.info("Processing asset geofence updates: asset count=" + assetLocationPredicateMap.size());+ for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {+ geofenceAssetAdapter.processLocationPredicates(unmodifiableAssetStateLocationPredicateMap, isFirstRun);+ }+ });+ }+@Overridepublic String toString() {return getClass().getSimpleName() + "{}";diff --git a/manager/src/main/java/org/openremote/manager/rules/geofence/GeofenceAssetAdapter.java b/manager/src/main/java/org/openremote/manager/rules/geofence/GeofenceAssetAdapter.javanew file mode 100644index 000000000..d267db8e8--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/rules/geofence/GeofenceAssetAdapter.java@@ -0,0 +1,72 @@+/*+ * 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.manager.rules.geofence;++import org.openremote.container.ContainerService;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.BaseAssetQuery;+import org.openremote.model.rules.AssetState;++import java.util.Map;+import java.util.Set;++/**+ * Defines an adapter that can take a collection of {@link BaseAssetQuery.LocationPredicate} that apply to a given+ * {@link Asset} and can convert the {@link BaseAssetQuery.LocationPredicate}s into Geofences that can be implemented by+ * the asset(s) itself.+ * <p>+ * The adapter is notified when the {@link BaseAssetQuery.LocationPredicate}s {@link Asset} map changes; if a map entry+ * contains a null or empty collection of {@link BaseAssetQuery.LocationPredicate}s then it means that there are no+ * longer any associated with that {@link Asset} so the adapter should clear any that already exist on that {@link+ * Asset}, it is the adapters job to maintain state if required (see initialising flag on {@link+ * #processLocationPredicates}).+ * <p>+ * When an adapter consumes a {@link BaseAssetQuery.LocationPredicate} for an {@link Asset} then it should remove that+ * value from the collection (the map entry cannot be removed so adapters must only modify the entry collection value).+ * This means that the next adapter won't be able to consume the same {@link BaseAssetQuery.LocationPredicate}.+ * <p>+ * How the gefences are implemented and 'pushed' to the {@link Asset}s is up to the adapter but when a geofence is+ * triggered on an asset then the asset should update its own location by posting to the asset/location endpoint, the+ * location value sent should be as follows:+ * <ul>+ * <li>Geofence Enter - Send geofence centre point as location (centre point should have been provided in the geofence+ * definition retrieved from the backend)</li>+ * <li>Geofence Exit - Send null (this will clear the devices location and indicate that the asset has left the+ * geofence)</li>+ * </ul>+ */+public interface GeofenceAssetAdapter extends ContainerService {++ /**+ * An integer indicating where this adapter should be placed in the adapter chain; adapters are ordered by priority+ * so a higher priority means the adapter will be called sooner (i.e. it will have a chance to consume {@link+ * BaseAssetQuery.LocationPredicate}s before adapters with a lower priority).+ */+ int getPriority();++ /**+ * The initialising flag is used to indicate that the system is just initialising and the adapter is being made+ * aware of existing {@link BaseAssetQuery.LocationPredicate}s; generally adapters should use this to initialise+ * their own state rather than 'pushing' geofences to the asset(s) it can be assumed that they were previously sent,+ * hence adapters should be more concerned with delta changes (but this is really up to the adapter).+ */+ void processLocationPredicates(Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> assetLocationPredicateMap,+ boolean initialising);+}diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.javaindex f423798a8..cf7038300 100644--- a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java@@ -53,10 +53,11 @@ public class ManagerDemoSetup extends AbstractManagerSetup {public static final int DEMO_RULE_STATES_APARTMENT_1 = 37;public static final int DEMO_RULE_STATES_APARTMENT_2 = 11;public static final int DEMO_RULE_STATES_APARTMENT_3 = 0;+ public static final int DEMO_RULE_STATES_SMART_OFFICE = 1;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;- public static final int DEMO_RULE_STATES_GLOBAL = DEMO_RULE_STATES_CUSTOMER_A;+ public static final int DEMO_RULE_STATES_GLOBAL = DEMO_RULE_STATES_CUSTOMER_A + DEMO_RULE_STATES_SMART_OFFICE;public static final int DEMO_RULE_STATES_APARTMENT_1_WITH_SCENES = DEMO_RULE_STATES_APARTMENT_1 + 28;public static final int DEMO_RULE_STATES_SMART_HOME_WITH_SCENES = DEMO_RULE_STATES_APARTMENT_1_WITH_SCENES + DEMO_RULE_STATES_APARTMENT_2 + DEMO_RULE_STATES_APARTMENT_3;@@ -140,6 +141,10 @@ public class ManagerDemoSetup extends AbstractManagerSetup {ServerAsset lobby = new ServerAsset("Lobby", ROOM, groundFloor);lobby.setLocation(groundFloor.getLocation());+ lobby.addAttributes(+ new AssetAttribute("location", AttributeType.ARRAY)+ );+lobby = assetStorageService.merge(lobby);lobbyId = lobby.getId();@@ -242,7 +247,9 @@ public class ManagerDemoSetup extends AbstractManagerSetup {new MetaItem(STORE_DATA_POINTS, Values.create(true)))- )+ ),+ new AssetAttribute("location", ARRAY)+ .setMeta(new MetaItem(RULE_STATE)));thing = assetStorageService.merge(thing);thingId = thing.getId();diff --git a/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java b/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.javaindex 671dc0add..d874ad169 100644--- a/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java+++ b/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java@@ -29,6 +29,7 @@ import org.openremote.model.value.*;import java.util.Arrays;import java.util.Locale;+import java.util.Objects;/*** Encapsulate asset query restriction, projection, and ordering of results.@@ -872,19 +873,23 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {}@JsonSubTypes({- @JsonSubTypes.Type(value = RadialLocationPredicate.class, name = "radial"),- @JsonSubTypes.Type(value = RectangularLocationPredicate.class, name = "rect")+ @JsonSubTypes.Type(value = RadialLocationPredicate.class, name = RadialLocationPredicate.name),+ @JsonSubTypes.Type(value = RectangularLocationPredicate.class, name = RectangularLocationPredicate.name)})@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,include = JsonTypeInfo.As.PROPERTY,property = "predicateType")- public static class LocationPredicate {++ public abstract static class LocationPredicate {+ // TODO: switch return type to location object+ public abstract double[] getCentrePoint();}public static class RadialLocationPredicate extends LocationPredicate {+ public static final String name = "radial";public boolean negated;public int radius;public double lat;@@ -911,10 +916,32 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {negated = true;return this;}++ @Override+ public boolean equals(Object o) {+ if (this == o) return true;+ if (o == null || getClass() != o.getClass()) return false;+ RadialLocationPredicate that = (RadialLocationPredicate) o;+ return negated == that.negated &&+ radius == that.radius &&+ Double.compare(that.lat, lat) == 0 &&+ Double.compare(that.lng, lng) == 0;+ }++ @Override+ public int hashCode() {+ return Objects.hash(name, negated, radius, lat, lng);+ }++ @Override+ public double[] getCentrePoint() {+ return new double[] {lng, lat};+ }}public static class RectangularLocationPredicate extends LocationPredicate {+ public static final String name = "rect";public boolean negated;public double latMin;public double lngMin;@@ -945,6 +972,30 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {negated = true;return this;}++ @Override+ public boolean equals(Object o) {+ if (this == o) return true;+ if (o == null || getClass() != o.getClass()) return false;+ RectangularLocationPredicate that = (RectangularLocationPredicate) o;+ return negated == that.negated &&+ Double.compare(that.latMin, latMin) == 0 &&+ Double.compare(that.lngMin, lngMin) == 0 &&+ Double.compare(that.latMax, latMax) == 0 &&+ Double.compare(that.lngMax, lngMax) == 0;+ }++ @Override+ public int hashCode() {+ return Objects.hash(name, negated, latMin, lngMin, latMax, lngMax);+ }++ @Override+ public double[] getCentrePoint() {+ double x = (lngMin+lngMax)/2;+ double y = (latMin+latMax)/2;+ return new double[] {x,y};+ }}public static class OrderBy {diff --git a/model/src/main/java/org/openremote/model/rules/AssetQueryPredicate.java b/model/src/main/java/org/openremote/model/rules/AssetQueryPredicate.javaindex 415e4798d..f93b001e1 100644--- a/model/src/main/java/org/openremote/model/rules/AssetQueryPredicate.java+++ b/model/src/main/java/org/openremote/model/rules/AssetQueryPredicate.java@@ -85,6 +85,18 @@ public class AssetQueryPredicate implements Predicate<AssetState> {throw new UnsupportedOperationException("Sorting with 'orderBy' not supported in rules matching");}+ if (query.location != null) {+ // Cannot use JTS libraries here without moving this class into manager module+ // TODO: decide whether to use JTS lib or do simple approx calcs (e.g. (x - center_x)^2 + (y - center_y)^2 < radius^2)+ if (query.location instanceof RadialLocationPredicate) {+ RadialLocationPredicate radialLocationPredicate = (RadialLocationPredicate)query.location;+ return false;+ } else if (query.location instanceof RectangularLocationPredicate) {+ return false;+ }+ throw new UnsupportedOperationException("Location predicate '" + query.location.getClass().getSimpleName() + "' not supported in rules matching");+ }+return true;}diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovyindex 115f89cbe..bb33e42f5 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy@@ -66,7 +66,8 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainerconditions.eventually {assert rulesService.globalEngine != nullassert rulesService.globalEngine.isRunning()- assert rulesService.globalEngine.deployments.size() == 2+ assert rulesService.globalEngine.deployments.size() == 3+ assert rulesService.globalEngine.deployments.values().any({ it.name == "Location predicate demo rules" && it.status == DEPLOYED})assert rulesService.globalEngine.deployments.values().any({ it.name == "Some global demo rules" && it.status == DEPLOYED})assert rulesService.globalEngine.deployments.values().any({ it.name == "Some more global rules" && it.status == DEPLOYED})}@@ -163,10 +164,11 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainerthen: "the global rules engine should not run and the rule engine status should indicate the issue"conditions.eventually {- assert rulesService.globalEngine.deployments.size() == 3+ assert rulesService.globalEngine.deployments.size() == 4assert rulesService.globalEngine.running == falseassert rulesService.globalEngine.isError()assert rulesService.globalEngine.error instanceof RuntimeException+ assert rulesService.globalEngine.deployments.values().any({ it.name == "Location predicate demo rules" && it.status == READY})assert rulesService.globalEngine.deployments.values().any({ it.name == "Some global demo rules" && it.status == READY})assert rulesService.globalEngine.deployments.values().any({ it.name == "Some more global rules" && it.status == READY})assert rulesService.globalEngine.deployments.values().any({ it.name == "Some broken global rules" && it.status == COMPILATION_ERROR})@@ -177,9 +179,10 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainerthen: "the global rules engine should restart"conditions.eventually {- assert rulesService.globalEngine.deployments.size() == 2+ assert rulesService.globalEngine.deployments.size() == 3assert rulesService.globalEngine.running == trueassert rulesService.globalEngine.isError() == false+ assert rulesService.globalEngine.deployments.values().any({ it.name == "Location predicate demo rules" && it.status == DEPLOYED})assert rulesService.globalEngine.deployments.values().any({ it.name == "Some global demo rules" && it.status == DEPLOYED })assert rulesService.globalEngine.deployments.values().any({ it.name == "Some more global rules" && it.status == DEPLOYED })}diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovyindex 6b3122417..5410c2009 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy@@ -17,6 +17,7 @@ class BasicRulesImport {final Long globalRulesetIdfinal Long globalRuleset2Id+ final Long globalRuleset3Idfinal Long masterRulesetIdfinal Long customerARulesetIdfinal Long customerBRulesetId@@ -50,6 +51,13 @@ class BasicRulesImport {ruleset.setEnabled(false)globalRuleset2Id = rulesetStorageService.merge(ruleset).id+ ruleset = new GlobalRuleset(+ "Location predicate demo rules",+ getClass().getResource("/org/openremote/test/rules/BasicLocationPredicate.groovy").text,+ GROOVY+ )+ globalRuleset3Id = rulesetStorageService.merge(ruleset).id+ruleset = new TenantRuleset("Some master tenant demo rules",keycloakDemoSetup.masterTenant.id,@@ -109,10 +117,9 @@ class BasicRulesImport {globalEngine.disableTemporaryFactExpiration = trueassert globalEngine != nullassert globalEngine.isRunning()- assert globalEngine != null- assert globalEngine.isRunning()- assert globalEngine.deployments.size() == 1+ assert globalEngine.deployments.size() == 2assert globalEngine.deployments.values().any { it -> it.name == "Some global demo rules" && it.status == DEPLOYED }+ assert globalEngine.deployments.values().any { it -> it.name == "Location predicate demo rules" && it.status == DEPLOYED }assert rulesService.tenantEngines.size() == 2masterEngine = rulesService.tenantEngines.get(keycloakDemoSetup.masterTenant.id)diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovyindex 03420a259..528d6af5b 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy@@ -1,22 +1,27 @@package org.openremote.test.rules+import org.openremote.container.Containerimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.asset.ServerAssetimport org.openremote.manager.rules.RulesEngineimport org.openremote.manager.rules.RulesServiceimport org.openremote.manager.rules.RulesetStorageService+import org.openremote.manager.rules.geofence.GeofenceAssetAdapterimport org.openremote.manager.setup.SetupServiceimport org.openremote.manager.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.setup.builtin.ManagerDemoSetupimport org.openremote.model.asset.AssetAttributeimport org.openremote.model.asset.AssetMetaimport org.openremote.model.asset.AssetType+import org.openremote.model.asset.BaseAssetQueryimport org.openremote.model.attribute.AttributeEventimport org.openremote.model.attribute.AttributeTypeimport org.openremote.model.attribute.Metaimport org.openremote.model.attribute.MetaItemimport org.openremote.model.rules.AssetRuleset+import org.openremote.model.rules.AssetState+import org.openremote.model.rules.GlobalRulesetimport org.openremote.model.rules.Rulesetimport org.openremote.model.rules.TenantRulesetimport org.openremote.model.value.Values@@ -55,7 +60,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerconditions.eventually {assert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBALassert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL- assert rulesImport.masterEngine.assetStates.size() == 0+ assert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICEassert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_Aassert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3@@ -121,7 +126,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerconditions.eventually {assert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBALassert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL- assert rulesImport.masterEngine.assetStates.size() == 0+ assert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICEassert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_Aassert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3@@ -226,12 +231,14 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerconditions.eventually {assert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBAL + 1assert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL + 1- assert rulesImport.masterEngine.assetStates.size() == 0+ assert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICEassert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A + 1assert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2 + 1assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3assertRulesFired(rulesImport.globalEngine, 1)assertRulesFired(rulesImport.globalEngine, ["All"])+ assertRulesFired(rulesImport.masterEngine, 1)+ assertRulesFired(rulesImport.masterEngine, ["All"])assertRulesFired(rulesImport.customerAEngine, 1)assertRulesFired(rulesImport.customerAEngine, ["All"])assertRulesFired(rulesImport.apartment2Engine, 1)@@ -255,7 +262,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainernew PollingConditions(initialDelay: 3).eventually {assert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBAL + 1assert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL + 1- assert rulesImport.masterEngine.assetStates.size() == 0+ assert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICEassert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A + 1assert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2 + 1assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3@@ -281,7 +288,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerconditions.eventually {assert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBALassert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL- assert rulesImport.masterEngine.assetStates.size() == 0+ assert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICEassert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_Aassert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3@@ -313,7 +320,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerconditions.eventually {assert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBAL + 2assert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL + 2- assert rulesImport.masterEngine.assetStates.size() == 0+ assert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICEassert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A + 2assert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2 + 2assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3@@ -334,7 +341,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerconditions.eventually {assert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBALassert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL- assert rulesImport.masterEngine.assetStates.size() == 0+ assert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICEassert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_Aassert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3@@ -410,4 +417,173 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainercleanup: "the server should be stopped"stopContainer(container)}++ def "Check tracking of location predicate rules"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 10, initialDelay: 0.5, delay: 0.5)++ and: "a mock geofence adapter"+ Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> geofenceChangeMap = null+ def geofenceInit = false;+ def testGeofenceAdapter = new GeofenceAssetAdapter() {++ @Override+ int getPriority() {+ return Integer.MAX_VALUE+ }++ @Override+ void processLocationPredicates(Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> assetLocationPredicateMap, boolean initialising) {+ geofenceChangeMap = assetLocationPredicateMap+ geofenceInit = initialising+ }++ @Override+ void init(Container container) throws Exception {++ }++ @Override+ void start(Container container) throws Exception {++ }++ @Override+ void stop(Container container) throws Exception {++ }+ }++ and: "the container is started"+ def serverPort = findEphemeralPort()+ RulesService.GEOFENCE_PROCESSING_DEBOUNCE_MILLIS = 50+ def container = startContainer(defaultConfig(serverPort), defaultServices(testGeofenceAdapter))+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)+ def rulesService = container.getService(RulesService.class)+ def rulesetStorageService = container.getService(RulesetStorageService.class)+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)++ and: "some test rulesets have been imported"+ def rulesImport = new BasicRulesImport(rulesetStorageService, keycloakDemoSetup, managerDemoSetup)++ expect: "the rules engines to be ready"+ conditions.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() == DEMO_RULE_STATES_GLOBAL+ assert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL+ assert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICE+ assert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A+ assert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2+ assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3+ }++ and: "the mock geofence adapter should have been initialised with the demo thing assets location predicate"+ conditions.eventually {+ assert geofenceChangeMap != null+ assert geofenceInit+ assert geofenceChangeMap.size() == 1+ def thingGeofences = geofenceChangeMap.find({ it.key.id == managerDemoSetup.thingId }).value+ assert thingGeofences.size() == 1+ BaseAssetQuery.RadialLocationPredicate locPredicate = thingGeofences.find { it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 100 && it.centrePoint[1] == 50 && it.radius == 100 }+ assert locPredicate != null+ }++ when: "another asset's location attribute is marked as RULE_STATE"+ def lobby = assetStorageService.find(managerDemoSetup.lobbyId, true)+ lobby.getAttribute("location").get().addMeta(new MetaItem(AssetMeta.RULE_STATE))+ lobby = assetStorageService.merge(lobby)++ then: "the mock geofence adapter should be notified of the new lobby asset with a location predicate"+ conditions.eventually {+ assert geofenceChangeMap != null+ assert !geofenceInit+ assert geofenceChangeMap.size() == 1+ def lobbyGeofences = geofenceChangeMap.find({ it.key.id == managerDemoSetup.lobbyId }).value+ assert lobbyGeofences.size() == 1+ BaseAssetQuery.RadialLocationPredicate locPredicate = lobbyGeofences.find { it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 100 && it.centrePoint[1] == 50 && it.radius == 100 }+ assert locPredicate != null+ }++ when: "a new ruleset is deployed with multiple location predicate rules on the lobby asset"+ def lobbyRuleset = new AssetRuleset(+ "Lobby location predicates",+ managerDemoSetup.lobbyId,+ getClass().getResource("/org/openremote/test/rules/BasicLocationPredicate2.groovy").text,+ Ruleset.Lang.GROOVY+ )+ rulesetStorageService.merge(lobbyRuleset)+ RulesEngine lobbyEngine = null++ then: "the new rule engine should be created and be running"+ conditions.eventually {+ lobbyEngine = rulesService.assetEngines.get(managerDemoSetup.lobbyId)+ assert lobbyEngine != null+ assert lobbyEngine.isRunning()+ assert lobbyEngine.deployments.size() == 1+ assert lobbyEngine.deployments.values().any({+ it.name == "Lobby location predicates" && it.status == DEPLOYED+ })+ }++ then: "the mock geofence adapter should have been notified of the new location predicates for the demo thing and lobby assets"+ conditions.eventually {+ assert geofenceChangeMap != null+ assert !geofenceInit+ assert geofenceChangeMap.size() == 2+ Set<BaseAssetQuery.LocationPredicate> thingGeofences = geofenceChangeMap.find{ it.key.id == managerDemoSetup.thingId }.value+ assert thingGeofences.size() == 3+ BaseAssetQuery.RadialLocationPredicate rad1Predicate = thingGeofences.find { it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 100 && it.centrePoint[1] == 50 && it.radius == 100 }+ BaseAssetQuery.RadialLocationPredicate rad2Predicate = thingGeofences.find { it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 50 && it.centrePoint[1] == 0 && it.radius == 200 }+ BaseAssetQuery.RectangularLocationPredicate rect1Predicate = thingGeofences.find { it instanceof BaseAssetQuery.RectangularLocationPredicate && it.centrePoint[0] == 75 && it.centrePoint[1] == 25 && it.lngMax == 100 && it.latMax == 50 }+ assert rad1Predicate != null+ assert rad2Predicate != null+ assert rect1Predicate != null+ def lobbyGeofences = geofenceChangeMap.find({ it.key.id == managerDemoSetup.lobbyId }).value+ assert lobbyGeofences.size() == 3+ assert lobbyGeofences.any { it == rad1Predicate }+ assert lobbyGeofences.any { it == rad2Predicate }+ assert lobbyGeofences.any { it == rect1Predicate }+ }++ when: "a location predicate ruleset is removed"+ rulesetStorageService.delete(GlobalRuleset.class, rulesImport.globalRuleset3Id)++ then: "the mock geofence adapter should be notified that the demo thing and lobby asset's rules with location predicates have changed"+ conditions.eventually {+ assert geofenceChangeMap != null+ assert geofenceChangeMap.size() == 2+ Set<BaseAssetQuery.LocationPredicate> thingGeofences = geofenceChangeMap.find{ it.key.id == managerDemoSetup.thingId }.value+ assert thingGeofences.size() == 2+ BaseAssetQuery.RadialLocationPredicate rad2Predicate = thingGeofences.find { it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 50 && it.centrePoint[1] == 0 && it.radius == 200 }+ BaseAssetQuery.RectangularLocationPredicate rect1Predicate = thingGeofences.find { it instanceof BaseAssetQuery.RectangularLocationPredicate && it.centrePoint[0] == 75 && it.centrePoint[1] == 25 && it.lngMax == 100 && it.latMax == 50 }+ assert rad2Predicate != null+ assert rect1Predicate != null+ def lobbyGeofences = geofenceChangeMap.find({ it.key.id == managerDemoSetup.lobbyId }).value+ assert lobbyGeofences.size() == 2+ assert lobbyGeofences.any { it == rad2Predicate }+ assert lobbyGeofences.any { it == rect1Predicate }+ }++ when: "the RULE_STATE meta is removed from the lobby asset's location attribute"+ lobby.getAttribute("location").get().getMeta().removeIf({ it.name.orElse(null) == AssetMeta.RULE_STATE.urn })+ lobby = assetStorageService.merge(lobby)++ then: "the mock geofence adapter should be notified that the lobby asset no longer has any rules with location predicates"+ conditions.eventually {+ assert geofenceChangeMap != null+ assert !geofenceInit+ assert geofenceChangeMap.size() == 1+ def lobbyGeofences = geofenceChangeMap.find({ it.key.id == managerDemoSetup.lobbyId }).value+ assert lobbyGeofences.size() == 0+ }++ cleanup: "the server should be stopped"+ stopContainer(container)+ }}diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovyindex c52b5d440..f79f331ec 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy@@ -58,7 +58,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainerdef ruleDefinitions = rulesetResource.getGlobalRulesets(null)then: "result should match"- ruleDefinitions.length == 2+ ruleDefinitions.length == 3ruleDefinitions[0].name == "Some global demo rules"ruleDefinitions[0].lang == GROOVYruleDefinitions[0].rules == null // Don't retrieve the (large) rules data when getting a list of rule definitions@@ -92,7 +92,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainerwhen: "global ruleset is created"def globalRuleset = new GlobalRuleset("Test global definition", "SomeRulesCode", GROOVY)rulesetResource.createGlobalRuleset(null, globalRuleset)- def rulesetId = rulesetResource.getGlobalRulesets(null)[2].id+ def rulesetId = rulesetResource.getGlobalRulesets(null)[3].idglobalRuleset = rulesetResource.getGlobalRuleset(null, rulesetId)def lastModified = globalRuleset.lastModifieddiff --git a/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicate.groovy b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicate.groovynew file mode 100644index 000000000..7a004d364--- /dev/null+++ b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicate.groovy@@ -0,0 +1,19 @@+package org.openremote.test.rules++import org.openremote.manager.rules.RulesBuilder+import org.openremote.model.asset.AssetQuery+import org.openremote.model.asset.BaseAssetQuery++RulesBuilder rules = binding.rules++rules.add()+ .name("Location predicate")+ .when(+ { facts ->+ facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RadialLocationPredicate(100, 50, 100))).isPresent() &&+ !facts.matchFirst("Location").isPresent()+ })+ .then(+ { facts ->+ facts.put("Location", "fired")+ })diff --git a/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicate2.groovy b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicate2.groovynew file mode 100644index 000000000..4545c5720--- /dev/null+++ b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicate2.groovy@@ -0,0 +1,31 @@+package org.openremote.test.rules++import org.openremote.manager.rules.RulesBuilder+import org.openremote.model.asset.AssetQuery+import org.openremote.model.asset.BaseAssetQuery++RulesBuilder rules = binding.rules++rules.add()+ .name("Radial location predicate")+ .when(+ { facts ->+ facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RadialLocationPredicate(200, 0, 50))).isPresent() &&+ !facts.matchFirst("RadialLocation").isPresent()+ })+ .then(+ { facts ->+ facts.put("RadialLocation", "fired")+ })++rules.add()+ .name("Rectangular location predicate")+ .when(+ { facts ->+ facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RectangularLocationPredicate(0, 50, 50, 100))).isPresent() &&+ !facts.matchFirst("RectLocation").isPresent()+ })+ .then(+ { facts ->+ facts.put("RectLocation", "fired")+ })