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
Cleanup of location predicate tracking
Rich Turnerf34cb2dae662
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.javaindex fccf38c64..3e5dd38d3 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java@@ -29,6 +29,7 @@ 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.Asset;import org.openremote.model.asset.AssetMeta;import org.openremote.model.asset.BaseAssetQuery;import org.openremote.model.rules.*;@@ -45,6 +46,28 @@ import static org.openremote.manager.rules.RulesetDeployment.Status.*;public class RulesEngine<T extends Ruleset> {+ /**+ * Identifies a set of {@link BaseAssetQuery.LocationPredicate}s associated with a particular {@link Asset}+ */+ public static final class AssetStateLocationPredicates {++ protected final AssetState assetState;+ protected final Set<BaseAssetQuery.LocationPredicate> locationPredicates;++ public AssetStateLocationPredicates(AssetState assetState, Set<BaseAssetQuery.LocationPredicate> locationPredicates) {+ this.assetState = assetState;+ this.locationPredicates = locationPredicates;+ }++ public AssetState getAssetState() {+ return assetState;+ }++ public Set<BaseAssetQuery.LocationPredicate> getLocationPredicates() {+ return locationPredicates;+ }+ }+public static final Logger LOG = Logger.getLogger(RulesEngine.class.getName());// Separate logger for execution of rules@@ -60,7 +83,7 @@ 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 BiConsumer<RulesEngine, List<AssetStateLocationPredicates>> assetLocationPredicatesConsumer;final protected Map<Long, RulesetDeployment> deployments = new LinkedHashMap<>();final protected RulesFacts facts;@@ -84,14 +107,15 @@ public class RulesEngine<T extends Ruleset> {AssetProcessingService assetProcessingService,NotificationService notificationService,RulesEngineId<T> id,- BiConsumer<RulesEngine, Map<AssetState, Set<BaseAssetQuery.LocationPredicate>>> assetLocationPredicateMapConsumer) {+ // Change to a class+ BiConsumer<RulesEngine, List<AssetStateLocationPredicates>> assetLocationPredicatesConsumer) {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.assetLocationPredicatesConsumer = assetLocationPredicatesConsumer;this.facts = new RulesFacts(assetsFacade, this, RULES_LOG);engine = new InferenceRulesEngine(@@ -305,7 +329,7 @@ public class RulesEngine<T extends Ruleset> {return;}- if (trackLocationPredicates && assetLocationPredicateMapConsumer != null) {+ if (trackLocationPredicates && assetLocationPredicatesConsumer != null) {facts.startTrackingLocationRules();}@@ -353,7 +377,7 @@ public class RulesEngine<T extends Ruleset> {if (trackLocationPredicates) {trackLocationPredicates = false;- if (assetLocationPredicateMapConsumer != null) {+ if (assetLocationPredicatesConsumer != null) {processLocationRules(facts.stopTrackingLocationRules());}}@@ -378,8 +402,8 @@ public class RulesEngine<T extends Ruleset> {}running = false;- if (!systemShutdownInProgress && assetLocationPredicateMapConsumer != null) {- assetLocationPredicateMapConsumer.accept(this, null);+ if (!systemShutdownInProgress && assetLocationPredicatesConsumer != null) {+ assetLocationPredicatesConsumer.accept(this, null);}}@@ -437,9 +461,9 @@ 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);+ protected void processLocationRules(List<AssetStateLocationPredicates> assetStateLocationPredicates) {+ if (assetLocationPredicatesConsumer != null) {+ assetLocationPredicatesConsumer.accept(this, assetStateLocationPredicates);}}diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.javaindex d9930e700..04d881281 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java@@ -26,7 +26,6 @@ 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;import org.openremote.model.rules.AssetState;import org.openremote.model.rules.Assets;import org.openremote.model.rules.TemporaryFact;@@ -84,11 +83,15 @@ public class RulesFacts extends Facts implements RuleListener {trackLocationRules = true;}- protected Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> stopTrackingLocationRules() {+ protected List<RulesEngine.AssetStateLocationPredicates> stopTrackingLocationRules() {trackLocationRules = false;Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> assetStateLocationPredicateMap = this.assetStateLocationPredicateMap;this.assetStateLocationPredicateMap = null;- return assetStateLocationPredicateMap;+ return assetStateLocationPredicateMap.entrySet().stream()+ .map(assetStateSetEntry ->+ new RulesEngine.AssetStateLocationPredicates(+ assetStateSetEntry.getKey(),+ assetStateSetEntry.getValue())).collect(Collectors.toList());}public void setClock(RulesClock clock) {diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.javaindex 6f993f6f0..74ae9d704 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java@@ -101,8 +101,8 @@ public class RulesService extends RouteBuilder implements ContainerService, Asseprotected 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 BiConsumer<RulesEngine, List<RulesEngine.AssetStateLocationPredicates>> locationPredicateRulesConsumer;+ protected Map<RulesEngine, List<RulesEngine.AssetStateLocationPredicates>> engineAssetLocationPredicateMap = new HashMap<>();protected Set<AssetState> modifiedAssetLocationPredicates = new HashSet<>();protected ScheduledFuture scheduledGeofenceProcessor;protected boolean firstGeofenceProcessorRun = true;@@ -700,57 +700,64 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse* 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) {+ protected void onEngineLocationRulesChanged(RulesEngine rulesEngine, List<RulesEngine.AssetStateLocationPredicates> newEngineAssetStateLocationPredicates) {withLock(getClass().getSimpleName() + "::onEngineLocationRulesChanged", () -> {int initialModifiedCount = modifiedAssetLocationPredicates.size();- if (newAssetStateLocationPredicateMap == null) {+ if (newEngineAssetStateLocationPredicates == null) {engineAssetLocationPredicateMap.computeIfPresent(rulesEngine,- (re, existingAssetStateLocationPredicateMap) -> {+ (re, existingAssetStateLocationPredicates) -> {// All location predicates have been removed so record each asset state as modifiedmodifiedAssetLocationPredicates.addAll(- existingAssetStateLocationPredicateMap.keySet());+ existingAssetStateLocationPredicates.stream().map(RulesEngine.AssetStateLocationPredicates::getAssetState).collect(Collectors.toList()));// Remove this engine from the mapreturn null;});} else {- engineAssetLocationPredicateMap.compute(rulesEngine, (re, existingAssetStateLocationPredicateMap) -> {+ engineAssetLocationPredicateMap.compute(rulesEngine, (re, existingEngineAssetStateLocationPredicates) -> {// 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) {+ if (existingEngineAssetStateLocationPredicates == null) {// All asset states are new so record them all as modified- modifiedAssetLocationPredicates.addAll(newAssetStateLocationPredicateMap.keySet());+ modifiedAssetLocationPredicates.addAll(newEngineAssetStateLocationPredicates.stream().map(RulesEngine.AssetStateLocationPredicates::getAssetState).collect(Collectors.toList()));} else {// Find obsolete and modified asset states- existingAssetStateLocationPredicateMap.forEach((existingAssetState, existingLocationPredicates) -> {+ existingEngineAssetStateLocationPredicates.forEach(existingAssetStateLocationPredicates -> {// 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;- });+ Optional<RulesEngine.AssetStateLocationPredicates> newAssetStateLocationPredicates = newEngineAssetStateLocationPredicates.stream()+ .filter(assetStateLocationPredicates ->+ assetStateLocationPredicates.assetState.equals(+ existingAssetStateLocationPredicates.getAssetState()))+ .findFirst();++ if (newAssetStateLocationPredicates.isPresent()) {+ // Compare existing and new location predicate sets if there is any change then record it+ if (!newAssetStateLocationPredicates.get().getLocationPredicates().equals(+ existingAssetStateLocationPredicates.getLocationPredicates())) {+ modifiedAssetLocationPredicates.add(+ existingAssetStateLocationPredicates.getAssetState());+ }+ } else {+ // This means that there are no longer any location predicates so old ones are obsolete+ modifiedAssetLocationPredicates.add(+ existingAssetStateLocationPredicates.getAssetState());+ }});+// Check for asset states in the new map but not in the old one- newAssetStateLocationPredicateMap.forEach((newAssetState, newLocationPredicates) -> existingAssetStateLocationPredicateMap.computeIfAbsent(- newAssetState,- as -> {+ newEngineAssetStateLocationPredicates.forEach(newAssetStateLocationPredicates -> {+ boolean isNewAssetState = existingEngineAssetStateLocationPredicates.stream()+ .noneMatch(assetStateLocationPredicates ->+ assetStateLocationPredicates.assetState.equals(+ newAssetStateLocationPredicates.getAssetState()));++ if (isNewAssetState) {// This means that all predicates for this asset are new- modifiedAssetLocationPredicates.add(newAssetState);- return null;- }));+ modifiedAssetLocationPredicates.add(newAssetStateLocationPredicates.getAssetState());+ }+ });}- return newAssetStateLocationPredicateMap;+ return newEngineAssetStateLocationPredicates;});}@@ -770,32 +777,34 @@ public class RulesService extends RouteBuilder implements ContainerService, AssefirstGeofenceProcessorRun = false;// Find all location predicates associated with modified asset states and pass through to geofence adapters- Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> assetLocationPredicateMap = new HashMap<>(+ List<RulesEngine.AssetStateLocationPredicates> assetLocationPredicates = new ArrayList<>(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;+ RulesEngine.AssetStateLocationPredicates locationPredicates = new RulesEngine.AssetStateLocationPredicates(assetState, new HashSet<>());+ engineAssetLocationPredicateMap.forEach((rulesEngine, engineAssetStateLocationPredicates) ->+ engineAssetStateLocationPredicates.stream().filter(assetStateLocationPredicates ->+ assetStateLocationPredicates.assetState.equals(+ assetState))+ .findFirst()+ .ifPresent(assetStateLocationPredicate -> {+ locationPredicates.getLocationPredicates().addAll(+ assetStateLocationPredicate.getLocationPredicates());}));- assetLocationPredicateMap.put(assetState, locationPredicates);+ assetLocationPredicates.add(locationPredicates);});// Clear modified assets ready for next batchmodifiedAssetLocationPredicates.clear();scheduledGeofenceProcessor = null;- Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> unmodifiableAssetStateLocationPredicateMap =- Collections.unmodifiableMap(assetLocationPredicateMap);+ List<RulesEngine.AssetStateLocationPredicates> unmodifiableAssetStateLocationPredicates =+ Collections.unmodifiableList(assetLocationPredicates);- LOG.info("Processing asset geofence updates: asset count=" + assetLocationPredicateMap.size());+ LOG.info("Processing asset geofence updates: asset count=" + assetLocationPredicates.size());for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {- geofenceAssetAdapter.processLocationPredicates(unmodifiableAssetStateLocationPredicateMap, isFirstRun);+ geofenceAssetAdapter.processLocationPredicates(unmodifiableAssetStateLocationPredicates, isFirstRun);}});}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.javaindex d267db8e8..284a971b4 100644--- a/manager/src/main/java/org/openremote/manager/rules/geofence/GeofenceAssetAdapter.java+++ b/manager/src/main/java/org/openremote/manager/rules/geofence/GeofenceAssetAdapter.java@@ -20,10 +20,12 @@package org.openremote.manager.rules.geofence;import org.openremote.container.ContainerService;+import org.openremote.manager.rules.RulesEngine;import org.openremote.model.asset.Asset;import org.openremote.model.asset.BaseAssetQuery;import org.openremote.model.rules.AssetState;+import java.util.List;import java.util.Map;import java.util.Set;@@ -67,6 +69,6 @@ public interface GeofenceAssetAdapter extends ContainerService {* 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,+ void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> assetLocationPredicates,boolean initialising);}diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovyindex 41954804e..f455c9d0d 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy@@ -424,7 +424,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerdef conditions = new PollingConditions(timeout: 10, initialDelay: 0.5, delay: 0.5)and: "a mock geofence adapter"- Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> geofenceChangeMap = null+ List<RulesEngine.AssetStateLocationPredicates> geofenceChanges = nulldef geofenceInit = false;def testGeofenceAdapter = new GeofenceAssetAdapter() {@@ -434,8 +434,8 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer}@Override- void processLocationPredicates(Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> assetLocationPredicateMap, boolean initialising) {- geofenceChangeMap = assetLocationPredicateMap+ void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> assetLocationPredicates, boolean initialising) {+ geofenceChanges = assetLocationPredicatesgeofenceInit = initialising}@@ -486,10 +486,10 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerand: "the mock geofence adapter should have been initialised with the demo thing assets location predicate"conditions.eventually {- assert geofenceChangeMap != null+ assert geofenceChanges != nullassert geofenceInit- assert geofenceChangeMap.size() == 1- def thingGeofences = geofenceChangeMap.find({ it.key.id == managerDemoSetup.thingId }).value+ assert geofenceChanges.size() == 1+ def thingGeofences = geofenceChanges.find({ it.assetState.id == managerDemoSetup.thingId }).locationPredicatesassert thingGeofences.size() == 1BaseAssetQuery.RadialLocationPredicate locPredicate = thingGeofences.find { it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 100 && it.centrePoint[1] == 50 && it.radius == 100 }assert locPredicate != null@@ -502,10 +502,10 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerthen: "the mock geofence adapter should be notified of the new lobby asset with a location predicate"conditions.eventually {- assert geofenceChangeMap != null+ assert geofenceChanges != nullassert !geofenceInit- assert geofenceChangeMap.size() == 1- def lobbyGeofences = geofenceChangeMap.find({ it.key.id == managerDemoSetup.lobbyId }).value+ assert geofenceChanges.size() == 1+ def lobbyGeofences = geofenceChanges.find({ it.assetState.id == managerDemoSetup.lobbyId }).locationPredicatesassert lobbyGeofences.size() == 1BaseAssetQuery.RadialLocationPredicate locPredicate = lobbyGeofences.find { it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 100 && it.centrePoint[1] == 50 && it.radius == 100 }assert locPredicate != null@@ -534,10 +534,10 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerthen: "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 geofenceChanges != nullassert !geofenceInit- assert geofenceChangeMap.size() == 2- Set<BaseAssetQuery.LocationPredicate> thingGeofences = geofenceChangeMap.find{ it.key.id == managerDemoSetup.thingId }.value+ assert geofenceChanges.size() == 2+ Set<BaseAssetQuery.LocationPredicate> thingGeofences = geofenceChanges.find{ it.assetState.id == managerDemoSetup.thingId }.locationPredicatesassert thingGeofences.size() == 3BaseAssetQuery.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 }@@ -545,7 +545,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassert rad1Predicate != nullassert rad2Predicate != nullassert rect1Predicate != null- def lobbyGeofences = geofenceChangeMap.find({ it.key.id == managerDemoSetup.lobbyId }).value+ def lobbyGeofences = geofenceChanges.find({ it.assetState.id == managerDemoSetup.lobbyId }).locationPredicatesassert lobbyGeofences.size() == 3assert lobbyGeofences.any { it == rad1Predicate }assert lobbyGeofences.any { it == rad2Predicate }@@ -557,15 +557,15 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerthen: "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 geofenceChanges != null+ assert geofenceChanges.size() == 2+ Set<BaseAssetQuery.LocationPredicate> thingGeofences = geofenceChanges.find{ it.assetState.id == managerDemoSetup.thingId }.locationPredicatesassert thingGeofences.size() == 2BaseAssetQuery.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 != nullassert rect1Predicate != null- def lobbyGeofences = geofenceChangeMap.find({ it.key.id == managerDemoSetup.lobbyId }).value+ def lobbyGeofences = geofenceChanges.find({ it.assetState.id == managerDemoSetup.lobbyId }).locationPredicatesassert lobbyGeofences.size() == 2assert lobbyGeofences.any { it == rad2Predicate }assert lobbyGeofences.any { it == rect1Predicate }@@ -577,10 +577,10 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerthen: "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 geofenceChanges != nullassert !geofenceInit- assert geofenceChangeMap.size() == 1- def lobbyGeofences = geofenceChangeMap.find({ it.key.id == managerDemoSetup.lobbyId }).value+ assert geofenceChanges.size() == 1+ def lobbyGeofences = geofenceChanges.find({ it.assetState.id == managerDemoSetup.lobbyId }).locationPredicatesassert lobbyGeofences.size() == 0}