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
Group summation rule groovy (#1275)
Igor Rutkafca187feff69
diff --git a/test/src/test/groovy/org/openremote/test/rules/GroupSummationRuleTest.groovy b/test/src/test/groovy/org/openremote/test/rules/GroupSummationRuleTest.groovynew file mode 100644index 000000000..ad4ab135c--- /dev/null+++ b/test/src/test/groovy/org/openremote/test/rules/GroupSummationRuleTest.groovy@@ -0,0 +1,114 @@+package org.openremote.test.rules++import org.openremote.container.util.UniqueIdentifierGenerator+import org.openremote.manager.asset.AssetProcessingService+import org.openremote.manager.asset.AssetStorageService+import org.openremote.manager.rules.RulesEngine+import org.openremote.manager.rules.RulesService+import org.openremote.manager.rules.RulesetStorageService+import org.openremote.model.Constants+import org.openremote.model.asset.impl.ThingAsset+import org.openremote.model.attribute.Attribute+import org.openremote.model.attribute.AttributeEvent+import org.openremote.model.attribute.MetaItem+import org.openremote.model.rules.RealmRuleset+import org.openremote.model.rules.Ruleset+import org.openremote.model.value.MetaItemType+import org.openremote.model.value.ValueType+import org.openremote.test.ManagerContainerTrait+import spock.lang.Specification+import spock.util.concurrent.PollingConditions++class GroupSummationRuleTest extends Specification implements ManagerContainerTrait {++ def "Group summation rule test"() {++ given: "the container environment is started"+ def conditions = new PollingConditions(timeout: 5, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())+ def rulesService = container.getService(RulesService.class)+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def rulesetStorageService = container.getService(RulesetStorageService.class)+ RulesEngine engine = null++ and: "a parent asset and child assets are added"+ def parentAsset = new ThingAsset("SummationParentAsset")+ .setId(UniqueIdentifierGenerator.generateId("SummationParentAsset"))+ .setRealm(Constants.MASTER_REALM)+ .addAttributes(+ new Attribute<>("boolean", ValueType.BOOLEAN, null).addMeta(new MetaItem<>(MetaItemType.RULE_STATE)),+ new Attribute<>("integer", ValueType.INTEGER, null).addMeta(new MetaItem<>(MetaItemType.RULE_STATE)),+ new Attribute<>("number", ValueType.NUMBER, null).addMeta(new MetaItem<>(MetaItemType.RULE_STATE))+ )+ parentAsset = assetStorageService.merge(parentAsset)++ def childAsset1 = new ThingAsset("childAsset1")+ .setId(UniqueIdentifierGenerator.generateId("childAsset1"))+ .setParent(parentAsset)+ .addAttributes(+ new Attribute<>("boolean", ValueType.BOOLEAN, null).addMeta(new MetaItem<>(MetaItemType.RULE_STATE)),+ new Attribute<>("integer", ValueType.INTEGER, null).addMeta(new MetaItem<>(MetaItemType.RULE_STATE)),+ new Attribute<>("number", ValueType.NUMBER, null).addMeta(new MetaItem<>(MetaItemType.RULE_STATE))+ )+ childAsset1 = assetStorageService.merge(childAsset1)++ def childAsset2 = new ThingAsset("childAsset2")+ .setId(UniqueIdentifierGenerator.generateId("childAsset2"))+ .setParent(parentAsset)+ .addAttributes(+ new Attribute<>("boolean", ValueType.BOOLEAN, null).addMeta(new MetaItem<>(MetaItemType.RULE_STATE)),+ new Attribute<>("integer", ValueType.INTEGER, null).addMeta(new MetaItem<>(MetaItemType.RULE_STATE)),+ new Attribute<>("number", ValueType.NUMBER, null).addMeta(new MetaItem<>(MetaItemType.RULE_STATE))+ )+ childAsset2 = assetStorageService.merge(childAsset2)++ and: "the group summation ruleset is added"+ Ruleset ruleset = new RealmRuleset(+ Constants.MASTER_REALM,+ "Group summation rule",+ Ruleset.Lang.GROOVY,+ getClass().getResource("/org/openremote/test/rules/GroupSummationRule.groovy").text)+ ruleset = rulesetStorageService.merge(ruleset)++ expect: "the rule engines to become available and be running"+ conditions.eventually {+ engine = rulesService.realmEngines.get(Constants.MASTER_REALM)+ assert engine != null+ assert engine.isRunning()+ assert engine.assetStates.count { it.id == parentAsset.id } == 3+ assert engine.lastFireTimestamp > ruleset.createdOn.getTime()+ assert engine.deployments.get(ruleset.id) != null+ }++ when: "the integer attribute of the child assets is written to"+ assetProcessingService.sendAttributeEvent(new AttributeEvent(childAsset1.id, "integer", 1))+ assetProcessingService.sendAttributeEvent(new AttributeEvent(childAsset2.id, "integer", 1))++ then: "the corresponding attribute of the parent asset should be updated with the attribute sum of the child assets"+ conditions.eventually {+ parentAsset = assetStorageService.find(parentAsset.id, true) as ThingAsset+ assert parentAsset.getAttribute("integer").flatMap { it.value }.orElse(0) == 2+ }++ when: "the number attribute of the child assets is written to"+ assetProcessingService.sendAttributeEvent(new AttributeEvent(childAsset1.id, "number", 1.0))+ assetProcessingService.sendAttributeEvent(new AttributeEvent(childAsset2.id, "number", 1.0))++ then: "the corresponding attribute of the parent asset should be updated with the attribute sum of the child assets"+ conditions.eventually {+ parentAsset = assetStorageService.find(parentAsset.id, true) as ThingAsset+ assert parentAsset.getAttribute("number").flatMap { it.value }.orElse(0.0) == 2.0+ }++ when: "the boolean attribute of the child assets is written to"+ assetProcessingService.sendAttributeEvent(new AttributeEvent(childAsset1.id, "boolean", true))+ assetProcessingService.sendAttributeEvent(new AttributeEvent(childAsset2.id, "boolean", true))++ then: "the corresponding attribute of the parent asset should not be updated"+ conditions.eventually {+ parentAsset = assetStorageService.find(parentAsset.id, true) as ThingAsset+ assert !parentAsset.getAttribute("boolean").flatMap { it.value }.orElse(false)+ }+ }+}diff --git a/test/src/test/resources/org/openremote/test/rules/GroupSummationRule.groovy b/test/src/test/resources/org/openremote/test/rules/GroupSummationRule.groovynew file mode 100644index 000000000..6a464c696--- /dev/null+++ b/test/src/test/resources/org/openremote/test/rules/GroupSummationRule.groovy@@ -0,0 +1,135 @@+/*+Example group summation rule for the summation of child asset attributes to parent asset attributes:+ - The child and parent attributes must have the 'Rule state' configuration item added.+ - You must specify the parent asset ID below.+ */++package org.openremote.test.rules++import org.openremote.manager.rules.RulesBuilder+import org.openremote.model.attribute.AttributeInfo+import org.openremote.model.query.AssetQuery+import org.openremote.model.rules.Assets+import org.openremote.model.rules.Notifications+import org.openremote.model.rules.Users++import java.util.logging.Logger++Logger LOG = binding.LOG+RulesBuilder rules = binding.rules+Users users = binding.users+Notifications notifications = binding.notifications+Assets assets = binding.assets++// Put the parent asset ID here:+String parentAssetId = "47zxEJ7nZCPbOHLvYKWNs6"++// Put the attribute names for summation here (or leave empty to include all child asset attribute names with 'Rule state'):+String[] attributeNames = []+//String[] attributeNames = ["attributeName1", "attributeName2"] // Example++// Put if the child and parent asset type must match here:+boolean matchParentAssetType = true++rules.add()+ .name("Group summation rule")+ .when({ facts ->++ // Check if parent asset ID is valid+ Optional<AttributeInfo> parent = facts.matchFirstAssetState(new AssetQuery().ids(parentAssetId))++ if (parent.isEmpty()) {+ LOG.warning("No Parent Asset found with ID: '" + parentAssetId + "'; Check Parent Asset ID and if the rule state configuration is added to the attribute")+ return false+ }++ // Find attribute changes in group for your attribute names+ List<AttributeInfo> changes = facts+ .matchAssetState(new AssetQuery().parents(parentAssetId).attributeNames(attributeNames))+ .filter { attributeInfo ->+ boolean timestampChanged = false++ // Get previous attribute state from facts+ Optional<AttributeInfo> previous = facts.matchFirst(attributeInfo.id + attributeInfo.name)++ // Check if attribute timestamp has been updated (attribute value can be the same)+ if (attributeInfo.timestamp > previous.map { it.timestamp }.orElse(0)) {+ timestampChanged = true+ }++ return timestampChanged+ }+ .toList()++ // Get attribute names of changes+ String[] changesAttributeNames = changes+ .collect { it.name }+ .unique()++ // Find all relevant children attributes+ List<AttributeInfo> childrenAttributes = Collections.synchronizedList(new ArrayList<>())++ if (changesAttributeNames.length > 0) {+ childrenAttributes = facts+ .matchAssetState(new AssetQuery().parents(parentAssetId).attributeNames(changesAttributeNames))+ .toList()+ }++ // Bind attribute info for the then trigger+ if (!changes.isEmpty()) {+ facts.bind("parent", parent)+ facts.bind("changes", changes)++ if (!childrenAttributes.isEmpty()) {+ facts.bind("changesAttributeNames", changesAttributeNames)+ facts.bind("childrenAttributes", childrenAttributes)+ }+ }++ // Trigger the rule 'then' action if there are changes to process+ return !changes.isEmpty()+ })+ .then({ facts ->+ Optional<AttributeInfo> parent = facts.bound("parent")+ List<AttributeInfo> changes = facts.bound("changes")+ String[] changesAttributeNames = facts.bound("changesAttributeNames")+ List<AttributeInfo> childrenAttributes = facts.bound("childrenAttributes")++ // Create fact for each attribute change+ changes.forEach { attributeInfo -> facts.put(attributeInfo.id + attributeInfo.name, attributeInfo as Object) }++ // Stop when group is empty+ if (childrenAttributes == null) {+ return+ }++ // Filter children attributes+ List<AttributeInfo> childrenAttributesFiltered = childrenAttributes++ if (matchParentAssetType) {+ childrenAttributesFiltered = childrenAttributes+ .findAll { it.assetType == parent.get().assetType }+ }++ // Sum values per attribute+ for (attributeName in changesAttributeNames) {+ // Validate value type+ boolean validValueType = childrenAttributesFiltered+ .find { it.name == attributeName }+ .collect { it.type.type.name }+ .any { it in ["java.lang.Double", "java.lang.Integer", "java.lang.Long", "java.math.BigDecimal", "java.math.BigInteger"] }++ if (validValueType) {+ def sum = childrenAttributesFiltered+ .findAll { it.name == attributeName }+ .findAll { it.value.isPresent() }+ .collect { it.value.get() }+ .sum()++ // Update parent+ if (sum != null) {+ assets.dispatch(parentAssetId, attributeName, sum)+ }+ }+ }+ })