Skip to content

armgit / core

Public Imported from GitHub
0

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

JSON rules support for multiple attributes within a when condition (#960)

Rich Turner327a8b1abf9e
diff --git a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
index eeec7efdd..b72ae302e 100644
--- a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
+++ b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
@@ -105,7 +105,7 @@ public class AssetQueryPredicate implements Predicate<AssetState<?>> {
if (query.attributes != null) {
// TODO: LogicGroup AND doesn't make much sense when applying to a single asset state
- if (!asPredicate(timerService::getCurrentTimeMillis, query.attributes).test(assetState)) {
+ if (!asAssetPredicate(timerService::getCurrentTimeMillis, query.attributes).test(Collections.singletonList(assetState))) {
return false;
}
}
@@ -179,21 +179,25 @@ public class AssetQueryPredicate implements Predicate<AssetState<?>> {
&& valuePredicate.test(valueExtractor.get().apply(nameValueHolder));
}
+ /**
+ * A predicate for {@link AssetState}s of an asset; the states must be related to the same asset to allow
+ * {@link LogicGroup.Operator#AND} to be applied.
+ */
@SuppressWarnings("unchecked")
- public static Predicate<AssetState<?>> asPredicate(Supplier<Long> currentMillisProducer, LogicGroup<AttributePredicate> condition) {
+ public static Predicate<List<AssetState<?>>> asAssetPredicate(Supplier<Long> currentMillisProducer, LogicGroup<AttributePredicate> condition) {
if (groupIsEmpty(condition)) {
return as -> true;
}
LogicGroup.Operator operator = condition.operator == null ? LogicGroup.Operator.AND : condition.operator;
-
- List<Predicate<AssetState<?>>> assetStatePredicates = new ArrayList<>();
+ List<Predicate<List<AssetState<?>>>> assetPredicates = new ArrayList<>();
+ List<Predicate<AssetState<?>>> attributePredicates = new ArrayList<>();
if (condition.getItems().size() > 0) {
condition.getItems().stream()
.forEach(p -> {
- assetStatePredicates.add((Predicate<AssetState<?>>)(Predicate)asPredicate(currentMillisProducer, p));
+ attributePredicates.add((Predicate<AssetState<?>>)(Predicate)asPredicate(currentMillisProducer, p));
AtomicReference<Predicate<AssetState<?>>> metaPredicate = new AtomicReference<>(nameValueHolder -> true);
AtomicReference<Predicate<AssetState<?>>> oldValuePredicate = new AtomicReference<>(value -> true);
@@ -209,25 +213,37 @@ public class AssetQueryPredicate implements Predicate<AssetState<?>> {
innerMetaPredicate.test(assetState)
);
});
- assetStatePredicates.add(metaPredicate.get());
+ attributePredicates.add(metaPredicate.get());
}
if (p.previousValue != null) {
Predicate<Object> innerOldValuePredicate = p.previousValue.asPredicate(currentMillisProducer);
oldValuePredicate.set(nameValueHolder -> innerOldValuePredicate.test((nameValueHolder).getOldValue()));
- assetStatePredicates.add(oldValuePredicate.get());
+ attributePredicates.add(oldValuePredicate.get());
}
});
}
if (condition.groups != null && condition.groups.size() > 0) {
- assetStatePredicates.addAll(
+ assetPredicates.addAll(
condition.groups.stream()
- .map(c -> asPredicate(currentMillisProducer, c)).collect(Collectors.toList())
+ .map(c -> asAssetPredicate(currentMillisProducer, c)).toList()
+ );
+ }
+
+ if (operator == LogicGroup.Operator.AND) {
+ // All predicates must match at least one of the asset's state
+ assetPredicates.add(assetStates ->
+ attributePredicates.stream().allMatch(attributePredicate -> assetStates.stream().anyMatch(attributePredicate))
+ );
+ } else {
+ // Any of the predicates must match at least one of the asset's state
+ assetPredicates.add(assetStates ->
+ attributePredicates.stream().anyMatch(attributePredicate -> assetStates.stream().anyMatch(attributePredicate))
);
}
- return asPredicate(assetStatePredicates, operator);
+ return asPredicate(assetPredicates, operator);
}
protected static boolean groupIsEmpty(LogicGroup<?> condition) {
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
index 540606037..1a11e15ee 100644
--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
@@ -90,7 +90,7 @@ public class JsonRulesBuilder extends RulesBuilder {
AssetQuery.OrderBy orderBy;
int limit;
LogicGroup<AttributePredicate> attributePredicates = null;
- Predicate<AssetState<?>> assetStatePredicate = null;
+ Predicate<List<AssetState<?>>> assetPredicate = null;
Set<AssetState<?>> unfilteredAssetStates = new HashSet<>();
Set<AssetState<?>> previouslyMatchedAssetStates = new HashSet<>();
Set<AssetState<?>> previouslyUnmatchedAssetStates;
@@ -199,7 +199,7 @@ public class JsonRulesBuilder extends RulesBuilder {
// Only supports a single level or logic group for attributes (i.e. cannot nest groups in the UI so
// don't support it here either)
attributePredicates.groups = null;
- assetStatePredicate = AssetQueryPredicate.asPredicate(timerService::getCurrentTimeMillis, attributePredicates);
+ assetPredicate = AssetQueryPredicate.asAssetPredicate(timerService::getCurrentTimeMillis, attributePredicates);
}
ruleCondition.assets.orderBy = null;
ruleCondition.assets.limit = 0;
@@ -278,30 +278,19 @@ public class JsonRulesBuilder extends RulesBuilder {
matchedAssetStates = new ArrayList<>(unfilteredAssetStates);
} else {
- Map<Boolean, List<AssetState<?>>> results;
- boolean isAndGroup = attributePredicates.operator == null || attributePredicates.operator == LogicGroup.Operator.AND;
+ Map<Boolean, List<AssetState<?>>> results = new HashMap<>();
+ ArrayList<AssetState<?>> matched = new ArrayList<>();
+ ArrayList<AssetState<?>> unmatched = new ArrayList<>();
+ results.put(true, matched);
+ results.put(false, unmatched);
- if (isAndGroup) {
-
- // ANDs need to be applied in the context of an entire asset as don't make any sense otherwise
- results = new HashMap<>();
- ArrayList<AssetState<?>> matched = new ArrayList<>();
- ArrayList<AssetState<?>> unmatched = new ArrayList<>();
- results.put(true, matched);
- results.put(false, unmatched);
-
- unfilteredAssetStates.stream().collect(Collectors.groupingBy(AssetState::getId)).forEach((id, states) -> {
-
- Map<Boolean, List<AssetState<?>>> assetResults = states.stream().collect(Collectors.groupingBy(assetStatePredicate::test));
- matched.addAll(assetResults.getOrDefault(true, Collections.emptyList()));
- unmatched.addAll(assetResults.getOrDefault(false, Collections.emptyList()));
- });
-
- } else {
-
- results = unfilteredAssetStates.stream().collect(Collectors.groupingBy(assetStatePredicate::test));
-
- }
+ unfilteredAssetStates.stream().collect(Collectors.groupingBy(AssetState::getId)).forEach((id, states) -> {
+ if (assetPredicate.test(states)) {
+ matched.addAll(states);
+ } else {
+ unmatched.addAll(states);
+ }
+ });
matchedAssetStates = results.getOrDefault(true, Collections.emptyList());
unmatchedAssetStates = results.getOrDefault(false, Collections.emptyList());
diff --git a/manager/src/main/resources/logging-dev.properties b/manager/src/main/resources/logging-dev.properties
index 0c31dbbac..dafaf3bd5 100644
--- a/manager/src/main/resources/logging-dev.properties
+++ b/manager/src/main/resources/logging-dev.properties
@@ -29,6 +29,7 @@ java.util.logging.ConsoleHandler.formatter=org.openremote.container.util.LogForm
# The root logger category of OpenRemote
org.openremote.level=FINE
+org.openremote.agent.protocol.level=FINEST
# Processing time logging
#org.openremote.container.concurrent.GlobalLock.level=FINE
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.json
index fb0245696..e9a9438f6 100644
--- a/manager/src/web/shared/locales/en/or.json
+++ b/manager/src/web/shared/locales/en/or.json
@@ -94,6 +94,7 @@
"twilight_morning_civil": "Morning twilight",
"twilight_evening_civil": "Evening twilight",
"rulesEditorAddCondition": "Add condition",
+ "rulesEditorAddAttribute": "Add attribute",
"rulesEditorAddGroup": "Add group",
"rulesEditorAddAction": "Add action",
"sortBy": "Sort by",
diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.json
index 7908d857d..cf7b0c056 100644
--- a/manager/src/web/shared/locales/nl/or.json
+++ b/manager/src/web/shared/locales/nl/or.json
@@ -94,6 +94,7 @@
"twilight_morning_civil": "Ochtendschemering",
"twilight_evening_civil": "Avondschemering",
"rulesEditorAddCondition": "Voeg voorwaarde toe",
+ "rulesEditorAddAttribute": "Voeg attribute toe",
"rulesEditorAddGroup": "Groep",
"rulesEditorAddAction": "Voeg actie toe",
"sortBy": "Sorteren op",
diff --git a/test/src/test/resources/org/openremote/test/rules/Geofence.json b/test/src/test/resources/org/openremote/test/rules/Geofence.json
deleted file mode 100644
index 242ddae75..000000000
--- a/test/src/test/resources/org/openremote/test/rules/Geofence.json
+++ /dev/null
@@ -1,76 +0,0 @@
-{
- "rules": [
- {
- "name": "De Kuip",
- "when": {
- "operator": "OR",
- "groups": [
- {
- "operator": "AND",
- "items": [
- {
- "assets": {
- "types": [
- "ConsoleAsset"
- ],
- "attributes": {
- "items": [
- {
- "name": {
- "predicateType": "string",
- "match": "EXACT",
- "value": "location"
- },
- "value": {
- "predicateType": "radial",
- "negated": false,
- "radius": 100,
- "lat": 51.8938569,
- "lng": 4.5219983
- }
- }
- ]
- }
- }
- }
- ]
- }
- ]
- },
- "then": [
- {
- "action": "notification",
- "notification": {
- "name": "De Kuip",
- "message": {
- "type": "push",
- "title": "De Kuip",
- "body": "De thuis van Feyenoord",
- "action": {
- "url": "https://www.feyenoord.nl"
- },
- "buttons": [
- {
- "title": "Open in app",
- "action": {
- "url": "https://www.feyenoord.nl"
- }
- },
- {
- "title": "Open in browser",
- "action": {
- "url": "https://www.feyenoord.nl",
- "openInBrowser": true
- }
- }
- ]
- }
- }
- }
- ],
- "reset": {
- "timer": "1m"
- }
- }
- ]
-}
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts
index 8e261328f..1e49817df 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts
@@ -31,6 +31,7 @@ import {OrAttributeInputChangedEvent} from "@openremote/or-attribute-input";
import "./modals/or-rule-radial-modal";
import { ifDefined } from "lit/directives/if-defined.js";
import {when} from 'lit/directives/when.js';
+import {getWhenTypesMenu} from "./or-rule-condition";
// language=CSS
const style = css`
@@ -44,7 +45,7 @@ const style = css`
.attribute-group {
flex-grow: 1;
display: flex;
- align-items: center;
+ align-items: start;
flex-direction: row;
flex-wrap: wrap;
}
@@ -56,6 +57,37 @@ const style = css`
.attribute-group > * {
margin: 10px 3px 6px 3px;
}
+ .attributes {
+ flex: 1 1 min-content;
+ display: flex;
+ flex-direction: column;
+ row-gap: 10px;
+ }
+ or-icon.small {
+ --or-icon-width: 14px;
+ --or-icon-height: 14px;
+ }
+ .attribute {
+ display: flex;
+ align-items: center;
+ }
+ .attribute > div {
+ display: flex;
+ flex-direction: row;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px;
+ }
+ .attribute > div > * {
+ min-width: 200px;
+ }
+ .button-clear {
+ margin-left: auto;
+ }
+ .attribute:hover .button-clear {
+ visibility: visible;
+ }
+
.invalidLabel {
display: flex;
align-items: center;
@@ -187,8 +219,8 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
const operators = attributeName ? this.getOperators(assetDescriptor, descriptors ? descriptors[0] : undefined, descriptors ? descriptors[1] : undefined, attribute, attributeName) : [];
return html`
- <or-mwc-input type="${InputType.SELECT}" class="min-width" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setAttributeName(attributePredicate, e.detail.value)}" .readonly="${this.readonly || false}" .options="${attributes}" .value="${attributeName}" .label="${i18next.t("attribute")}"></or-mwc-input>
- ${attributeName ? html`<or-mwc-input type="${InputType.SELECT}" class="min-width" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setOperator(assetDescriptor, attribute, attributeName, attributePredicate, e.detail.value)}" .readonly="${this.readonly || false}" .options="${operators}" .value="${operator}" .label="${i18next.t("operator")}"></or-mwc-input>` : ``}
+ <or-mwc-input type="${InputType.SELECT}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setAttributeName(attributePredicate, e.detail.value)}" .readonly="${this.readonly || false}" .options="${attributes}" .value="${attributeName}" .label="${i18next.t("attribute")}"></or-mwc-input>
+ ${attributeName ? html`<or-mwc-input type="${InputType.SELECT}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setOperator(assetDescriptor, attribute, attributeName, attributePredicate, e.detail.value)}" .readonly="${this.readonly || false}" .options="${operators}" .value="${operator}" .label="${i18next.t("operator")}"></or-mwc-input>` : ``}
${attributePredicate ? this.attributePredicateValueEditorTemplate(assetDescriptor, asset, attributePredicate) : ``}
`;
}
@@ -212,7 +244,7 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
switch (valuePredicate.predicateType) {
case "string":
- return html`<or-attribute-input class="min-width" @or-attribute-input-changed="${(ev: OrAttributeInputChangedEvent) => this.setValuePredicateProperty(valuePredicate, "value", ev.detail.value)}" .customProvider="${this.config?.inputProvider}" .label="" .assetType="${assetType}" .attributeDescriptor="${descriptors[0]}" .attributeValueDescriptor="${descriptors[1]}" .value="${value}" .readonly="${this.readonly || false}" .fullWidth="${true}"></or-attribute-input>`;
+ return html`<or-attribute-input @or-attribute-input-changed="${(ev: OrAttributeInputChangedEvent) => this.setValuePredicateProperty(valuePredicate, "value", ev.detail.value)}" .customProvider="${this.config?.inputProvider}" .label="${i18next.t("value")}" .assetType="${assetType}" .attributeDescriptor="${descriptors[0]}" .attributeValueDescriptor="${descriptors[1]}" .value="${value}" .readonly="${this.readonly || false}" .fullWidth="${true}"></or-attribute-input>`;
case "boolean":
return html ``; // Handled by the operator IS_TRUE or IS_FALSE
case "datetime":
@@ -326,19 +358,32 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
}
}
}
+
+ const showAddAttribute = !this.readonly && (!this.config || !this.config.controls || this.config.controls.hideWhenAddAttribute !== true);
+
return html`
<or-mwc-input id="idSelect" class="min-width filledSelect" type="${InputType.SELECT}" .readonly="${this.readonly || false}" .label="${i18next.t("asset")}"
.options="${idOptions}" .value="${idValue}" .searchProvider="${searchProvider}"
@or-mwc-input-changed="${(e: OrInputChangedEvent) => { this._assetId = (e.detail.value); this.refresh(); }}"
></or-mwc-input>
- ${this.query.attributes && this.query.attributes.items ? this.query.attributes.items.map((attributePredicate) => {
- return html`
- ${this.attributePredicateEditorTemplate(assetTypeInfo, idValue !== "*" ? this._assets!.find((asset) => asset.id === idValue) : undefined, attributePredicate)}
- ${showRemoveAttribute ? html`
- <button class="button-clear" @click="${() => this.removeAttributePredicate(this.query!.attributes!, attributePredicate)}"><or-icon icon="close-circle"></or-icon></input>
- ` : ``}
- `;
- }) : ``}
+ <div class="attributes">
+ ${this.query.attributes && this.query.attributes.items ? this.query.attributes.items.map((attributePredicate, index) => {
+ return html`
+ ${index > 0 ? html`<or-icon class="small" icon="ampersand"></or-icon>` : ``}
+ <div class="attribute">
+ <div>
+ ${this.attributePredicateEditorTemplate(assetTypeInfo, idValue !== "*" ? this._assets!.find((asset) => asset.id === idValue) : undefined, attributePredicate)}
+ </div>
+ ${showRemoveAttribute ? html`
+ <button class="button-clear" @click="${() => this.removeAttributePredicate(this.query!.attributes!, attributePredicate)}"><or-icon icon="close-circle"></or-icon></input>
+ </div>` : ``}
+ `;
+ }) : ``}
+ ${showAddAttribute ? html`
+ <or-mwc-input class="plus-button" type="${InputType.BUTTON}" icon="plus"
+ .label="${i18next.t("rulesEditorAddAttribute")}" @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.addAttributePredicate(this.query!.attributes!)}"></or-mwc-input>
+ `: ``}
+ </div>
`;
})}
</div>
diff --git a/yarn.lock b/yarn.lock
index 8b207ef08..304b3371c 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5719,9 +5719,9 @@ __metadata:
linkType: hard
"http-cache-semantics@npm:^4.1.0":
- version: 4.1.0
- resolution: "http-cache-semantics@npm:4.1.0"
- checksum: 974de94a81c5474be07f269f9fd8383e92ebb5a448208223bfb39e172a9dbc26feff250192ecc23b9593b3f92098e010406b0f24bd4d588d631f80214648ed42
+ version: 4.1.1
+ resolution: "http-cache-semantics@npm:4.1.1"
+ checksum: 83ac0bc60b17a3a36f9953e7be55e5c8f41acc61b22583060e8dedc9dd5e3607c823a88d0926f9150e571f90946835c7fe150732801010845c72cd8bbff1a236
languageName: node
linkType: hard