Skip to content

armgit / core

Public Imported from GitHub
0

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

Notification and geofence bug fixes

Rich Turnerfccf18d922df
diff --git a/deployment/manager/logging.properties b/deployment/manager/logging.properties
index 5d3ea8537..a62bb2885 100644
--- a/deployment/manager/logging.properties
+++ b/deployment/manager/logging.properties
@@ -16,8 +16,7 @@
###############################################################################
# Log on STDOUT and internal syslog service (monitoring in Manager UI)
-handlers=java.util.logging.ConsoleHandler, \
- org.openremote.manager.syslog.SyslogService
+handlers=java.util.logging.ConsoleHandler,org.openremote.manager.syslog.SyslogService
# Log on STDOUT, to a file, and internal syslog service (monitoring in Manager UI)
#handlers=java.util.logging.ConsoleHandler, \
diff --git a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
index e9c1b9bb4..710efd2f2 100644
--- a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
@@ -51,6 +51,7 @@ import java.nio.file.Paths;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
+import java.util.stream.Collector;
import java.util.stream.Collectors;
import static org.openremote.container.concurrent.GlobalLock.withLock;
@@ -81,12 +82,12 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
String firebaseConfigFilePath = container.getConfig().get(FIREBASE_CONFIG_FILE);
if (TextUtil.isNullOrEmpty(firebaseConfigFilePath)) {
- LOG.info(FIREBASE_CONFIG_FILE + " not defined, can not send FCM notifications");
+ LOG.warning(FIREBASE_CONFIG_FILE + " not defined, can not send FCM notifications");
return;
}
if (!Files.isReadable(Paths.get(firebaseConfigFilePath))) {
- LOG.info(FIREBASE_CONFIG_FILE + " invalid path or file not readable");
+ LOG.warning(FIREBASE_CONFIG_FILE + " invalid path or file not readable");
return;
}
@@ -108,11 +109,15 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
public void start(Container container) throws Exception {
if (!isValid()) {
+ LOG.warning("FCM configuration invalid so cannot start");
return;
}
+ // Not using Collectors.toMap is there is a quirk in there which means null values aren't supported!
+ consoleFCMTokenMap = new HashMap<>();
+
// Find all console assets that use this adapter
- consoleFCMTokenMap = assetStorageService.findAll(
+ assetStorageService.findAll(
new AssetQuery()
.select(new BaseAssetQuery.Select(BaseAssetQuery.Include.ALL_EXCEPT_PATH,
false,
@@ -122,7 +127,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
new ObjectValueKeyPredicate("push")))
.stream()
.filter(PushNotificationHandler::isLinkedToFcmProvider)
- .collect(Collectors.toMap(Asset::getId, asset -> getFcmToken(asset).orElse(null)));
+ .forEach(asset -> consoleFCMTokenMap.put(asset.getId(), getFcmToken(asset).orElse(null)));
}
@Override
@@ -152,10 +157,6 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
@Override
public boolean isMessageValid(AbstractNotificationMessage message) {
- if (!isValid()) {
- LOG.warning("Invalid message: FCM invalid configuration");
- return false;
- }
if (!(message instanceof PushNotificationMessage)) {
LOG.warning("Invalid message: '" + message.getClass().getSimpleName() + "' is not an instance of PushNotificationMessage");
@@ -176,9 +177,9 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
// Check if message is going to a topic if so then filter consoles subscribed to that topic
PushNotificationMessage pushMessage = (PushNotificationMessage) message;
- BaseAssetQuery.Select select = null;
+ BaseAssetQuery.Select select;
boolean forTopic = pushMessage.getTargetType() == TOPIC;
- List<Asset> mappedConsoles = null;
+ List<Asset> mappedConsoles;
if (forTopic) {
select = new BaseAssetQuery.Select(ONLY_ID_AND_NAME_AND_ATTRIBUTES, false, AttributeType.CONSOLE_PROVIDERS.getName());
@@ -272,6 +273,8 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
@Override
public NotificationSendResult sendMessage(long id, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message) {
+ LOG.info("Sending notification '" + id + "' to: " + targetId);
+
if (targetType != Notification.TargetType.ASSET) {
LOG.warning("Target type not supported: " + targetType);
return NotificationSendResult.failure("Target type not supported: " + targetType);
@@ -287,7 +290,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
if (TextUtil.isNullOrEmpty(fcmToken)) {
LOG.warning("No FCM token found for console: " + targetId);
- return NotificationSendResult.failure("FCM invalid configuration so ignoring");
+ return NotificationSendResult.failure("No FCM token found for console: " + targetId);
}
PushNotificationMessage pushMessage = (PushNotificationMessage) message;
@@ -352,11 +355,6 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
}
protected NotificationSendResult sendMessage(Message message) {
- if (!isValid()) {
- LOG.warning("FCM invalid configuration so ignoring");
- return NotificationSendResult.failure("FCM invalid configuration so ignoring");
- }
-
try {
FirebaseMessaging.getInstance().send(message);
return NotificationSendResult.success();
@@ -459,7 +457,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
}
protected static boolean isLinkedToFcmProvider(Asset asset) {
- return ConsoleConfiguration.getConsoleProvider(asset, "geofence")
+ return ConsoleConfiguration.getConsoleProvider(asset, "push")
.map(ConsoleProvider::getVersion).map(FCM_PROVIDER_NAME::equals).orElse(false);
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
index 034a78596..0b96475a8 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
@@ -32,6 +32,7 @@ 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.attribute.AttributeType;
import org.openremote.model.query.filter.LocationPredicate;
import org.openremote.model.rules.*;
@@ -412,7 +413,7 @@ public class RulesEngine<T extends Ruleset> {
public void updateFact(AssetState assetState, boolean fireImmediately) {
facts.putAssetState(assetState);
- trackLocationPredicates = trackLocationPredicates || assetState.getAttributeName().equals("location");
+ trackLocationPredicates = trackLocationPredicates || assetState.getAttributeName().equals(AttributeType.LOCATION.getName());
if (fireImmediately) {
fire();
}
@@ -420,13 +421,13 @@ public class RulesEngine<T extends Ruleset> {
public void removeFact(AssetState assetState) {
facts.removeAssetState(assetState);
- trackLocationPredicates = trackLocationPredicates || assetState.getAttributeName().equals("location");
+ trackLocationPredicates = trackLocationPredicates || assetState.getAttributeName().equals(AttributeType.LOCATION.getName());
fire();
}
public void insertFact(String expires, AssetState assetState) {
facts.insertAssetEvent(expires, assetState);
- trackLocationPredicates = trackLocationPredicates || assetState.getAttributeName().equals("location");
+ trackLocationPredicates = trackLocationPredicates || assetState.getAttributeName().equals(AttributeType.LOCATION.getName());
fire();
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
index b9e92a60c..d2c168c36 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
@@ -22,6 +22,7 @@ package org.openremote.manager.rules;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.api.RuleListener;
+import org.openremote.model.attribute.AttributeType;
import org.openremote.model.query.AssetQuery;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeExecuteStatus;
@@ -434,7 +435,7 @@ public class RulesFacts extends Facts implements RuleListener {
// 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());
+ Collection<AssetState> locationAssetStates = getAssetStates().stream().filter(assetState -> assetState.getAttributeName().equalsIgnoreCase(AttributeType.LOCATION.getName())).collect(Collectors.toSet());
assetStateLocationPredicateMap = new HashMap<>(locationAssetStates.size());
locationAssetStates.forEach(assetState -> assetStateLocationPredicateMap.put(assetState.getId(), new HashSet<>()));
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
index 99adc57c0..53928743c 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
@@ -34,7 +34,9 @@ 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.*;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetMeta;
import org.openremote.model.attribute.AttributeEvent.Source;
import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.filter.AttributeMetaPredicate;
@@ -48,7 +50,6 @@ 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;
@@ -91,7 +92,6 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
public static final String RULE_EVENT_EXPIRES = "RULE_EVENT_EXPIRES";
public static final String RULE_EVENT_EXPIRES_DEFAULT = "1h";
- public static final int GEOFENCE_INIT_DEBOUNCE_MILLIS = 2000;
private static final Logger LOG = Logger.getLogger(RulesService.class.getName());
protected static List<GeofenceAssetAdapter> geofenceAssetAdapters;
@@ -119,13 +119,11 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
protected BiConsumer<RulesEngine, List<RulesEngine.AssetStateLocationPredicates>> locationPredicateRulesConsumer;
protected Map<RulesEngine, List<RulesEngine.AssetStateLocationPredicates>> engineAssetLocationPredicateMap = new HashMap<>();
protected Set<String> assetsWithModifiedLocationPredicates = new HashSet<>();
- 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
protected Set<AssetState> assetStates = new HashSet<>();
protected String configEventExpires;
- protected ScheduledFuture geofenceInitScheduledFuture;
@Override
public void init(Container container) throws Exception {
@@ -142,7 +140,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
// asset persistence changes before the rule engines are updated.
for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {
if (geofenceAssetAdapter instanceof ContainerService) {
- ((ContainerService)geofenceAssetAdapter).init(container);
+ ((ContainerService) geofenceAssetAdapter).init(container);
}
}
@@ -192,7 +190,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {
if (geofenceAssetAdapter instanceof ContainerService) {
- ((ContainerService)geofenceAssetAdapter).start(container);
+ ((ContainerService) geofenceAssetAdapter).start(container);
}
}
}
@@ -205,9 +203,9 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
rulesetStorageService.findEnabledTenantRulesets()
.stream()
.filter(rd ->
- Arrays.stream(activeTenantIds)
- .anyMatch(tenantId -> rd.getRealmId().equals(tenantId))
- ).forEach(this::deployTenantRuleset);
+ Arrays.stream(activeTenantIds)
+ .anyMatch(tenantId -> rd.getRealmId().equals(tenantId))
+ ).forEach(this::deployTenantRuleset);
LOG.info("Deploying asset rulesets");
// Group by asset ID then tenant and check tenant is enabled
@@ -234,7 +232,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {
if (geofenceAssetAdapter instanceof ContainerService) {
try {
- ((ContainerService)geofenceAssetAdapter).stop(container);
+ ((ContainerService) geofenceAssetAdapter).stop(container);
} catch (Exception e) {
LOG.log(SEVERE, "Exception thrown whilst stopping geofence adapter", e);
}
@@ -267,7 +265,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
new AssetState(asset, attribute, source),
false, // Don't skip the error check on the rules engines
!attribute.isRuleEvent() // If it's not a rule event, fire immediately
- );
+ );
}
// Then as asset event (if there wasn't an error), this will also fire the rules engines
@@ -275,7 +273,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
insertAssetEvent(
new AssetState(asset, attribute, source),
attribute.getRuleEventExpires().orElse(configEventExpires)
- );
+ );
}
return false;
@@ -323,9 +321,9 @@ 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 {
// Create tenant rules engines for this tenant if it has any rulesets
@@ -348,15 +346,14 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
new AssetState(loadedAsset, attribute.deepCopy(), Source.INTERNAL);
switch (persistenceEvent.getCause()) {
- case INSERT:
- {
+ case INSERT: {
// New asset has been created so get attributes that have RULE_STATE meta
List<AssetAttribute> ruleStateAttributes =
asset.getAttributesStream().filter(AssetAttribute::isRuleState).collect(Collectors.toList());
// Asset used to be loaded for each attribute which is inefficient
Asset loadedAsset = ruleStateAttributes.isEmpty() ? null : assetStorageService.find(asset.getId(),
- true);
+ true);
// Build an update with a fully loaded asset
ruleStateAttributes.forEach(attribute -> {
@@ -389,18 +386,18 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
attributesFromJson(
(ObjectValue) persistenceEvent.getPreviousState()[attributesIndex],
asset.getId()
- ).filter(AssetAttribute::isRuleState).collect(Collectors.toList());
+ ).filter(AssetAttribute::isRuleState).collect(Collectors.toList());
List<AssetAttribute> newRuleStateAttributes =
attributesFromJson(
(ObjectValue) persistenceEvent.getCurrentState()[attributesIndex],
asset.getId()
- ).filter(AssetAttribute::isRuleState).collect(Collectors.toList());
+ ).filter(AssetAttribute::isRuleState).collect(Collectors.toList());
// Retract facts for attributes that are obsolete
getAddedOrModifiedAttributes(newRuleStateAttributes,
- oldRuleStateAttributes,
- key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME))
+ 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);
@@ -409,8 +406,8 @@ 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))
+ 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);
@@ -570,8 +567,8 @@ 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()))
.entrySet()
@@ -742,12 +739,12 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
new AttributeMetaPredicate(
AssetMeta.RULE_STATE,
new BooleanPredicate(true))
- ));
+ ));
return assets.stream()
.map((Asset asset) ->
- new Pair<>(asset, asset.getAttributesStream().filter(AssetAttribute::isRuleState))
- );
+ new Pair<>(asset, asset.getAttributesStream().filter(AssetAttribute::isRuleState))
+ );
}
/**
@@ -762,68 +759,68 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
if (newEngineAssetStateLocationPredicates == null) {
engineAssetLocationPredicateMap.computeIfPresent(rulesEngine,
- (re, existingAssetStateLocationPredicates) -> {
- // All location predicates have been removed so record each asset state as modified
- assetsWithModifiedLocationPredicates.addAll(
- existingAssetStateLocationPredicates.stream().map(
- RulesEngine.AssetStateLocationPredicates::getAssetId).collect(
- Collectors.toList()));
- // Remove this engine from the map
- return null;
- });
+ (re, existingAssetStateLocationPredicates) -> {
+ // All location predicates have been removed so record each asset state as modified
+ assetsWithModifiedLocationPredicates.addAll(
+ existingAssetStateLocationPredicates.stream().map(
+ RulesEngine.AssetStateLocationPredicates::getAssetId).collect(
+ Collectors.toList()));
+ // Remove this engine from the map
+ return null;
+ });
} else {
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 (existingEngineAssetStateLocationPredicates == null) {
- // All asset states are new so record them all as modified
- assetsWithModifiedLocationPredicates.addAll(
- newEngineAssetStateLocationPredicates.stream().map(
- RulesEngine.AssetStateLocationPredicates::getAssetId).collect(
- Collectors.toList()));
- } else {
- // Find obsolete and modified asset states
- existingEngineAssetStateLocationPredicates.forEach(
- existingAssetStateLocationPredicates -> {
- // Check if there are no longer any location predicates for this asset
- Optional<RulesEngine.AssetStateLocationPredicates> newAssetStateLocationPredicates = newEngineAssetStateLocationPredicates.stream()
- .filter(assetStateLocationPredicates ->
- assetStateLocationPredicates.getAssetId().equals(
- existingAssetStateLocationPredicates.getAssetId()))
- .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())) {
- assetsWithModifiedLocationPredicates.add(
- existingAssetStateLocationPredicates.getAssetId());
- }
- } else {
- // This means that there are no longer any location predicates so old ones are obsolete
- assetsWithModifiedLocationPredicates.add(
- existingAssetStateLocationPredicates.getAssetId());
- }
- });
-
- // Check for asset states in the new map but not in the old one
- newEngineAssetStateLocationPredicates.forEach(
- newAssetStateLocationPredicates -> {
- boolean isNewAssetState = existingEngineAssetStateLocationPredicates.stream()
- .noneMatch(assetStateLocationPredicates ->
- assetStateLocationPredicates.getAssetId().equals(
- newAssetStateLocationPredicates.getAssetId()));
-
- if (isNewAssetState) {
- // This means that all predicates for this asset are new
- assetsWithModifiedLocationPredicates.add(
- newAssetStateLocationPredicates.getAssetId());
- }
- });
- }
- return newEngineAssetStateLocationPredicates;
- });
+ (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 (existingEngineAssetStateLocationPredicates == null) {
+ // All asset states are new so record them all as modified
+ assetsWithModifiedLocationPredicates.addAll(
+ newEngineAssetStateLocationPredicates.stream().map(
+ RulesEngine.AssetStateLocationPredicates::getAssetId).collect(
+ Collectors.toList()));
+ } else {
+ // Find obsolete and modified asset states
+ existingEngineAssetStateLocationPredicates.forEach(
+ existingAssetStateLocationPredicates -> {
+ // Check if there are no longer any location predicates for this asset
+ Optional<RulesEngine.AssetStateLocationPredicates> newAssetStateLocationPredicates = newEngineAssetStateLocationPredicates.stream()
+ .filter(assetStateLocationPredicates ->
+ assetStateLocationPredicates.getAssetId().equals(
+ existingAssetStateLocationPredicates.getAssetId()))
+ .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())) {
+ assetsWithModifiedLocationPredicates.add(
+ existingAssetStateLocationPredicates.getAssetId());
+ }
+ } else {
+ // This means that there are no longer any location predicates so old ones are obsolete
+ assetsWithModifiedLocationPredicates.add(
+ existingAssetStateLocationPredicates.getAssetId());
+ }
+ });
+
+ // Check for asset states in the new map but not in the old one
+ newEngineAssetStateLocationPredicates.forEach(
+ newAssetStateLocationPredicates -> {
+ boolean isNewAssetState = existingEngineAssetStateLocationPredicates.stream()
+ .noneMatch(assetStateLocationPredicates ->
+ assetStateLocationPredicates.getAssetId().equals(
+ newAssetStateLocationPredicates.getAssetId()));
+
+ if (isNewAssetState) {
+ // This means that all predicates for this asset are new
+ assetsWithModifiedLocationPredicates.add(
+ newAssetStateLocationPredicates.getAssetId());
+ }
+ });
+ }
+ return newEngineAssetStateLocationPredicates;
+ });
}
if (assetsWithModifiedLocationPredicates.size() != initialModifiedCount) {
@@ -835,17 +832,6 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
protected void processModifiedGeofences() {
withLock(getClass().getSimpleName() + "::processModifiedGeofences", () -> {
LOG.finest("Processing geofence modifications: modified asset geofence count=" + assetsWithModifiedLocationPredicates.size());
- boolean isFirstRun = firstGeofenceProcessorRun;
-
- if (isFirstRun) {
- if (geofenceInitScheduledFuture == null || geofenceInitScheduledFuture.cancel(false)) {
- geofenceInitScheduledFuture = executorService.schedule(() -> {
- firstGeofenceProcessorRun = false;
- geofenceInitScheduledFuture = null;
- },
- GEOFENCE_INIT_DEBOUNCE_MILLIS);
- }
- }
try {
// Find all location predicates associated with modified assets and pass through to the geofence adapters
@@ -859,23 +845,23 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
new HashSet<>());
engineAssetLocationPredicateMap.forEach((rulesEngine, engineAssetStateLocationPredicates) ->
- engineAssetStateLocationPredicates.stream().filter(
- assetStateLocationPredicates ->
- assetStateLocationPredicates.getAssetId().equals(
- assetId))
- .findFirst()
- .ifPresent(
- assetStateLocationPredicate -> {
- locationPredicates.getLocationPredicates().addAll(
- assetStateLocationPredicate.getLocationPredicates());
- }));
+ engineAssetStateLocationPredicates.stream().filter(
+ assetStateLocationPredicates ->
+ assetStateLocationPredicates.getAssetId().equals(
+ assetId))
+ .findFirst()
+ .ifPresent(
+ assetStateLocationPredicate -> {
+ locationPredicates.getLocationPredicates().addAll(
+ assetStateLocationPredicate.getLocationPredicates());
+ }));
assetLocationPredicates.add(locationPredicates);
});
for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {
LOG.finest("Passing modified geofences to adapter: " + geofenceAssetAdapter.getName());
- geofenceAssetAdapter.processLocationPredicates(assetLocationPredicates, isFirstRun);
+ geofenceAssetAdapter.processLocationPredicates(assetLocationPredicates);
if (assetLocationPredicates.isEmpty()) {
LOG.finest("All modified geofences handled");
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.java
index e9557f298..469ac40a2 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
@@ -60,17 +60,11 @@ public interface GeofenceAssetAdapter {
String getName();
/**
- * The initialising flag is used to indicate that the system is just initialising and the adapter is being made
- * aware of existing {@link 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).
- * <p>
* If an adapter handles the location predicates for a particular asset then the adapter should remove that item
* from the list to prevent other adapters from also handling it. If an {@link RulesEngine.AssetStateLocationPredicates#getLocationPredicates}
* is empty then it means there are no longer any location predicates associated with that asset
*/
- void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> modifiedAssetLocationPredicates,
- boolean initialising);
+ void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> modifiedAssetLocationPredicates);
/**
* Called to return the active geofences for the specified {@link Asset}; if this adapter supports the requested
diff --git a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
index 122bc5418..c0b4a161a 100644
--- a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
+++ b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
@@ -31,17 +31,18 @@ import org.openremote.manager.rules.RulesEngine;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.model.asset.Asset;
import org.openremote.model.attribute.AttributeRef;
-import org.openremote.model.query.AssetQuery;
-import org.openremote.model.query.BaseAssetQuery;
import org.openremote.model.attribute.AttributeType;
import org.openremote.model.console.ConsoleConfiguration;
import org.openremote.model.console.ConsoleProvider;
import org.openremote.model.notification.Notification;
import org.openremote.model.notification.PushNotificationMessage;
+import org.openremote.model.query.AssetQuery;
+import org.openremote.model.query.BaseAssetQuery;
import org.openremote.model.query.filter.LocationPredicate;
import org.openremote.model.query.filter.ObjectValueKeyPredicate;
import org.openremote.model.query.filter.RadialLocationPredicate;
import org.openremote.model.rules.geofence.GeofenceDefinition;
+import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.TextUtil;
import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.Values;
@@ -51,12 +52,14 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
import java.util.stream.Collectors;
+import java.util.stream.IntStream;
import static org.openremote.container.concurrent.GlobalLock.withLock;
import static org.openremote.container.persistence.PersistenceEvent.*;
import static org.openremote.model.asset.AssetResource.Util.WRITE_ATTRIBUTE_HTTP_METHOD;
import static org.openremote.model.asset.AssetResource.Util.getWriteAttributeUrl;
import static org.openremote.model.asset.AssetType.CONSOLE;
+import static org.openremote.model.syslog.SyslogCategory.RULES;
/**
* This implementation is for handling geofences on console assets that support the OR Console Geofence Provider (i.e.
@@ -68,7 +71,7 @@ import static org.openremote.model.asset.AssetType.CONSOLE;
*/
public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements GeofenceAssetAdapter, ContainerService {
- private static final Logger LOG = Logger.getLogger(ORConsoleGeofenceAssetAdapter.class.getName());
+ private static final Logger LOG = SyslogCategory.getLogger(RULES, ORConsoleGeofenceAssetAdapter.class.getName());
public static final String NAME = "ORConsole";
public static int NOTIFY_ASSETS_DEBOUNCE_MILLIS = 60000;
protected Map<String, RulesEngine.AssetStateLocationPredicates> assetLocationPredicatesMap = new HashMap<>();
@@ -93,17 +96,19 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
public void start(Container container) throws Exception {
// Find all console assets that use this adapter
- consoleIdRealmMap = assetStorageService.findAll(
+ consoleIdRealmMap = new HashMap<>();
+
+ assetStorageService.findAll(
new AssetQuery()
.select(new BaseAssetQuery.Select(BaseAssetQuery.Include.ALL_EXCEPT_PATH,
- false,
- AttributeType.CONSOLE_PROVIDERS.getName()))
+ false,
+ AttributeType.CONSOLE_PROVIDERS.getName()))
.type(CONSOLE)
.attributeValue(AttributeType.CONSOLE_PROVIDERS.getName(),
- new ObjectValueKeyPredicate("geofence")))
+ new ObjectValueKeyPredicate("geofence")))
.stream()
.filter(ORConsoleGeofenceAssetAdapter::isLinkedToORConsoleGeofenceAdapter)
- .collect(Collectors.toMap(Asset::getId, Asset::getTenantRealm));
+ .forEach(asset -> consoleIdRealmMap.put(asset.getId(), asset.getTenantRealm()));
}
@Override
@@ -138,7 +143,7 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
}
@Override
- public void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> modifiedAssetLocationPredicates, boolean initialising) {
+ public void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> modifiedAssetLocationPredicates) {
withLock(getClass().getSimpleName() + "::processLocationPredicates", () -> {
@@ -157,27 +162,37 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
assetStateLocationPredicates
.getLocationPredicates()
.removeIf(locationPredicate ->
- !(locationPredicate instanceof RadialLocationPredicate));
+ !(locationPredicate instanceof RadialLocationPredicate));
- // If not initialising compare existing with new predicates and notify affected assets
- if (!initialising) {
- RulesEngine.AssetStateLocationPredicates existingPredicates = assetLocationPredicatesMap.get(
- assetStateLocationPredicates.getAssetId());
- if (existingPredicates == null || !existingPredicates.getLocationPredicates().equals(assetStateLocationPredicates.getLocationPredicates())) {
- // We're not comparing before and after state as RulesService has done that although it could be
- // that rectangular location predicates have changed but this will do for now
- notifyAssets.add(assetStateLocationPredicates.getAssetId());
- notifierDebounce.set(true);
- }
+ RulesEngine.AssetStateLocationPredicates existingPredicates = assetLocationPredicatesMap.get(
+ assetStateLocationPredicates.getAssetId());
+ if (existingPredicates == null || !existingPredicates.getLocationPredicates().equals(assetStateLocationPredicates.getLocationPredicates())) {
+ // We're not comparing before and after state as RulesService has done that although it could be
+ // that rectangular location predicates have changed but this will do for now
+ notifyAssets.add(assetStateLocationPredicates.getAssetId());
+ notifierDebounce.set(true);
}
if (assetStateLocationPredicates.getLocationPredicates().isEmpty()) {
- assetLocationPredicatesMap.remove(assetStateLocationPredicates.getAssetId());
+ if (assetLocationPredicatesMap.remove(assetStateLocationPredicates.getAssetId()) != null) {
+ LOG.info("Clearing location predicates for asset: " + assetStateLocationPredicates.getAssetId());
+ notifyAssets.add(assetStateLocationPredicates.getAssetId());
+ notifierDebounce.set(true);
+ }
} else {
+ LOG.info("Setting "
+ + assetStateLocationPredicates.getLocationPredicates().size()
+ + " location predicate(s) for asset: " + assetStateLocationPredicates.getAssetId());
+
assetLocationPredicatesMap.put(assetStateLocationPredicates.getAssetId(),
- assetStateLocationPredicates);
+ assetStateLocationPredicates);
}
+ } else if (assetLocationPredicatesMap.remove(assetStateLocationPredicates.getAssetId()) != null) {
+ // Used to be in this map so must have been deleted so ask console to delete its geofences also
+ LOG.info("Clearing location predicates for asset: " + assetStateLocationPredicates.getAssetId());
+ notifyAssets.add(assetStateLocationPredicates.getAssetId());
+ notifierDebounce.set(true);
}
return remove;
@@ -186,12 +201,13 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
if (notifierDebounce.get()) {
if (notifyAssetsScheduledFuture == null || notifyAssetsScheduledFuture.cancel(false)) {
notifyAssetsScheduledFuture = executorService.schedule(() ->
- withLock(getClass().getSimpleName() + "::notifyAssets",
- () -> {
- notifyAssets.forEach(this::notifyAssetGeofencesChanged);
- notifyAssetsScheduledFuture = null;
- }),
- NOTIFY_ASSETS_DEBOUNCE_MILLIS);
+ withLock(getClass().getSimpleName() + "::notifyAssets",
+ () -> {
+ notifyAssetGeofencesChanged(notifyAssets);
+ notifyAssets = null;
+ notifyAssetsScheduledFuture = null;
+ }),
+ NOTIFY_ASSETS_DEBOUNCE_MILLIS);
}
}
});
@@ -201,8 +217,10 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
public GeofenceDefinition[] getAssetGeofences(String assetId) {
String realm = consoleIdRealmMap.get(assetId);
+ LOG.info("Request for console geofences: " + assetId);
+
if (realm == null) {
- LOG.finest("Console ID not found in map so cannot retrieve geofences");
+ LOG.info("Console ID not found in map so cannot retrieve geofences");
// Asset not supported by this adapter
return null;
}
@@ -211,14 +229,18 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
if (assetStateLocationPredicates == null) {
// No geofences exist for this asset
+ LOG.info("No geofences exist");
return new GeofenceDefinition[0];
}
- return assetStateLocationPredicates.getLocationPredicates().stream()
+ GeofenceDefinition[] geofences = assetStateLocationPredicates.getLocationPredicates().stream()
.map(locationPredicate ->
- locationPredicateToGeofenceDefinition(assetStateLocationPredicates.getAssetId(),
- locationPredicate))
+ locationPredicateToGeofenceDefinition(assetStateLocationPredicates.getAssetId(),
+ locationPredicate))
.toArray(GeofenceDefinition[]::new);
+
+ LOG.info("Retrieved " + geofences.length + " geofence(s)");
+ return geofences;
}
protected GeofenceDefinition locationPredicateToGeofenceDefinition(String assetId, LocationPredicate locationPredicate) {
@@ -226,24 +248,35 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
String id = assetId + "_" + Integer.toString(radialLocationPredicate.hashCode());
String url = getWriteAttributeUrl(new AttributeRef(assetId, AttributeType.LOCATION.getName()));
return new GeofenceDefinition(id,
- radialLocationPredicate.getLat(),
- radialLocationPredicate.getLng(),
- radialLocationPredicate.getRadius(),
- WRITE_ATTRIBUTE_HTTP_METHOD,
- url);
+ radialLocationPredicate.getLat(),
+ radialLocationPredicate.getLng(),
+ radialLocationPredicate.getRadius(),
+ WRITE_ATTRIBUTE_HTTP_METHOD,
+ url);
}
/**
* Send a silent push notification to the console to get it to refresh its geofences
*/
- protected void notifyAssetGeofencesChanged(String assetId) {
+ protected void notifyAssetGeofencesChanged(Set<String> assetIds) {
+ if (assetIds == null) {
+ return;
+ }
+
+ List<String> ids = new ArrayList<>(assetIds);
ObjectValue data = Values.createObject();
data.put("action", "GEOFENCE_REFRESH");
- notificationService.sendNotification(
- new Notification(
- "GeofenceRefresh",
- new PushNotificationMessage().setData(data),
- new Notification.Targets(Notification.TargetType.ASSET, Collections.singletonList(assetId))));
+ Notification notification = new Notification("GeofenceRefresh", new PushNotificationMessage().setData(data), null);
+
+ // Break into batches of 10 sent every 10s to avoid consoles bombarding the backend
+ int rows = 1 + ids.size() / 10;
+ IntStream.range(0, rows)
+ .forEach(i -> {
+ List<String> subIds = ids.subList(10 * i, Math.min(10 + (10 * i), ids.size()));
+ notification.setTargets(new Notification.Targets(Notification.TargetType.ASSET, subIds));
+ LOG.info("Notifiying consoles that geofences have changed: " + subIds);
+ executorService.schedule(() -> notificationService.sendNotification(notification), i * 10000);
+ });
}
protected void processConsoleAssetChange(Asset asset, PersistenceEvent persistenceEvent) {
diff --git a/manager/src/main/resources/logging.properties b/manager/src/main/resources/logging.properties
index 27c229784..41a8df736 100644
--- a/manager/src/main/resources/logging.properties
+++ b/manager/src/main/resources/logging.properties
@@ -8,8 +8,7 @@
###############################################################################
# Log on STDOUT and internal syslog service (monitoring in Manager UI)
-handlers=java.util.logging.ConsoleHandler, \
- org.openremote.manager.syslog.SyslogService
+handlers=java.util.logging.ConsoleHandler,org.openremote.manager.syslog.SyslogService
# Log on STDOUT, to a file, and internal syslog service (monitoring in Manager UI)
#handlers=java.util.logging.ConsoleHandler, \