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
First implementation of edge gateway attribute event rate limiting (#1353)
Rich Turner4e5f87e939c9
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.javaindex 90b4e61ea..a7702c62b 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java@@ -1408,7 +1408,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicnew AttributeEvent(asset,newAttribute,- getClass().getName(),+ getClass().getSimpleName(),newAttribute.getValue().orElse(null),newAttribute.getTimestamp().orElse(0L),newAttribute.getValue().orElse(null),@@ -1437,7 +1437,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic)).forEach(obsoleteAttribute ->clientEventService.publishEvent(- new AttributeEvent(asset, obsoleteAttribute, getClass().getName(), null, timerService.getCurrentTimeMillis(), null, 0L)+ new AttributeEvent(asset, obsoleteAttribute, getClass().getSimpleName(), null, timerService.getCurrentTimeMillis(), null, 0L).setDeleted(true)));}@@ -1480,7 +1480,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicAttributeMap deletedAttributes = asset.getAttributes();deletedAttributes.forEach(obsoleteAttribute ->clientEventService.publishEvent(- new AttributeEvent(asset, obsoleteAttribute, getClass().getName(), null, timerService.getCurrentTimeMillis(), null, 0L)+ new AttributeEvent(asset, obsoleteAttribute, getClass().getSimpleName(), null, timerService.getCurrentTimeMillis(), null, 0L).setDeleted(true)));}diff --git a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java b/manager/src/main/java/org/openremote/manager/event/ClientEventService.javaindex b01b3ec8b..7c7efbb65 100644--- a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java+++ b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java@@ -484,7 +484,7 @@ public class ClientEventService extends RouteBuilder implements ContainerService* This handles basic authorisation checks for clients that want to subscribe to events in the system*/public boolean authorizeEventSubscription(String realm, AuthContext authContext, EventSubscription<?> subscription) {- boolean authorized = eventSubscriptionAuthorizers.stream()+ boolean authorized = subscription.isInternal() || eventSubscriptionAuthorizers.stream().anyMatch(authorizer -> authorizer.authorise(realm, authContext, subscription));if (!authorized) {diff --git a/manager/src/main/java/org/openremote/manager/gateway/GatewayClientResourceImpl.java b/manager/src/main/java/org/openremote/manager/gateway/GatewayClientResourceImpl.javaindex cb9f4e10d..8c3b2191a 100644--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayClientResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayClientResourceImpl.java@@ -28,6 +28,8 @@ import org.openremote.model.gateway.GatewayConnection;import org.openremote.model.http.RequestParams;import jakarta.ws.rs.WebApplicationException;+import org.openremote.model.query.filter.RealmPredicate;+import java.util.Collections;import java.util.List;@@ -82,10 +84,19 @@ public class GatewayClientResourceImpl extends ManagerWebResource implements Gat@Overridepublic void setConnection(RequestParams requestParams, String realm, GatewayConnection connection) {+ if (!realm.equals(getAuthenticatedRealmName()) && !isSuperUser()) {+ throw new WebApplicationException("Gateway connection can only be created in the users realm", FORBIDDEN);+ }+connection.setLocalRealm(realm);- if (!connection.getLocalRealm().equals(getAuthenticatedRealmName()) && !isSuperUser()) {- throw new WebApplicationException(FORBIDDEN);+ // Force realm of any attribute filters+ if (connection.getAttributeFilters() != null) {+ connection.getAttributeFilters().forEach(filter -> {+ if (filter.getMatcher() != null) {+ filter.getMatcher().realm(new RealmPredicate(realm));+ }+ });}try {diff --git a/manager/src/main/java/org/openremote/manager/gateway/GatewayClientService.java b/manager/src/main/java/org/openremote/manager/gateway/GatewayClientService.javaindex 952d6f8e7..515d76418 100644--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayClientService.java+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayClientService.java@@ -22,8 +22,10 @@ package org.openremote.manager.gateway;import io.netty.channel.ChannelHandler;import org.apache.camel.builder.RouteBuilder;import org.apache.http.client.utils.URIBuilder;+import org.openremote.manager.rules.AssetQueryPredicate;import org.openremote.model.Constants;import org.openremote.model.Container;+import org.openremote.model.attribute.AttributeRef;import org.openremote.model.auth.OAuthClientCredentialsGrant;import org.openremote.agent.protocol.io.AbstractNettyIOClient;import org.openremote.model.ContainerService;@@ -39,19 +41,18 @@ import org.openremote.manager.web.ManagerWebService;import org.openremote.model.asset.*;import org.openremote.model.asset.agent.ConnectionStatus;import org.openremote.model.attribute.AttributeEvent;-import org.openremote.model.event.shared.EventRequestResponseWrapper;-import org.openremote.model.event.shared.EventSubscription;-import org.openremote.model.event.shared.SharedEvent;-import org.openremote.model.event.shared.RealmFilter;+import org.openremote.model.event.shared.*;import org.openremote.model.gateway.*;import org.openremote.model.query.AssetQuery;import org.openremote.model.query.filter.RealmPredicate;import org.openremote.model.syslog.SyslogCategory;+import org.openremote.model.util.Pair;import org.openremote.model.util.TextUtil;import org.openremote.model.util.ValueUtil;import java.io.File;import java.util.*;+import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ScheduledExecutorService;import java.util.logging.Level;import java.util.logging.Logger;@@ -81,6 +82,7 @@ public class GatewayClientService extends RouteBuilder implements ContainerServiprotected final Map<String, GatewayConnection> connectionRealmMap = new HashMap<>();protected final Map<String, GatewayIOClient> clientRealmMap = new HashMap<>();protected GatewayTunnelFactory gatewayTunnelFactory;+ protected Map<String, Map<AttributeRef, Long>> clientAttributeTimestamps = new ConcurrentHashMap<>();@Overridepublic void init(Container container) throws Exception {@@ -188,14 +190,22 @@ public class GatewayClientService extends RouteBuilder implements ContainerServiif (client != null) {destroyGatewayClient(connection, client);}+ if (connection.isDisabled()) {+ clientAttributeTimestamps.remove(connection.getLocalRealm());+ }case CREATE:connectionRealmMap.put(connection.getLocalRealm(), connection);if (!connection.isDisabled()) {clientRealmMap.put(connection.getLocalRealm(), createGatewayClient(connection));}+ // Gateway connection can become disabled if an error occurred during creation+ if (!connection.isDisabled()) {+ clientAttributeTimestamps.put(connection.getLocalRealm(), new ConcurrentHashMap<>());+ }break;case DELETE:connectionRealmMap.remove(connection.getLocalRealm());+ clientAttributeTimestamps.remove(connection.getLocalRealm());client = clientRealmMap.remove(connection.getLocalRealm());if (client != null) {destroyGatewayClient(connection, client);@@ -256,7 +266,7 @@ public class GatewayClientService extends RouteBuilder implements ContainerServiclientEventService.addInternalSubscription(getClientSessionKey(connection)+"Attribute",AttributeEvent.class,- new AssetFilter<AttributeEvent>().setRealm(connection.getLocalRealm()),+ getOutboundAttribueEventFilter(connection),attributeEvent ->sendCentralManagerMessage(connection.getLocalRealm(), messageToString(SharedEvent.MESSAGE_PREFIX, attributeEvent)));@@ -272,6 +282,89 @@ public class GatewayClientService extends RouteBuilder implements ContainerServireturn null;}+ protected EventFilter<AttributeEvent> getOutboundAttribueEventFilter(GatewayConnection gatewayConnection) {++ // Convert filters to predicates for efficiency+ List<Pair<AssetQueryPredicate, GatewayAttributeFilter>> predicatesWithFilters;+ if (gatewayConnection.getAttributeFilters() != null && !gatewayConnection.getAttributeFilters().isEmpty()) {+ predicatesWithFilters = gatewayConnection.getAttributeFilters()+ .stream()+ .map(filter -> {+ AssetQueryPredicate predicate = filter.getMatcher() != null ? new AssetQueryPredicate(timerService, assetStorageService, filter.getMatcher()) : null;+ return new Pair<>(predicate, filter);+ })+ .toList();+ } else {+ predicatesWithFilters = Collections.emptyList();+ }++ return ev -> {+ if (!gatewayConnection.getLocalRealm().equals(ev.getRealm())) {+ return null;+ }++ // Allow attribute events that came from the central manager to be returned+ if (getClass().getName().equals(ev.getSource())) {+ return ev;+ }++ boolean allowEvent = predicatesWithFilters.stream()+ .filter(predicateWithFilter -> {+ if (predicateWithFilter.key == null) {+ // Match all+ return true;+ }+ return predicateWithFilter.key.test(ev);+ })+ .findFirst()+ .map(predicatesWithFilter -> {+ GatewayAttributeFilter filter = predicatesWithFilter.value;+ if (filter.isAllow()) {+ return true;+ }+ if (filter.getSkipAlways() != null && filter.getSkipAlways()) {+ return false;+ }+ if (filter.getValueChange() != null && filter.getValueChange()) {+ if (!Objects.equals(ev.getValue(), ev.getOldValue())) {+ LOG.finest(() -> "Gateway client for '" + gatewayConnection.getLocalRealm() + "' value change has allowed attribute event: " + ev.getRef());+ return true;+ }+ }+ if (filter.getDelta() != null) {+ if (Number.class.isAssignableFrom(ev.getTypeClass())) {+ double delta = filter.getDelta();+ double value = ev.getValue(Double.class).orElse(0d);+ double oldValue = ev.getOldValue(Double.class).orElse(0d);+ if (Math.abs(value - oldValue) > Math.abs(delta)) {+ LOG.finest(() -> "Gateway client for '" + gatewayConnection.getLocalRealm() + "' delta setting has allowed attribute event: " + ev.getRef());+ return true;+ }+ }+ }+ if (filter.getDurationParsed().isPresent()) {+ boolean allow = filter.getDurationParsed().map(durationMillis -> {+ Map<AttributeRef, Long> attributeTimestamps = clientAttributeTimestamps.get(gatewayConnection.getLocalRealm());+ Long lastSendMillis = attributeTimestamps.get(ev.getRef());+ if (lastSendMillis == null || timerService.getCurrentTimeMillis() - lastSendMillis > durationMillis) {+ LOG.finest(() -> "Gateway client for '" + gatewayConnection.getLocalRealm() + "' duration setting has allowed attribute event: " + ev.getRef());+ attributeTimestamps.put(ev.getRef(), timerService.getCurrentTimeMillis());+ return true;+ }+ LOG.finest(() -> "Gateway client for '" + gatewayConnection.getLocalRealm() + "' duration setting has blocked attribute event: " + ev.getRef());+ return false;+ }).orElse(true);++ return allow;+ }++ return false;+ }).orElse(true);++ return allowEvent ? ev : null;+ };+ }+protected void destroyGatewayClient(GatewayConnection connection, GatewayIOClient client) {if (client == null) {return;diff --git a/manager/src/main/resources/org/openremote/manager/setup/database/V20240711_01__UpdateGatewayConnection.sql b/manager/src/main/resources/org/openremote/manager/setup/database/V20240711_01__UpdateGatewayConnection.sqlnew file mode 100644index 000000000..2bc0e0a5d--- /dev/null+++ b/manager/src/main/resources/org/openremote/manager/setup/database/V20240711_01__UpdateGatewayConnection.sql@@ -0,0 +1,2 @@+ALTER TABLE GATEWAY_CONNECTION+ ADD ATTRIBUTE_FILTERS jsonb;diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.jsonindex 64ab253f5..95ea54597 100644--- a/manager/src/web/shared/locales/en/or.json+++ b/manager/src/web/shared/locales/en/or.json@@ -321,7 +321,14 @@"JAVASCRIPT": "JavaScript"},"gatewayConnection": "Manager interconnect",- "gateway": "Manager interconnect",+ "gateway": {+ "": "Manager interconnect",+ "limit_sharing_is_custom_error": "An advanced data limiting configuration is set. To modify click the JSON button. Clear it to use the fields below.",+ "limit_sharing_attribute": "Limit data sharing by asset type attributes",+ "limit_sharing_attribute_selected": "attributes selected",+ "limit_sharing_rate": "Limit the rate of how often attribute value updates are shared",+ "limit_sharing_rate_suffix": "minutes interval"+ },"gatewayTunnel": "Gateway tunnel","gatewayTunnels": {"": "Gateway tunnels",@@ -346,6 +353,7 @@"tunnels": "tunnels","tunnel": "tunnel","connectionDetails": "CONNECTION DETAILS",+ "dataSharing": "Data sharing","secured": "Secured","clientSecret": "Client secret","clientId": "Client ID",diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.jsonindex 9a25b15aa..e74ed9bb8 100644--- a/manager/src/web/shared/locales/nl/or.json+++ b/manager/src/web/shared/locales/nl/or.json@@ -321,7 +321,14 @@"JAVASCRIPT": "JavaScript"},"gatewayConnection": "Manager interconnect",- "gateway": "Manager interconnect",+ "gateway": {+ "": "Manager interconnect",+ "limit_sharing_is_custom_error": "Een aangepaste configuratie is ingesteld. Klik op JSON om deze aan te passen. Maak de configuratie leeg om de velden hieronder te gebruiken.",+ "limit_sharing_attribute": "Begrens welke attributen van asset types worden gedeeld",+ "limit_sharing_types_selected": "asset types geselecteerd",+ "limit_sharing_rate": "Begrens hoevaak attribuut waarden worden bijgewerkt",+ "limit_sharing_rate_suffix": "minuten interval"+ },"gatewayTunnel": "Gateway tunnel","gatewayTunnels": {"": "Gateway tunnels",diff --git a/model/src/main/java/org/openremote/model/asset/AssetFilter.java b/model/src/main/java/org/openremote/model/asset/AssetFilter.javaindex 928508a87..b1207bd5a 100644--- a/model/src/main/java/org/openremote/model/asset/AssetFilter.java+++ b/model/src/main/java/org/openremote/model/asset/AssetFilter.java@@ -34,7 +34,7 @@ import java.util.stream.Collectors;// TODO: Merge this with AssetQuery and use AssetQueryPredicate to resolve@TsIgnoreTypeParams-public class AssetFilter<T extends SharedEvent & AssetInfo> extends EventFilter<T> {+public class AssetFilter<T extends SharedEvent & AssetInfo> implements EventFilter<T> {public static final String FILTER_TYPE = "asset";@@ -166,11 +166,6 @@ public class AssetFilter<T extends SharedEvent & AssetInfo> extends EventFilter<this.internal = internal;}- @Override- public String getFilterType() {- return FILTER_TYPE;- }-@SuppressWarnings("unchecked")@Overridepublic T apply(T event) {@@ -184,6 +179,12 @@ public class AssetFilter<T extends SharedEvent & AssetInfo> extends EventFilter<}}+ if (!TextUtil.isNullOrEmpty(realm)) {+ if (!realm.equals(event.getRealm())) {+ return null;+ }+ }+if (restrictedEvents) {if (event instanceof AttributeEvent attributeEvent) {if (!attributeEvent.getMetaValue(MetaItemType.ACCESS_RESTRICTED_READ).orElse(false)) {@@ -240,12 +241,6 @@ public class AssetFilter<T extends SharedEvent & AssetInfo> extends EventFilter<}}- if (!TextUtil.isNullOrEmpty(realm)) {- if (!realm.equals(event.getRealm())) {- return null;- }- }-if (filterAttributesBy != null) {// Filter attributes before doing name matchAssetEvent assetEvent = (AssetEvent) event;diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.javaindex 86b262d19..5d815799e 100644--- a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java@@ -19,8 +19,9 @@*/package org.openremote.model.attribute;-import com.fasterxml.jackson.annotation.*;-import com.fasterxml.jackson.databind.annotation.JsonDeserialize;+import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonIgnore;+import com.fasterxml.jackson.annotation.JsonView;import com.fasterxml.jackson.databind.annotation.JsonSerialize;import jakarta.annotation.Nonnull;import org.openremote.model.asset.Asset;@@ -157,6 +158,10 @@ public class AttributeEvent extends SharedEvent implements AttributeInfo {return Optional.ofNullable(oldValue);}+ public <U> Optional<U> getOldValue(@Nonnull Class<U> valueType) {+ return ValueUtil.getValueCoerced(oldValue, valueType);+ }+public long getOldValueTimestamp() {return oldValueTimestamp;}@@ -257,7 +262,7 @@ public class AttributeEvent extends SharedEvent implements AttributeInfo {}@Override- public Optional getValue(@Nonnull Class valueType) {+ public <U> Optional<U> getValue(@Nonnull Class<U> valueType) {return ValueUtil.getValueCoerced(value, valueType);}diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeInfo.java b/model/src/main/java/org/openremote/model/attribute/AttributeInfo.javaindex 1b8222a8b..ad82a182c 100644--- a/model/src/main/java/org/openremote/model/attribute/AttributeInfo.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeInfo.java@@ -1,7 +1,9 @@package org.openremote.model.attribute;import com.fasterxml.jackson.annotation.JsonProperty;+import jakarta.annotation.Nonnull;import org.openremote.model.asset.AssetInfo;+import org.openremote.model.util.ValueUtil;import org.openremote.model.value.MetaHolder;import org.openremote.model.value.NameValueHolder;@@ -26,6 +28,8 @@ public interface AttributeInfo extends AssetInfo, NameValueHolder<Object>, MetaH@JsonPropertyOptional<Object> getOldValue();+ <U> Optional<U> getOldValue(@Nonnull Class<U> valueType);+@JsonPropertylong getOldValueTimestamp();}diff --git a/model/src/main/java/org/openremote/model/event/shared/EventFilter.java b/model/src/main/java/org/openremote/model/event/shared/EventFilter.javaindex 76c55289c..7f5559dfb 100644--- a/model/src/main/java/org/openremote/model/event/shared/EventFilter.java+++ b/model/src/main/java/org/openremote/model/event/shared/EventFilter.java@@ -44,13 +44,11 @@ import org.openremote.model.syslog.SyslogEvent;setterVisibility= JsonAutoDetect.Visibility.NONE,isGetterVisibility= JsonAutoDetect.Visibility.NONE)-public abstract class EventFilter<E extends SharedEvent> {-- public abstract String getFilterType();-+@FunctionalInterface+public interface EventFilter<E extends SharedEvent> {/**** @return the event or a filtered copy of it if the filter matches; do not modify the supplied event.*/- public abstract E apply(E event);+ E apply(E event);}diff --git a/model/src/main/java/org/openremote/model/event/shared/RealmFilter.java b/model/src/main/java/org/openremote/model/event/shared/RealmFilter.javaindex c22e8ac59..7aa0f5785 100644--- a/model/src/main/java/org/openremote/model/event/shared/RealmFilter.java+++ b/model/src/main/java/org/openremote/model/event/shared/RealmFilter.java@@ -19,7 +19,7 @@*/package org.openremote.model.event.shared;-public class RealmFilter<T extends RealmScopedEvent> extends EventFilter<T> {+public class RealmFilter<T extends RealmScopedEvent> implements EventFilter<T> {public static final String FILTER_TYPE = "realm";@@ -36,11 +36,6 @@ public class RealmFilter<T extends RealmScopedEvent> extends EventFilter<T> {return name;}- @Override- public String getFilterType() {- return FILTER_TYPE;- }-@Overridepublic T apply(T event) {return getName().equals(event.getRealm()) ? event : null;diff --git a/model/src/main/java/org/openremote/model/gateway/GatewayAttributeFilter.java b/model/src/main/java/org/openremote/model/gateway/GatewayAttributeFilter.javanew file mode 100644index 000000000..ca6161ca3--- /dev/null+++ b/model/src/main/java/org/openremote/model/gateway/GatewayAttributeFilter.java@@ -0,0 +1,115 @@+package org.openremote.model.gateway;++import org.openremote.model.attribute.Attribute;+import org.openremote.model.query.AssetQuery;+import org.openremote.model.util.TextUtil;+import org.openremote.model.util.TimeUtil;++import java.util.Optional;++/**+ * A filter for limiting when {@link org.openremote.model.attribute.AttributeEvent}s are sent to the central instance.+ * Consists of an {@link AssetQuery} and various options for limiting the frequency of sending matched events. The+ * options are OR'ed except for {@link #skipAlways}. A null {@link #matcher} indicates a match all. If {@link #delta},+ * {@link #duration}, {@link #valueChange} and {@link #skipAlways} are all null then any event that matches will not be+ * filtered. This facilitates an allow exclusion for one or more attributes provided the allow filter is before any other+ * filter that would also match the event.+ */+public class GatewayAttributeFilter {+ /**+ * The {@link AssetQuery} used to determine if an {@link org.openremote.model.attribute.AttributeEvent} matches+ * this filter+ */+ protected AssetQuery matcher;+ /**+ * ISO8601 duration expression (e.g. PT1H)+ */+ protected String duration;+ /**+ * A delta change required only applicable when {@link Attribute#getTypeClass()} is assignable from {@link Number}+ */+ protected Double delta;+ /**+ * Send whenever the value changes in accordance with {@link Object#equals}+ */+ protected Boolean valueChange;+ /**+ * Do not send any updates for matching attributes+ */+ protected Boolean skipAlways;++ @SuppressWarnings("OptionalUsedAsFieldOrParameterType")+ protected Optional<Long> durationParsedMillis;++ public AssetQuery getMatcher() {+ return matcher;+ }++ public GatewayAttributeFilter setMatcher(AssetQuery matcher) {+ this.matcher = matcher;+ return this;+ }++ public String getDuration() {+ return duration;+ }++ public Optional<Long> getDurationParsed() {+ if (durationParsedMillis == null) {+ durationParsedMillis = Optional.empty();+ try {+ durationParsedMillis = Optional.of(TimeUtil.parseTimeDuration(duration));+ } catch (RuntimeException e) {+ durationParsedMillis = Optional.empty();+ }+ }+ return durationParsedMillis;+ }++ public GatewayAttributeFilter setDuration(String duration) {+ this.duration = duration;+ return this;+ }++ public Double getDelta() {+ return delta;+ }++ public GatewayAttributeFilter setDelta(Double delta) {+ this.delta = delta;+ return this;+ }++ public Boolean getValueChange() {+ return valueChange;+ }++ public GatewayAttributeFilter setValueChange(Boolean valueChange) {+ this.valueChange = valueChange;+ return this;+ }++ public Boolean getSkipAlways() {+ return skipAlways;+ }++ public GatewayAttributeFilter setSkipAlways(Boolean skipAlways) {+ this.skipAlways = skipAlways;+ return this;+ }++ public boolean isAllow() {+ return (skipAlways == null || !skipAlways) && (valueChange == null || !valueChange) && delta == null && TextUtil.isNullOrEmpty(duration);+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "matcher=" + matcher ++ ", duration='" + duration + '\'' ++ ", delta=" + delta ++ ", valueChange=" + valueChange ++ ", skipAlways=" + skipAlways ++ '}';+ }+}diff --git a/model/src/main/java/org/openremote/model/gateway/GatewayConnection.java b/model/src/main/java/org/openremote/model/gateway/GatewayConnection.javaindex 6953debf0..6e1d9b8b5 100644--- a/model/src/main/java/org/openremote/model/gateway/GatewayConnection.java+++ b/model/src/main/java/org/openremote/model/gateway/GatewayConnection.java@@ -30,6 +30,10 @@ import jakarta.validation.constraints.Max;import jakarta.validation.constraints.Min;import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.Size;+import org.hibernate.annotations.JdbcTypeCode;+import org.hibernate.type.SqlTypes;++import java.util.List;@Entity@Table(name = "GATEWAY_CONNECTION")@@ -68,22 +72,32 @@ public class GatewayConnection {@Column(name = "DISABLED")protected boolean disabled;+ /**+ * Filters are applied in order and the first to match the {@link org.openremote.model.attribute.AttributeEvent} will+ * be applied; if a catch all filter is to be used (i.e. {@link GatewayAttributeFilter#matcher == null}) it should+ * be last in the list.+ */+ @Column(name = "ATTRIBUTE_FILTERS")+ @JdbcTypeCode(SqlTypes.JSON)+ protected List<GatewayAttributeFilter> attributeFilters;+/*** For JPA*/- GatewayConnection() {+ protected GatewayConnection() {}@JsonCreatorpublic GatewayConnection(- @JsonProperty("localRealm") String localRealm,- @JsonProperty("host") String host,- @JsonProperty("port") Integer port,- @JsonProperty("realm") String realm,- @JsonProperty("clientId") String clientId,- @JsonProperty("clientSecret") String clientSecret,- @JsonProperty("secured") Boolean secured,- @JsonProperty("disabled") boolean disabled) {+ String localRealm,+ String host,+ Integer port,+ String realm,+ String clientId,+ String clientSecret,+ Boolean secured,+ List<GatewayAttributeFilter> attributeFilters,+ boolean disabled) {this.localRealm = localRealm;this.host = host;this.port = port;@@ -92,6 +106,7 @@ public class GatewayConnection {this.clientSecret = clientSecret;this.secured = secured;this.disabled = disabled;+ this.attributeFilters = attributeFilters;}public GatewayConnection(@@ -164,7 +179,7 @@ public class GatewayConnection {}public boolean isSecured() {- return secured == null ? true : secured;+ return secured == null || secured;}public void setSecured(boolean secured) {@@ -179,6 +194,15 @@ public class GatewayConnection {this.disabled = disabled;}+ public List<GatewayAttributeFilter> getAttributeFilters() {+ return attributeFilters;+ }++ public GatewayConnection setAttributeFilters(List<GatewayAttributeFilter> attributeFilters) {+ this.attributeFilters = attributeFilters;+ return this;+ }+@Overridepublic String toString() {return getClass().getSimpleName() + "{" +@@ -187,6 +211,7 @@ public class GatewayConnection {", port=" + port +", realm='" + realm + '\'' +", secured=" + secured ++ ", attributeFilters=" + attributeFilters +", disabled=" + disabled +'}';}diff --git a/model/src/main/java/org/openremote/model/syslog/SyslogEvent.java b/model/src/main/java/org/openremote/model/syslog/SyslogEvent.javaindex 9f6751cbb..5bf27d03b 100644--- a/model/src/main/java/org/openremote/model/syslog/SyslogEvent.java+++ b/model/src/main/java/org/openremote/model/syslog/SyslogEvent.java@@ -32,7 +32,7 @@ import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;@Table(name = "SYSLOG_EVENT")public class SyslogEvent extends SharedEvent {- static public class LevelCategoryFilter extends EventFilter<SyslogEvent> {+ static public class LevelCategoryFilter implements EventFilter<SyslogEvent> {public static final String FILTER_TYPE = "level-category-filter";@@ -48,11 +48,6 @@ public class SyslogEvent extends SharedEvent {this.categories = categories != null ? Arrays.asList(categories) : Collections.EMPTY_LIST;}- @Override- public String getFilterType() {- return FILTER_TYPE;- }-public List<SyslogCategory> getCategories() {return categories;}diff --git a/setup/src/integration/java/org/openremote/setup/integration/ManagerTestSetup.java b/setup/src/integration/java/org/openremote/setup/integration/ManagerTestSetup.javaindex 3fc1b01b8..fde2ec2fa 100644--- a/setup/src/integration/java/org/openremote/setup/integration/ManagerTestSetup.java+++ b/setup/src/integration/java/org/openremote/setup/integration/ManagerTestSetup.java@@ -91,6 +91,8 @@ public class ManagerTestSetup extends ManagerSetup {public String smartCityServiceAgentId;public String area1Id;public String microphone1Id;+ public String peopleCounter1AssetId;+ public String peopleCounter2AssetId;public String peopleCounter3AssetId;public String electricityOptimisationAssetId;public String electricityConsumerAssetId;@@ -637,6 +639,7 @@ public class ManagerTestSetup extends ManagerSetup {PeopleCounterAsset peopleCounter1Asset = createDemoPeopleCounterAsset("PeopleCounter 1", assetArea1, new GeoJSONPoint(5.477126, 51.439137), () ->new SimulatorAgentLink(smartCityServiceAgentId));peopleCounter1Asset = assetStorageService.merge(peopleCounter1Asset);+ peopleCounter1AssetId = peopleCounter1Asset.getId();Asset<?> microphone1Asset = createDemoMicrophoneAsset("Microphone 1", assetArea1, new GeoJSONPoint(5.478092, 51.438655), () ->new SimulatorAgentLink(smartCityServiceAgentId));@@ -668,6 +671,7 @@ public class ManagerTestSetup extends ManagerSetup {Asset<?> peopleCounter2Asset = createDemoPeopleCounterAsset("PeopleCounter 2", assetArea2, new GeoJSONPoint(5.473686, 51.438603), () ->new SimulatorAgentLink(smartCityServiceAgentId));peopleCounter2Asset = assetStorageService.merge(peopleCounter2Asset);+ peopleCounter2AssetId = peopleCounter2Asset.getId();Asset<?> environment2Asset = createDemoEnvironmentAsset("Environment 2", assetArea2, new GeoJSONPoint(5.473552, 51.438412), () ->new SimulatorAgentLink(smartCityServiceAgentId));diff --git a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovyindex d93f80c98..5341b8c2c 100644--- a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy+++ b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy@@ -30,10 +30,7 @@ import org.openremote.model.attribute.MetaItemimport org.openremote.model.auth.OAuthClientCredentialsGrantimport org.openremote.model.event.shared.EventRequestResponseWrapperimport org.openremote.model.event.shared.SharedEvent-import org.openremote.model.gateway.GatewayClientResource-import org.openremote.model.gateway.GatewayConnection-import org.openremote.model.gateway.GatewayTunnelInfo-import org.openremote.model.gateway.GatewayTunnelStartRequestEvent+import org.openremote.model.gateway.*import org.openremote.model.geo.GeoJSONPointimport org.openremote.model.query.AssetQueryimport org.openremote.model.query.filter.RealmPredicate@@ -751,7 +748,9 @@ class GatewayTest extends Specification implements ManagerContainerTrait {given: "the container environment is started"def conditions = new PollingConditions(timeout: 15, delay: 0.2)+ def delayedConditions = new PollingConditions(initialDelay: 1, delay: 1, timeout: 10)def container = startContainer(defaultConfig(), defaultServices())+ def timerService = container.getService(TimerService.class)def assetProcessingService = container.getService(AssetProcessingService.class)def assetStorageService = container.getService(AssetStorageService.class)def gatewayService = container.getService(GatewayService.class)@@ -796,12 +795,14 @@ class GatewayTest extends Specification implements ManagerContainerTrait {when: "a gateway client connection is created to connect the city realm to the gateway in the building realm"def gatewayConnection = new GatewayConnection(+ managerTestSetup.realmCityName,"127.0.0.1",serverPort,managerTestSetup.realmBuildingName,gateway.getClientId().orElse(""),gateway.getClientSecret().orElse(""),false,+ null,false)gatewayClientResource.setConnection(null, managerTestSetup.realmCityName, gatewayConnection)@@ -909,7 +910,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {when: "we subscribe to attribute events"List<AttributeEvent> attributeEvents = []- clientEventService.addInternalSubscription(AttributeEvent.class, null, {attributeEvent ->+ def subscriptionId = clientEventService.addInternalSubscription(AttributeEvent.class, null, {attributeEvent ->attributeEvents.add(attributeEvent)})@@ -934,6 +935,106 @@ class GatewayTest extends Specification implements ManagerContainerTrait {conditions.eventually {assert assetStorageService.find(mapAssetId(gateway.id, managerTestSetup.microphone1Id, false)) == null}++ when: "attribute filters are added to the gateway connection and persisted"+ gatewayConnection.setAttributeFilters([+ new GatewayAttributeFilter().setMatcher(new AssetQuery().types(LightAsset.class)).setValueChange(true),+ new GatewayAttributeFilter().setMatcher(new AssetQuery().types(PeopleCounterAsset.class).attributeNames(PeopleCounterAsset.COUNT_TOTAL.name, PeopleCounterAsset.COUNT_GROWTH_PER_MINUTE.name))+ .setDelta(1.5d),+ new GatewayAttributeFilter().setMatcher(new AssetQuery().names("Microphone 2")).setDuration("PT1M"),+ // Ignore any other attribute+ new GatewayAttributeFilter().setSkipAlways(true)+ ])+ gatewayClientResource.setConnection(null, managerTestSetup.realmCityName, gatewayConnection)+ def oldClient = gatewayClientService.clientRealmMap.get(gatewayConnection.getLocalRealm())++ then: "the gateway connection IO client should have been replaced and synchronisation should be complete"+ conditions.eventually {+ assert gatewayClientService.clientRealmMap.get(gatewayConnection.getLocalRealm()) != null+ assert gatewayClientService.clientRealmMap.get(gatewayConnection.getLocalRealm()) != oldClient+ GatewayConnector connector = gatewayService.gatewayConnectorMap.get(gateway.getId().toLowerCase(Locale.ROOT))+ assert connector != null+ assert !connector.initialSyncInProgress+ }++ when: "an attribute event occurs in the edge gateway realm for an attribute with a value change filter and the attribute value has not changed"+ attributeEvents.clear()+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.light2Id, LightAsset.ON_OFF, true))++ then: "the value should not have been forwarded to the central instance"+ delayedConditions.eventually {+ assert attributeEvents.any{it.id == managerTestSetup.light2Id && it.name == LightAsset.ON_OFF.name && it.value.orElse(false)}+ assert !attributeEvents.any{it.id == mapAssetId(gateway.id, managerTestSetup.light2Id, false) && it.name == LightAsset.ON_OFF.name}+ }++ when: "an attribute event occurs in the edge gateway realm for an attribute with a value change filter and the attribute value has changed"+ attributeEvents.clear()+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.light2Id, LightAsset.ON_OFF, false))++ then: "the value should now have been forwarded to the central instance"+ conditions.eventually {+ def mirroredLight2 = assetStorageService.find(mapAssetId(gateway.id, managerTestSetup.light2Id, false))+ assert mirroredLight2 != null+ assert !mirroredLight2.getAttribute(LightAsset.ON_OFF).flatMap{it.getValue()}.orElse(true)+ assert attributeEvents.any{it.id == managerTestSetup.light2Id && it.name == LightAsset.ON_OFF.name && !it.value.orElse(true)}+ assert attributeEvents.any{it.id == mapAssetId(gateway.id, managerTestSetup.light2Id, false) && it.name == LightAsset.ON_OFF.name && !it.value.orElse(true)}+ }++ when: "an attribute event occurs in the edge gateway realm for an attribute with a delta filter and the attribute value has changed by less than delta"+ attributeEvents.clear()+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.peopleCounter1AssetId, PeopleCounterAsset.COUNT_GROWTH_PER_MINUTE, 0.5d))++ then: "the value should not have been forwarded to the central instance"+ delayedConditions.eventually {+ assert attributeEvents.any{it.id == managerTestSetup.peopleCounter1AssetId && it.name == PeopleCounterAsset.COUNT_GROWTH_PER_MINUTE.name && Math.abs(it.value.orElse(0d) - 0.5d) < 0.000001d}+ assert !attributeEvents.any{it.id == mapAssetId(gateway.id, managerTestSetup.peopleCounter1AssetId, false) && it.name == PeopleCounterAsset.COUNT_GROWTH_PER_MINUTE.name}+ }++ when: "an attribute event occurs in the edge gateway realm for an attribute with a delta filter and the attribute value has changed by more than delta"+ attributeEvents.clear()+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.peopleCounter1AssetId, PeopleCounterAsset.COUNT_GROWTH_PER_MINUTE, -1.1d))++ then: "the value should have been forwarded to the central instance"+ conditions.eventually {+ assert attributeEvents.any{it.id == managerTestSetup.peopleCounter1AssetId && it.name == PeopleCounterAsset.COUNT_GROWTH_PER_MINUTE.name && Math.abs(it.value.orElse(0d) + 1.1d) < 0.000001d}+ assert attributeEvents.any{it.id == mapAssetId(gateway.id, managerTestSetup.peopleCounter1AssetId, false) && it.name == PeopleCounterAsset.COUNT_GROWTH_PER_MINUTE.name && Math.abs(it.value.orElse(0d) + 1.1d) < 0.000001d}+ }++ when: "an attribute event occurs in the edge gateway realm for an attribute with a duration filter"+ attributeEvents.clear()+ microphone2 = assetStorageService.find(microphone2.id)+ assetProcessingService.sendAttributeEvent(new AttributeEvent(microphone2.id, MicrophoneAsset.SOUND_LEVEL, 50d))++ then: "the value should have been forwarded to the central instance (as no prior value has been sent since the filter was created)"+ conditions.eventually {+ assert attributeEvents.any{it.id == microphone2.id && it.name == MicrophoneAsset.SOUND_LEVEL.name && Math.abs(it.value.orElse(0d) - 50d) < 0.000001d}+ assert attributeEvents.any{it.id == mapAssetId(gateway.id, microphone2.id, false) && it.name == MicrophoneAsset.SOUND_LEVEL.name && Math.abs(it.value.orElse(0d) - 50d) < 0.000001d}+ }++ when: "an attribute event occurs in the edge gateway realm for the same attribute before the duration filter has elapsed"+ attributeEvents.clear()+ assetProcessingService.sendAttributeEvent(new AttributeEvent(microphone2.id, MicrophoneAsset.SOUND_LEVEL, 60d))++ then: "the value should not have been forwarded to the central instance"+ delayedConditions.eventually {+ assert attributeEvents.any{it.id == microphone2.id && it.name == MicrophoneAsset.SOUND_LEVEL.name && Math.abs(it.value.orElse(0d) - 60d) < 0.000001d}+ assert !attributeEvents.any{it.id == mapAssetId(gateway.id, microphone2.id, false) && it.name == MicrophoneAsset.SOUND_LEVEL.name}+ }++ when: "an attribute event occurs in the edge gateway realm for an attribute that matches the catch all and skip filter"+ attributeEvents.clear()+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.area1Id, Asset.NOTES, "Some test notes"))++ then: "the value should not have been forwarded to the central instance"+ delayedConditions.eventually {+ assert attributeEvents.any{it.id == managerTestSetup.area1Id && it.name == Asset.NOTES.name && "Some test notes".equals(it.value.orElse(null))}+ assert !attributeEvents.any{it.id == mapAssetId(gateway.id, managerTestSetup.area1Id, false) && it.name == Asset.NOTES.name}+ }++ cleanup: "Remove any subscriptions created"+ if (clientEventService != null && subscriptionId != null) {+ clientEventService.cancelInternalSubscription(subscriptionId)+ }}/**diff --git a/ui/app/manager/src/pages/page-gateway.ts b/ui/app/manager/src/pages/page-gateway.tsindex 912c08824..0910eefd9 100644--- a/ui/app/manager/src/pages/page-gateway.ts+++ b/ui/app/manager/src/pages/page-gateway.ts@@ -1,13 +1,21 @@import {css, html, PropertyValues, TemplateResult, unsafeCSS} from "lit";-import {customElement, property, state} from "lit/decorators.js";+import {customElement, state} from "lit/decorators.js";import i18next from "i18next";+import {when} from "lit/directives/when.js";+import {until} from "lit/directives/until.js";+import {createRef, Ref, ref} from "lit/directives/ref.js";import "@openremote/or-components/or-panel";-import {ClientRole, ConnectionStatus, GatewayConnection, GatewayConnectionStatusEvent} from "@openremote/model";-import manager, {DefaultColor1, DefaultColor3, OREvent} from "@openremote/core";+import {OrMwcDialog, showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";+import {AttributeDescriptor, AttributePredicate, ClientRole, ConnectionStatus, GatewayAttributeFilter, GatewayConnection, GatewayConnectionStatusEvent, LogicGroupOperator} from "@openremote/model";+import manager, {DefaultColor1, DefaultColor3} from "@openremote/core";import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";-import {Page, PageProvider} from "@openremote/or-app";-import {AppStateKeyed} from "@openremote/or-app";+import {AppStateKeyed, Page, PageProvider} from "@openremote/or-app";import {Store} from "@reduxjs/toolkit";+import {OrAssetTypeAttributePicker, OrAssetTypeAttributePickerPickedEvent} from "@openremote/or-attribute-picker";+import "@openremote/or-components/or-ace-editor";+import moment from "moment";+import {OrAceEditor} from "@openremote/or-components/or-ace-editor";+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";export function pageGatewayProvider(store: Store<AppStateKeyed>): PageProvider<AppStateKeyed> {return {@@ -48,68 +56,106 @@ export class PageGateway extends Page<AppStateKeyed> {flex-direction: column;overflow: auto;}-+#title {margin: 20px auto 0;+ max-width: 1360px;+ width: 100%;+ display: flex;+ justify-content: space-between;+ align-items: center;+ color: var(--or-app-color3, ${unsafeCSS(DefaultColor3)});+ }++ #title div {+ display: flex;+ align-items: center;+ }++ #title > div > span {font-size: 18px;font-weight: bold;- max-width: 1000px;- min-width: 600px;- color: var(--or-app-color3, ${unsafeCSS(DefaultColor3)});}- #title > or-icon {+ #title > div > or-icon {margin-right: 10px;margin-left: 14px;}-+or-panel {position: relative;- max-width: 1000px;- min-width: 600px;+ max-width: 1360px;+ width: 100%;margin: 20px auto;}-- #status {++ .gateway-status-header {position: absolute;- top: 15px;+ top: 18px;right: 25px;- font-weight: bold;+ font-weight: bold;+ display: flex;}-- #fields {++ #gateway-content {display: flex;- flex-direction: column;+ flex-wrap: wrap;padding: 10px;+ gap: 40px;}-- #fields > or-mwc-input {- margin: 10px 0;- width: 100%;++ .gateway-column {+ flex: 1;+ flex-basis: 45%;+ min-width: 350px;+ display: flex;+ flex-direction: column;+ gap: 20px;}-- #buttons {- text-align: right;++ .gateway-sharing-control {+ display: flex;+ flex-direction: column;+ gap: 10px;}-- #buttons > or-mwc-input {- margin: 10px;++ .gateway-sharing-control-child {+ margin-left: 20px;+ display: flex;+ gap: 10px;+ align-items: center;+ }++ #gateway-footer {+ margin-top: 40px;+ display: flex;+ justify-content: space-between;}+ #gateway-footer > div {+ display: flex;+ gap: 10px;+ }+@media only screen and (max-width: 780px){- :host {+ :host {--or-panel-border-radius: 0;}or-panel {width: 100%;min-width: auto;}-#title {width: 100%;min-width: auto;}}++ @media only screen and (max-width: 1200px) {+ #gateway-content {+ gap: 20px;+ }+ }`;}@@ -125,20 +171,17 @@ export class PageGateway extends Page<AppStateKeyed> {@state()protected _connectionStatus?: ConnectionStatus;- @property()+ @state()protected _dirty = false;protected _readonly = false;protected _eventSubscriptionId?: string;+ protected _intervalMin?: number;get name(): string {return "gatewayConnection";}- constructor(store: Store<AppStateKeyed>) {- super(store);- }-connectedCallback() {super.connectedCallback();this._readonly = !manager.hasRole(ClientRole.WRITE_ADMIN);@@ -150,6 +193,25 @@ export class PageGateway extends Page<AppStateKeyed> {this._unsubscribeEvents();}+ public stateChanged(state: AppStateKeyed) {+ this.realm = state.app.realm;+ }++ protected async _subscribeEvents() {+ if (manager.events) {+ this._eventSubscriptionId = await manager.events.subscribe<GatewayConnectionStatusEvent>({+ eventType: "gateway-connection-status"+ }, (ev) => this._onEvent(ev));+ }+ }++ protected _unsubscribeEvents() {+ if (this._eventSubscriptionId) {+ manager.events!.unsubscribe(this._eventSubscriptionId);+ this._eventSubscriptionId = undefined;+ }+ }+public shouldUpdate(_changedProperties: PropertyValues): boolean {if (_changedProperties.has("realm")) {@@ -169,52 +231,248 @@ export class PageGateway extends Page<AppStateKeyed> {protected render(): TemplateResult | void {const connection = this._connection;+ const disabled = this._loading || this._readonly;return html`<div id="wrapper">- <div id="title">- <or-icon icon="cloud"></or-icon>${i18next.t("gatewayConnection")}++ ${until(this._getTitleTemplate(connection, this._connectionStatus, disabled))}++ <or-panel ?disabled="${disabled}" .heading="${i18next.t("connectionDetails")}">+ ${when(this._connectionStatus, () => html`+ <div class="gateway-status-header">+ <or-translate value="status" style="font-weight: normal;"></or-translate>:+ <span style="margin-left: 10px;">${this._connectionStatus}</span>+ </div>+ `)}+ ${until(this._getContentTemplate(() => this._getSettingsColumns(connection, disabled)))}+ </or-panel>++ <or-panel ?disabled="${disabled}" heading="${i18next.t("dataSharing")}">+ <div class="gateway-status-header">+ <or-mwc-input .type="${InputType.BUTTON}" label="JSON" outlined icon="pencil"+ @or-mwc-input-changed="${() => this._openConnectionJSONEditor(connection)}"+ ></or-mwc-input>+ </div>+ ${until(this._getContentTemplate(() => this._getDataSharingColumns(connection, this._isDataSharingCustom(connection), disabled)))}+ </or-panel>+ </div>+ `;+ }++ protected async _getTitleTemplate(connection?: GatewayConnection, _status?: ConnectionStatus, disabled = true): Promise<TemplateResult> {+ return html`+ <div id="title">+ <div>+ <or-icon icon="cloud"></or-icon>+ <span>${i18next.t("gatewayConnection")}</span></div>- <or-panel ?disabled="${this._loading}" .heading="${i18next.t("connectionDetails")}">- <div id="status">- ${this._connectionStatus}+ <div style="gap: 20px;">+ <div>+ <or-translate value="enabled"></or-translate>+ <or-mwc-input .type="${InputType.SWITCH}" .value="${!connection.disabled}" ?disabled="${disabled}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("disabled", !e.detail.value)}"+ ></or-mwc-input></div>- <div id="fields">- <or-mwc-input .label="${i18next.t("host")}" .type="${InputType.TEXT}" ?disabled="${this._loading || this._readonly}" .value="${connection ? connection.host : ""}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("host", e.detail.value)}"></or-mwc-input>- <or-mwc-input .label="${i18next.t("port")}" .type="${InputType.NUMBER}" ?disabled="${this._loading || this._readonly}" min="1" max="65536" step="1" .value="${connection ? connection.port : undefined}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("port", e.detail.value)}"></or-mwc-input>- <or-mwc-input .label="${i18next.t("realm")}" .type="${InputType.TEXT}" ?disabled="${this._loading || this._readonly}" .value="${connection ? connection.realm : ""}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("realm", e.detail.value)}"></or-mwc-input>- <or-mwc-input .label="${i18next.t("clientId")}" .type="${InputType.TEXT}" ?disabled="${this._loading || this._readonly}" .value="${connection ? connection.clientId : ""}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("clientId", e.detail.value)}"></or-mwc-input>- <or-mwc-input .label="${i18next.t("clientSecret")}" .type="${InputType.TEXT}" ?disabled="${this._loading || this._readonly}" .value="${connection ? connection.clientSecret : ""}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("clientSecret", e.detail.value)}"></or-mwc-input>- <or-mwc-input .label="${i18next.t("secured")}" .type="${InputType.SWITCH}" ?disabled="${this._loading || this._readonly}" .value="${connection ? connection.secured : false}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("secured", e.detail.value)}"></or-mwc-input>- <or-mwc-input .label="${i18next.t("disabled")}" .type="${InputType.SWITCH}" ?disabled="${this._loading || this._readonly}" .value="${connection ? connection.disabled : false}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("disabled", e.detail.value)}"></or-mwc-input>+ <or-mwc-input label="save" ?disabled="${!this._dirty || disabled}" .type="${InputType.BUTTON}" raised @click="${() => this._save()}"></or-mwc-input>+ </div>+ </div>+ `;+ }++ protected async _getContentTemplate(content: () => Promise<TemplateResult>): Promise<TemplateResult> {+ return html`+ <div id="gateway-content">+ ${until(content(), html`<or-loading></or-loading>`)}+ </div>+ `;+ }++ /**+ * Returns an HTML {@link TemplateResult} with controls to configure the {@link GatewayConnection}.+ * Settings like host, port, realm, clientId, clientSecret, and more.+ */+ protected async _getSettingsColumns(connection: GatewayConnection, disabled = true): Promise<TemplateResult> {+ return html`+ <div id="gateway-column-1" class="gateway-column">+ <div></div>+ <or-mwc-input .label="${i18next.t("host")}" .type="${InputType.TEXT}" ?disabled="${disabled}" .value="${connection?.host}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("host", e.detail.value)}"+ ></or-mwc-input>+ <or-mwc-input .label="${i18next.t("port")}" .type="${InputType.NUMBER}"+ ?disabled="${disabled}" min="1" max="65536" step="1" .value="${connection?.port}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("port", e.detail.value)}"+ ></or-mwc-input>+ <or-mwc-input .label="${i18next.t("realm")}" .type="${InputType.TEXT}" ?disabled="${disabled}" .value="${connection?.realm}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("realm", e.detail.value)}"+ ></or-mwc-input>+ <div></div>+ </div>+ <div id="gateway-column-2" class="gateway-column">+ <div></div>+ <or-mwc-input .label="${i18next.t("clientId")}" .type="${InputType.TEXT}" ?disabled="${disabled}" .value="${connection?.clientId}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("clientId", e.detail.value)}"+ ></or-mwc-input>+ <or-mwc-input .label="${i18next.t("clientSecret")}" .type="${InputType.TEXT}" ?disabled="${disabled}" .value="${connection?.clientSecret}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("clientSecret", e.detail.value)}"+ ></or-mwc-input>+ <or-mwc-input .label="${i18next.t("secured")}" .type="${InputType.CHECKBOX}" style="height: 56px;" ?disabled="${disabled}" .value="${connection?.secured || false}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._setConnectionProperty("secured", e.detail.value)}"+ ></or-mwc-input>+ </div>+ `;+ }++ /**+ * Returns an HTML {@link TemplateResult} with the controls to limit the rate of {@link AttributeEvent}s in the {@link GatewayConnection}.+ * Think of an attribute picker, and a number control to define the interval (in minutes).+ */+ protected async _getDataSharingColumns(connection: GatewayConnection, isCustom = false, disabled = true): Promise<TemplateResult> {+ const controlsDisabled = isCustom || disabled;+ const filterChecked = connection.attributeFilters?.find(filter => filter.matcher !== undefined);+ const filterDisabled = controlsDisabled || !filterChecked;+ const interval = connection.attributeFilters?.[0]?.duration ? moment.duration(connection.attributeFilters[0].duration).get("minutes") : undefined;+ const intervalDisabled = controlsDisabled || interval === undefined;+ const attrAmountArr = connection.attributeFilters?.map(filter => filter.matcher?.attributes?.items?.length || 0);+ const attrAmount = attrAmountArr?.reduce((a, b) => a + b, 0);+ const controlStyling = controlsDisabled ? "--mdc-theme-text-primary-on-background: lightgray; color: lightgray" : undefined;+ return html`+ <div id="gateway-column-3" class="gateway-column">+ ${when(isCustom, () => html`+ <or-translate value="gateway.limit_sharing_is_custom_error"></or-translate>+ `, () => html`+ <div></div>+ `)}+ <div class="gateway-sharing-control" style="${controlStyling}">+ <or-mwc-input .label="${i18next.t("gateway.limit_sharing_attribute")}" .type="${InputType.CHECKBOX}"+ ?disabled="${controlsDisabled}" .value="${controlsDisabled ? undefined : filterChecked}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._onLimitAttributesCheck(e)}"+ ></or-mwc-input>+ <div class="gateway-sharing-control-child">+ <or-mwc-input .type="${InputType.BUTTON}" raised ?disabled="${filterDisabled}"+ label="${attrAmount || 0} ${i18next.t("gateway.limit_sharing_attribute_selected")}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._onLimitAttributesButtonClick(e)}"+ ></or-mwc-input></div>- <div id="buttons">- <or-mwc-input label="reset" ?disabled="${!this._dirty || this._loading || this._readonly}" .type="${InputType.BUTTON}" raised @click="${() => this._reset()}"></or-mwc-input>- <or-mwc-input label="delete" ?disabled="${this._loading || this._readonly}" .type="${InputType.BUTTON}" raised @click="${() => this._delete()}"></or-mwc-input>- <or-mwc-input label="save" ?disabled="${!this._dirty || this._loading || this._readonly}" .type="${InputType.BUTTON}" raised @click="${() => this._save()}"></or-mwc-input>+ </div>+ <div class="gateway-sharing-control" style="${controlStyling}">+ <or-mwc-input .label="${i18next.t("gateway.limit_sharing_rate")}" .type="${InputType.CHECKBOX}"+ ?disabled="${controlsDisabled}" .value="${!controlsDisabled && interval !== undefined}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._onAttributesIntervalUpdate(e.detail.value ? 1 : undefined)}"+ ></or-mwc-input>+ <div class="gateway-sharing-control-child">+ <or-mwc-input .type="${InputType.NUMBER}" compact outlined ?disabled="${intervalDisabled}" .value="${controlsDisabled ? undefined : interval}" style="width: 84px;"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._onAttributesIntervalUpdate(e.detail.value)}"+ ></or-mwc-input>+ <or-translate value="gateway.limit_sharing_rate_suffix"></or-translate></div>- </or-panel>+ </div>+ <div></div></div>`;}- public stateChanged(state: AppStateKeyed) {- this.realm = state.app.realm;+ /**+ * HTML callback for checking the "limit data sharing by attribute" checkbox.+ */+ protected _onLimitAttributesCheck(ev: OrInputChangedEvent) {+ const attrFilters = this._connection.attributeFilters;+ if(attrFilters?.length > 0) {+ attrFilters?.forEach(filter => {+ if(ev.detail.value) {+ filter.matcher = {};+ } else {+ delete filter.matcher;+ delete filter.skipAlways;+ }+ });+ this._updateAttributeFilters(attrFilters);+ } else {+ this._updateAttributeFilters(ev.detail.value ? [{ matcher: {} }] as GatewayAttributeFilter[] : undefined);+ }}- protected async _subscribeEvents() {- if (manager.events) {- this._eventSubscriptionId = await manager.events.subscribe<GatewayConnectionStatusEvent>({- eventType: "gateway-connection-status"- }, (ev) => this._onEvent(ev));+ /**+ * HTML callback for clicking the "X attributes selected" button.+ * Here, it opens an attribute picker and handles its callback.+ */+ protected _onLimitAttributesButtonClick(_ev: OrInputChangedEvent) {+ const selectedAttrs = this._getAttrDescriptorMapFromFilters(this._connection.attributeFilters);+ const dialog = showDialog(new OrAssetTypeAttributePicker().setSelectedAttributes(selectedAttrs).setMultiSelect(true));+ dialog.addEventListener(OrAssetTypeAttributePickerPickedEvent.NAME, (ev) => {++ const duration = this._intervalMin ? moment.duration(this._intervalMin, "minutes") : undefined;+ const assetTypeMap = ev.detail as Map<string, AttributeDescriptor[]>;+ const filters = Array.from(assetTypeMap.entries()).map(entry => ({+ duration: duration?.toISOString(),+ matcher: {+ types: [entry[0]] as string[],+ attributes: {+ items: entry[1]?.map((attr: AttributeDescriptor) => ({+ name: {predicateType: "string", value: attr.name}+ })),+ operator: LogicGroupOperator.OR+ }+ }+ }) as GatewayAttributeFilter);++ // By default, all other attributes will NOT be shared (they're blocked)+ filters.push({+ skipAlways: true+ });++ this._updateAttributeFilters(filters);+ });+ }++ /**+ * HTML callback for when the "minutes interval between attribute values" updates.+ */+ protected _onAttributesIntervalUpdate(value?: number) {+ this._intervalMin = value;+ const duration = this._intervalMin ? moment.duration(this._intervalMin, "minutes") : undefined;+ const attributeFilters = this._connection.attributeFilters || [];+ if(attributeFilters.length > 0) {++ // Update all existing filters to the new duration+ attributeFilters?.forEach(filter => {+ if(duration) {+ const isSkipAlwaysItem = Object.keys(filter).length === 1 && filter.skipAlways;+ if(!isSkipAlwaysItem) {+ filter.duration = duration?.toISOString();+ }+ } else {+ delete filter.duration;+ }+ });++ } else if(duration) {+ attributeFilters.push({+ duration: duration.toISOString()+ });}+ this._updateAttributeFilters(attributeFilters);}- protected _unsubscribeEvents() {- if (this._eventSubscriptionId) {- manager.events!.unsubscribe(this._eventSubscriptionId);- this._eventSubscriptionId = undefined;+ /**+ * Internal function that returns a map of {@link AttributeDescriptor[]}, based on the {@link GatewayAttributeFilter}.+ * Mainly meant for the attribute-picker, as it uses AttributeDescriptors instead.+ */+ protected _getAttrDescriptorMapFromFilters(attrFilters?: GatewayAttributeFilter[]): Map<string, AttributeDescriptor[]> {+ const map = new Map<string, AttributeDescriptor[]>();+ if(!attrFilters) {+ return map;}+ attrFilters.forEach(filter => {+ const key = filter.matcher?.types?.[0] as string | undefined;+ const values = (filter.matcher?.attributes?.items as any)?.map((attr: AttributePredicate) => ({+ name: attr.name.value+ }));+ if(key && values) {+ map.set(key, values);+ }+ });+ return map;}protected async _loadData() {@@ -228,9 +486,16 @@ export class PageGateway extends Page<AppStateKeyed> {this._connectionStatus = statusResponse.data;}+ protected _updateAttributeFilters(attributeFilters: GatewayAttributeFilter[]) {+ attributeFilters = attributeFilters?.filter(filter => Object.keys(filter).length > 0); // clear unset keys and empty objects+ console.debug("Updating attributeFilters to", attributeFilters);+ this._setConnectionProperty("attributeFilters", attributeFilters);+ }+protected _setConnectionProperty(propName: string, value: any) {this._connection[propName] = value;this._dirty = true;+ this.requestUpdate("_connection");}protected _reset() {@@ -266,4 +531,71 @@ export class PageGateway extends Page<AppStateKeyed> {this._connectionStatus = event.connectionStatus;}}++ /**+ * Internal function that verifies whether the Data Sharing configuration is customized through JSON.+ * (by checking the amount of object keys, and whether it is valid at all)+ */+ protected _isDataSharingCustom(connection?: GatewayConnection): boolean {+ if(!connection?.attributeFilters) {+ return false;+ }+ if(!Array.isArray(connection.attributeFilters)) {+ return true;+ }+ if(connection.attributeFilters.length === 0) {+ return false;+ }+ const excludedKeys = ['duration', 'matcher', 'durationParsedMillis', 'skipAlways'];+ const customFilter = connection.attributeFilters.find(filter => {+ const unknownKeys = Object.keys(filter).filter(key => !excludedKeys.includes(key));+ return unknownKeys.length > 0;+ });+ return !!customFilter;++ }++ /**+ * Function that opens the JSON editor for customizing the {@link GatewayAttributeFilter}s manually.+ * The changed are only applied once the save button is pressed.+ */+ protected _openConnectionJSONEditor(connection?: GatewayConnection) {+ const editorRef: Ref<OrAceEditor> = createRef();+ showDialog(new OrMwcDialog()+ .setHeading("JSON Editor")+ .setContent(html`+ <or-ace-editor ${ref(editorRef)} .value="${connection?.attributeFilters}" style="height: 60vh; width: 1024px;"></or-ace-editor>+ `)+ .setActions([+ { actionName: "cancel", content: "cancel"},+ { actionName: "save", content: "save", action: () => {+ const editor = editorRef.value;+ if(!editor.validate()) {+ console.warn("JSON was not valid");+ showSnackbar(undefined, i18next.t('errorOccurred'));+ return;+ }+ try {+ let parsed: GatewayAttributeFilter[] | undefined;+ if(editor.getValue().length > 0) {++ parsed = JSON.parse(editor.getValue());++ // Verify if the JSON is an array. If so; simply accept the format.+ if(!Array.isArray(parsed)) {+ console.warn("Could not parse JSON to GatewayAttributeFilter[], as it was not an array.");+ showSnackbar(undefined, i18next.t("errorOccurred"));+ return;+ }+ }+ this._updateAttributeFilters(parsed);++ } catch (e) {+ console.error(e);+ showSnackbar(undefined, i18next.t("errorOccurred"));+ }+ }}+ ])+ );+ }}diff --git a/ui/component/or-attribute-picker/src/asset-attribute-picker.ts b/ui/component/or-attribute-picker/src/asset-attribute-picker.tsnew file mode 100644index 000000000..423715952--- /dev/null+++ b/ui/component/or-attribute-picker/src/asset-attribute-picker.ts@@ -0,0 +1,194 @@+import {customElement, property, state} from "lit/decorators.js";+import {AttributePicker, AttributePickerPickedEvent} from "./attribute-picker";+import {Asset, Attribute, AttributeRef, WellknownMetaItems} from "@openremote/model";+import manager, {DefaultColor5, Util} from "@openremote/core";+import {OrAssetTree, OrAssetTreeSelectionEvent} from "@openremote/or-asset-tree";+import {html, unsafeCSS} from "lit";+import {InputType} from "@openremote/or-mwc-components/or-mwc-input";+import {when} from "lit/directives/when.js";+import {until} from "lit/directives/until.js";++/**+ * Custom Event that is dispatched upon closing the dialog.+ * Contains a list of {@link AttributeRef} of the selected attributes.+ */+export class OrAssetAttributePickerPickedEvent extends AttributePickerPickedEvent {++ public static readonly NAME = "or-asset-attribute-picker-picked";++ constructor(attrRefs: AttributeRef[]) {+ super(OrAssetAttributePickerPickedEvent.NAME, {+ bubbles: true,+ composed: true,+ detail: attrRefs+ });+ }+}++declare global {+ export interface HTMLElementEventMap {+ [OrAssetAttributePickerPickedEvent.NAME]: OrAssetAttributePickerPickedEvent;+ }+}++/**+ * The "Attribute Picker" component using the {@link OrAssetTree} component for selecting assets and its attributes.+ *+ * @attribute {object} attributeFilter - Callback method for consumers to filter the attribute list shown. Returning true will make the attribute visible, returning false hides it.+ */+@customElement("or-asset-attribute-picker")+export class OrAssetAttributePicker extends AttributePicker {++ @property()+ public attributeFilter?: (attribute: Attribute<any>) => boolean;++ @state()+ protected _assetAttributes?: (Attribute<any>)[];++ public selectedAssets: string[] = [];+ public selectedAttributes: AttributeRef[] = [];++ protected _asset?: Asset;+++ public setAttributeFilter(attributeFilter: ((attribute: Attribute<any>) => boolean) | undefined): this {+ this.attributeFilter = attributeFilter;+ return this;+ }++ public setSelectedAssets(selectedAssets: string[]): this {+ this.selectedAssets = selectedAssets;+ this._updateDialogContent();+ return this;+ }++ public setSelectedAttributes(selectedAttributes: AttributeRef[]): this {+ this.selectedAttributes = selectedAttributes;+ if(this.addBtn) {+ this.addBtn.disabled = this.selectedAttributes.length === 0;+ }+ return this;+ }++ protected _setDialogActions(): void {+ this.actions = [+ {+ actionName: "cancel",+ content: "cancel"+ },+ {+ actionName: "add",+ content: html`+ <or-mwc-input id="add-btn" class="button" label="add" .type="${InputType.BUTTON}"></or-mwc-input>`,+ action: () => {+ if (!this.addBtn.disabled) {+ this.dispatchEvent(new OrAssetAttributePickerPickedEvent(this.selectedAttributes));+ }+ }+ }+ ];+ }++ protected _setDialogContent(): void {++ this.content = () => html`+ <div class="row" style="display: flex;height: 600px;width: 800px;border-top: 1px solid ${unsafeCSS(DefaultColor5)};">+ <div class="col" style="width: 260px;overflow: auto;border-right: 1px solid ${unsafeCSS(DefaultColor5)};">+ <or-asset-tree id="chart-asset-tree" readonly .selectedIds="${this.selectedAssets.length > 0 ? this.selectedAssets : null}"+ @or-asset-tree-selection="${(ev: OrAssetTreeSelectionEvent) => this._onAssetSelectionChanged(ev)}">+ </or-asset-tree>+ </div>+ <div class="col" style="flex: 1 1 auto;width: 260px;overflow: auto;">+ ${when(this._assetAttributes && this._assetAttributes.length > 0, () => {+ const selectedNames = this.selectedAttributes.filter(attrRef => attrRef.id === this._asset?.id).map(attrRef => attrRef.name);+ return html`+ <div class="attributes-header">+ <or-translate value="attribute_plural"></or-translate>+ </div>+ ${until(+ this._getAttributesTemplate(this._assetAttributes!, undefined, selectedNames, this.multiSelect, (attrNames) => this._onAttributesSelect(attrNames)),+ html`<or-loading></or-loading>`+ )}+ `+ }, () => html`+ <div style="display: flex;align-items: center;text-align: center;height: 100%;padding: 0 20px;">+ <span style="width:100%">+ <or-translate value="${+ (this._assetAttributes && this._assetAttributes.length === 0) ?+ ((this.showOnlyDatapointAttrs && this.showOnlyRuleStateAttrs) ? "noDatapointsOrRuleStateAttributes" :+ this.showOnlyDatapointAttrs ? "noDatapointsAttributes" :+ this.showOnlyRuleStateAttrs ? "noRuleStateAttributes" : "noAttributesToShow"+ ) : "selectAssetOnTheLeft"}">+ </or-translate>+ </span>+ </div>+ `)}+ </div>+ `;+ }+++ /**+ * Event callback function that is triggered once a user selects an asset.+ * It fetches the attributes of that specific asset, and caches these to be displayed later.+ * Also applies the filtering such as {@link showOnlyDatapointAttrs}, {@link showOnlyRuleStateAttrs} and {@link attributeFilter} if set.+ */+ protected async _onAssetSelectionChanged(event: OrAssetTreeSelectionEvent) {+ this._assetAttributes = undefined;+ if (!this.multiSelect) {+ this.selectedAttributes = [];+ }+ // Disable buttons / elements if necessary+ this.addBtn.disabled = this.selectedAttributes.length === 0;+ const assetTree = event.target as OrAssetTree;+ assetTree.disabled = true;++ let selectedAsset = event.detail.newNodes.length === 0 ? undefined : event.detail.newNodes[0].asset;+ this._asset = selectedAsset;++ if (selectedAsset) {++ // Fetch the asset in full, including all its attributes+ const assetResponse = await manager.rest.api.AssetResource.get(selectedAsset.id!);+ selectedAsset = assetResponse.data;++ if (selectedAsset) {+ this._assetAttributes = Object.values(selectedAsset.attributes!)+ .map(attr => ({...attr, id: selectedAsset!.id!}))+ .sort(Util.sortByString((attribute) => attribute.name!));++ if (this.attributeFilter) {+ this._assetAttributes = this._assetAttributes.filter((attr) => this.attributeFilter!(attr))+ }++ if (this.showOnlyDatapointAttrs && this.showOnlyRuleStateAttrs) {+ this._assetAttributes = this._assetAttributes+ .filter(e => e.meta && (e.meta[WellknownMetaItems.STOREDATAPOINTS] || e.meta[WellknownMetaItems.RULESTATE] || e.meta[WellknownMetaItems.AGENTLINK]));+ } else if (this.showOnlyDatapointAttrs) {+ this._assetAttributes = this._assetAttributes+ .filter(e => e.meta && (e.meta[WellknownMetaItems.STOREDATAPOINTS] || e.meta[WellknownMetaItems.AGENTLINK]));+ } else if (this.showOnlyRuleStateAttrs) {+ this._assetAttributes = this._assetAttributes+ .filter(e => e.meta && (e.meta[WellknownMetaItems.RULESTATE] || e.meta[WellknownMetaItems.AGENTLINK]));+ }+ }+ }+ // Enable interaction with the asset tree again+ assetTree.disabled = false;+ }+++ /**+ * HTML Callback function when the selected attributes have been updated.+ *+ * @remarks+ * The {@link attrNames} parameter contains a list of attribute names VISIBLE in the list.+ * So, selected attributes of other assets, will merge together with the new {@link attrNames}.+ */+ protected _onAttributesSelect(attrNames: string[]) {+ this.setSelectedAttributes([+ ...this.selectedAttributes.filter(attributeRef => attributeRef.id !== this._asset!.id),+ ...attrNames.map(a => ({id: this._asset?.id, name: a}))+ ]);+ }+}diff --git a/ui/component/or-attribute-picker/src/assettype-attribute-picker.ts b/ui/component/or-attribute-picker/src/assettype-attribute-picker.tsnew file mode 100644index 000000000..fa7bd70ef--- /dev/null+++ b/ui/component/or-attribute-picker/src/assettype-attribute-picker.ts@@ -0,0 +1,251 @@+import {property, state} from "lit/decorators.js";+import {AttributePicker, AttributePickerPickedEvent} from "./attribute-picker";+import {PropertyValues, html, unsafeCSS} from "lit";+import {DefaultColor5, Util} from "@openremote/core";+import {when} from "lit/directives/when.js";+import {until} from "lit/directives/until.js";+import {ListItem, OrMwcListChangedEvent} from "@openremote/or-mwc-components/or-mwc-list";+import {AssetDescriptor, AssetModelUtil, AssetTypeInfo, AttributeDescriptor, WellknownMetaItems} from "@openremote/model";+import {InputType} from "@openremote/or-mwc-components/or-mwc-input";+import "./assettype-list";++/**+ * Custom Event that is dispatched upon closing the dialog.+ * Contains a map that is keyed by {@link AssetDescriptor.name}, with an array of {@link AttributeDescriptor}s of the selected attributes.+ */+export class AssetTypeAttributePickerPickedEvent extends AttributePickerPickedEvent {++ public static readonly NAME = "or-asset-type-attribute-picker-picked";++ constructor(attrDescriptors: Map<string, AttributeDescriptor[]>) {+ super(AssetTypeAttributePickerPickedEvent.NAME, {+ bubbles: true,+ composed: true,+ detail: attrDescriptors+ });+ }+}++declare global {+ export interface HTMLElementEventMap {+ [AssetTypeAttributePickerPickedEvent.NAME]: AssetTypeAttributePickerPickedEvent;+ }+}++/**+ * The "Attribute Picker" component using the {@link OrAssetTree} component for selecting assets and its attributes.+ *+ * @attribute {object} assetTypeFilter -Callback method for consumers to filter the asset type list shown. Returning true will make the asset type visible, returning false hides it.+ * @attribute {object} attributeFilter - Callback method for consumers to filter the attribute list shown. Returning true will make the attribute visible, returning false hides it.+ *+ * @remarks TODO: In the future this should be a separate component named "or-assettype-attribute-picker"+ */+export class AssetTypeAttributePicker extends AttributePicker {++ @property()+ public assetTypeFilter?: (descriptor: AssetDescriptor) => boolean;++ @property()+ public attributeFilter?: (descriptor: AttributeDescriptor) => boolean;++ public selectedAttributes: Map<string, AttributeDescriptor[]> = new Map();++ @state()+ protected _selectedAssetType?: string;++ @state()+ protected _loadedAttributeTypes?: AttributeDescriptor[];++ @state()+ protected _loadedAssetTypes?: AssetDescriptor[];++ public setSelectedAttributes(selectedAttributes: Map<string, AttributeDescriptor[]>) {+ this.selectedAttributes = selectedAttributes;+ return this;+ }++ protected willUpdate(changedProps: PropertyValues) {++ if (!this._loadedAssetTypes) {+ this._loadedAssetTypes = this._loadAssetTypes();+ }++ if (changedProps.has("_selectedAssetType")) {+ const descriptor = this._getAssetDescriptorByName(this._selectedAssetType);+ if (descriptor) {+ this._loadedAttributeTypes = this._loadAttributeTypes(descriptor);+ }+ }+ // Update UI manually+ this._updateDialogContent();+ this._updateDialogActions();++ return super.willUpdate(changedProps);+ }+++ /**+ * Function that will load and update the available asset types up for selection.+ * Also applies the filtering such as {@link assetTypeFilter} if set.+ */+ protected _loadAssetTypes(): AssetDescriptor[] {+ let assetTypes = AssetModelUtil.getAssetDescriptors();+ if (this.assetTypeFilter !== undefined) {+ assetTypes = assetTypes.filter(this.assetTypeFilter);+ }+ this._loadedAssetTypes = assetTypes;+ return assetTypes || [];+ }+++ /**+ * Function that will load and update the available attributes up for selection.+ * The {@link descriptor} parameter is usually the selected asset type.+ * Also applies the filtering such as {@link showOnlyDatapointAttrs}, {@link showOnlyRuleStateAttrs} and {@link attributeFilter} if set.+ */+ protected _loadAttributeTypes(descriptor: AssetDescriptor): AttributeDescriptor[] {+ const typeInfo: AssetTypeInfo = (AssetModelUtil.getAssetTypeInfo(descriptor) as AssetTypeInfo);+ let descriptors: AttributeDescriptor[] | undefined = typeInfo.attributeDescriptors;++ // Apply necessary filtering+ if (this.attributeFilter !== undefined) {+ descriptors = descriptors?.filter(this.attributeFilter);+ }+ if (this.showOnlyDatapointAttrs) {+ descriptors = descriptors?.filter(d => d.meta?.[WellknownMetaItems.STOREDATAPOINTS]);+ }+ if (this.showOnlyRuleStateAttrs) {+ descriptors = descriptors?.filter(d => d.meta?.[WellknownMetaItems.RULESTATE]);+ }++ this._loadedAttributeTypes = descriptors || [];+ return descriptors || [];+ }+++ /* ----------------------------- */+++ protected _setDialogContent(): void {++ const assetTypes = this._loadedAssetTypes || this._loadAssetTypes();+ const selectedTypeNames = this.selectedAttributes ? Array.from(this.selectedAttributes.keys()) : undefined;+ const assetTypeItems = this._getAssetTypeDescriptors(assetTypes, assetTypes.filter(type => !selectedTypeNames || selectedTypeNames.includes(type.name)));+ const assetDescriptor = this._getAssetDescriptorByName(this._selectedAssetType);+ const attributeTypes = (this._loadedAttributeTypes || (assetDescriptor ? this._loadAttributeTypes(assetDescriptor) : undefined))?.sort(Util.sortByString(item => item.name));++ this.content = () => html`+ <div class="row" style="display: flex;height: 600px;width: 800px;border-top: 1px solid ${unsafeCSS(DefaultColor5)};">+ <div class="col" style="width: 320px;overflow: auto;border-right: 1px solid ${unsafeCSS(DefaultColor5)};">+ <asset-type-list .listItems="${assetTypeItems}" style="--or-icon-fill: #000000;" @or-mwc-list-changed="${(evt: OrMwcListChangedEvent) => {+ if (evt.detail.length === 1) this._onAssetTypeItemClick(evt.detail[0] as ListItem);+ }}"+ ></asset-type-list>+ </div>+ <div class="col" style="flex: 1 1 auto;width: 320px;overflow: auto;">+ ${when(attributeTypes && attributeTypes.length > 0, () => {+ const selectedAttrNames = this._selectedAssetType ? this.selectedAttributes.get(this._selectedAssetType)?.map(desc => desc.name) : undefined;+ return html`+ <div class="attributes-header">+ <or-translate value="attribute_plural"></or-translate>+ </div>+ ${until(+ this._getAttributesTemplate(undefined, attributeTypes, selectedAttrNames, this.multiSelect, (attrNames) => this._onAttributesSelect(attrNames)),+ html`<or-loading></or-loading>`+ )}+ `;+ }, () => html`+ <div style="display: flex;align-items: center;text-align: center;height: 100%;padding: 0 20px;">+ <span style="width:100%">+ <or-translate value="${+ (attributeTypes && attributeTypes.length === 0) ?+ ((this.showOnlyDatapointAttrs && this.showOnlyRuleStateAttrs) ? "noDatapointsOrRuleStateAttributes" :+ this.showOnlyDatapointAttrs ? "noDatapointsAttributes" :+ this.showOnlyRuleStateAttrs ? "noRuleStateAttributes" : "noAttributesToShow"+ ) : "selectAssetTypeOnTheLeft"}">+ </or-translate>+ </span>+ </div>+ `)}+ </div>+ </div>+ `;+ }+++ protected _setDialogActions(): void {+ this.actions = [+ {+ actionName: "cancel",+ content: "cancel"+ },+ {+ actionName: "add",+ content: html`+ <or-mwc-input id="add-btn" class="button" label="add" .type="${InputType.BUTTON}"></or-mwc-input>`,+ action: () => {+ if (!this.addBtn.disabled) {+ this.dispatchEvent(new AssetTypeAttributePickerPickedEvent(this.selectedAttributes));+ }+ }+ }+ ];+ }+++ /**+ * HTML Callback function when the selected asset type has been updated.+ */+ protected _onAssetTypeItemClick(listItem: ListItem) {+ this._selectedAssetType = (listItem.data as AssetDescriptor).name;+ }+++ /**+ * HTML callback function when the selected attributes have been updated.+ */+ protected _onAttributesSelect(attrNames: string[]) {+ if (!this._selectedAssetType) {+ console.warn("Could not select attribute, since no asset type seemed to be selected.");+ return;+ }+ if (!this._loadedAttributeTypes) {+ console.warn("Could not select attribute, since the attribute list seems to be empty?");+ return;+ }+ this.selectedAttributes.set(this._selectedAssetType, this._loadedAttributeTypes?.filter(desc => attrNames.includes(desc.name)));+ }+++ /**+ * Function that maps the {@link AssetDescriptor}s to the formatted {@link ListItem}s.+ * Uses helpers like {@link Util.getAssetTypeLabel} and sorts by {@link descriptorType} so that agents show up first.+ */+ protected _getAssetTypeDescriptors(descriptors: AssetDescriptor[], selected?: AssetDescriptor[], withNoneValue?: ListItem): ListItem[] {+ const items: ListItem[] = descriptors?.map((descriptor) => {+ return {+ styleMap: {+ "--or-icon-fill": descriptor.colour ? "#" + descriptor.colour : "unset"+ },+ icon: descriptor.icon,+ trailingIcon: selected?.includes(descriptor) ? 'cloud-upload-outline' : undefined,+ text: Util.getAssetTypeLabel(descriptor),+ value: descriptor.name!,+ data: descriptor+ } as ListItem;+ }).sort((a, b) => (a.data.descriptorType === "agent" ? 0 : 1) - (b.data.descriptorType === "agent" ? 0 : 1) || a.text!.localeCompare(b.text!));++ if (withNoneValue) {+ items?.splice(0, 0, withNoneValue);+ }+ return items;+ }+++ /**+ * Utility method to get the cached {@link AssetDescriptor} by its name+ */+ protected _getAssetDescriptorByName(name?: string): AssetDescriptor | undefined {+ return name ? this._loadedAssetTypes?.find(at => at.name === name) : undefined;+ }+}diff --git a/ui/component/or-attribute-picker/src/assettype-list.ts b/ui/component/or-attribute-picker/src/assettype-list.tsnew file mode 100644index 000000000..f99ef165b--- /dev/null+++ b/ui/component/or-attribute-picker/src/assettype-list.ts@@ -0,0 +1,15 @@+import { OrMwcList } from "@openremote/or-mwc-components/or-mwc-list";+import { css } from "lit";+import { customElement } from "lit/decorators.js";++@customElement("asset-type-list")+export class AssettypeList extends OrMwcList {++ static get styles() {+ return [...super.styles, css`+ .mdc-list-item__meta or-icon {+ --or-icon-fill: gray;+ }+ `];+ }+}diff --git a/ui/component/or-attribute-picker/src/attribute-picker.ts b/ui/component/or-attribute-picker/src/attribute-picker.tsnew file mode 100644index 000000000..e83749463--- /dev/null+++ b/ui/component/or-attribute-picker/src/attribute-picker.ts@@ -0,0 +1,176 @@+import {html, TemplateResult, unsafeCSS} from "lit";+import {property, query} from "lit/decorators.js";+import "@openremote/or-asset-tree";+import "@openremote/or-translate";+import "@openremote/or-mwc-components/or-mwc-input";+import "@openremote/or-mwc-components/or-mwc-list";+import {InputType, OrInputChangedEvent, OrMwcInput} from "@openremote/or-mwc-components/or-mwc-input";+import {i18next} from "@openremote/or-translate";+import {DefaultColor2, DefaultColor4, DefaultColor5, Util} from "@openremote/core";+import {Attribute, AttributeDescriptor} from "@openremote/model";+import {DialogAction, DialogActionBase, OrMwcDialog} from "@openremote/or-mwc-components/or-mwc-dialog";+import {when} from "lit/directives/when.js";+import {ListItem, ListType, OrMwcListChangedEvent} from "@openremote/or-mwc-components/or-mwc-list";++export abstract class AttributePickerPickedEvent extends CustomEvent<any> {++}++/**+ * @summary Abstract implementation of the Attribute Picker UI. Wraps around OrMwcDialog and provides some utility properties and functions to inherit.+ *+ * @attribute {boolean} multiSelect - Whether selecting multiple attributes is allowed or not.+ * @attribute {boolean} showOnlyDatapointAttrs - Whether only attributes with the 'STORE_DATAPOINT' meta item should be shown.+ * @attribute {boolean} showOnlyRuleStateAttrs - Whether only attributes with the 'RULE_STATE' meta item should be shown.+ *+ * @remarks This class is abstract+ */+export abstract class AttributePicker extends OrMwcDialog {++ protected abstract _setDialogContent(): void;++ protected abstract _setDialogActions(): void;+++ @property({type: Boolean})+ public multiSelect?: boolean = false;++ @property({type: Boolean})+ public showOnlyDatapointAttrs?: boolean = false;++ @property({type: Boolean})+ public showOnlyRuleStateAttrs?: boolean = false;++ @query("#add-btn")+ protected addBtn!: OrMwcInput;++ connectedCallback() {+ super.connectedCallback();++ this.heading = i18next.t("selectAttributes");+ this._setDialogContent();+ this._setDialogActions();+ this.dismissAction = null;+ this.styles = this._getStyles();+ }++ public setShowOnlyDatapointAttrs(showOnlyDatapointAttrs: boolean | undefined): this {+ this.showOnlyDatapointAttrs = showOnlyDatapointAttrs;+ return this;+ }++ public setShowOnlyRuleStateAttrs(showOnlyRuleStateAttrs: boolean | undefined): this {+ this.showOnlyRuleStateAttrs = showOnlyRuleStateAttrs;+ return this;+ }++ public setMultiSelect(multiSelect: boolean | undefined): this {+ this.multiSelect = multiSelect;+ return this;+ }++ public setOpen(isOpen: boolean): this {+ super.setOpen(isOpen);+ return this;+ }++ public setHeading(heading: TemplateResult | string | undefined): this {+ super.setHeading(heading);+ return this;+ }++ public setContent(_content: TemplateResult | (() => TemplateResult) | undefined): this {+ throw new Error("Cannot modify attribute picker content");+ }++ public setActions(_actions: DialogAction[] | undefined): this {+ throw new Error("Cannot modify attribute picker actions");+ }++ public setDismissAction(_action: DialogActionBase | null | undefined): this {+ throw new Error("Cannot modify attribute picker dismiss action");+ }++ public setStyles(_styles: string | TemplateResult | undefined): this {+ throw new Error("Cannot modify attribute picker styles");+ }++ public setAvatar(_avatar: boolean | undefined): this {+ throw new Error("Cannot modify attribute picker avatar setting");+ }+++ /**+ * Convenient function to update the dialog content manually,+ * since updating the UI is handled different for {@link OrMwcDialog}.+ */+ protected _updateDialogContent() {+ this._setDialogContent();+ }+++ /**+ * Convenient function to update the dialog actions manually,+ * since updating the UI is handled different for {@link OrMwcDialog}.+ */+ protected _updateDialogActions() {+ this._setDialogActions();+ }+++ /**+ * Function that creates the HTML template for selecting attributes.+ * Currently uses {@link OrMwcList} with or without checkboxes, and uses {@link Util.getAttributeLabel} to formulate the text.+ *+ * @remarks TODO: Move this template into a separate component, such as an "or-attribute-list"+ */+ protected async _getAttributesTemplate(attributes?: Attribute<any>[], descriptors?: AttributeDescriptor[], selectedNames?: string[], multi = false, onSelect?: (attrNames: string[]) => void): Promise<TemplateResult> {+ const length = Math.max((attributes?.length || 0), (descriptors?.length || 0));+ const listItems: ListItem[] = [];+ for(let i = 0; i < length; i++) {+ listItems.push({+ text: Util.getAttributeLabel(attributes?.[i], descriptors?.[i], undefined, true),+ value: (attributes?.[i].name || descriptors?.[i].name),+ });+ }+ return html`+ ${when(multi, () => html`+ <or-mwc-list id="attribute-selector" .type="${ListType.MULTI_CHECKBOX}" .listItems="${listItems}" .values="${selectedNames}"+ @or-mwc-list-changed="${(ev: OrMwcListChangedEvent) => onSelect?.(ev.detail.map(item => item.value))}"+ </or-mwc-list>+ `, () => html`+ <or-mwc-input id="attribute-selector" .type="${InputType.LIST}" .options="${listItems?.map(item => ([item, item.text]))}"+ style="display:flex;" .label="${i18next.t("attribute")}"+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => onSelect?.([(ev.detail.value as ListItem).value])}"+ ></or-mwc-input>+ `)}+ `;+ }++ /**+ * Simple function that creates the CSS styles for this component+ */+ protected _getStyles(): string {++ // language=css+ return `+ .attributes-header {+ line-height: 48px;+ padding: 0 15px;+ background-color: ${unsafeCSS(DefaultColor2)};+ font-weight: bold;+ border-bottom: 1px solid ${unsafeCSS(DefaultColor2)};+ }+ footer.mdc-dialog__actions {+ border-top: 1px solid ${unsafeCSS(DefaultColor5)};+ }+ #header {+ background-color: ${unsafeCSS(DefaultColor4)} !important;+ }+ #dialog-content {+ padding: 0;+ }+ `++ }+}diff --git a/ui/component/or-attribute-picker/src/index.ts b/ui/component/or-attribute-picker/src/index.tsindex 6804317ff..bb5d876ec 100644--- a/ui/component/or-attribute-picker/src/index.ts+++ b/ui/component/or-attribute-picker/src/index.ts@@ -1,289 +1,34 @@-import {html, TemplateResult, unsafeCSS} from "lit";-import {customElement, property, query, state} from "lit/decorators.js";-import "@openremote/or-asset-tree";-import "@openremote/or-translate";-import "@openremote/or-mwc-components/or-mwc-input";-import "@openremote/or-mwc-components/or-mwc-list";-import {OrAssetTree, OrAssetTreeSelectionEvent} from "@openremote/or-asset-tree";-import {InputType, OrInputChangedEvent, OrMwcInput} from "@openremote/or-mwc-components/or-mwc-input";-import {i18next} from "@openremote/or-translate";-import manager, {DefaultColor2, DefaultColor4, DefaultColor5, Util} from "@openremote/core";-import {Asset, Attribute, AttributeRef, WellknownMetaItems} from "@openremote/model";-import {ListItem, ListType, OrMwcListChangedEvent} from "@openremote/or-mwc-components/or-mwc-list";-import {DialogAction, DialogActionBase, OrMwcDialog} from "@openremote/or-mwc-components/or-mwc-dialog";+import {customElement} from "lit/decorators.js";+import {OrAssetAttributePicker, OrAssetAttributePickerPickedEvent} from "./asset-attribute-picker";+import {AssetTypeAttributePickerPickedEvent, AssetTypeAttributePicker} from "./assettype-attribute-picker";-export class OrAttributePickerPickedEvent extends CustomEvent<AttributeRef[]> {+/**+ * {@link CustomEvent} that triggers once attributes have been selected, and the user closes the dialog.+ * @deprecated Replaced this class with an abstract {@link OrAssetAttributePickerPickedEvent}, that is inherited by other classes like {@link OrAssetAttributePicker} and {@link AssetTypeAttributePicker}.+ */+export class OrAttributePickerPickedEvent extends OrAssetAttributePickerPickedEvent {- public static readonly NAME = "or-attribute-picker-picked";-- constructor(detail: AttributeRef[]) {- super(OrAttributePickerPickedEvent.NAME, {- bubbles: true,- composed: true,- detail: detail- });- }-}--declare global {- export interface HTMLElementEventMap {- [OrAttributePickerPickedEvent.NAME]: OrAttributePickerPickedEvent;- }}+/**+ * Dialog to pick attributes of supplied asset(s).+ * @deprecated Replaced this class with {@link OrAssetAttributePicker}.+ */@customElement("or-attribute-picker")-export class OrAttributePicker extends OrMwcDialog {-- @property({type: Boolean})- public showOnlyDatapointAttrs?: boolean = false;-- @property({type: Boolean})- public showOnlyRuleStateAttrs?: boolean = false;--- @property()- public attributeFilter?: (attribute: Attribute<any>) => boolean;--- @property({type: Boolean})- public multiSelect?: boolean = false;-- public selectedAttributes: AttributeRef[] = [];- public selectedAssets: string[] = [];-- @state()- protected assetAttributes?: (Attribute<any>)[];- protected asset?: Asset;-- @query("#add-btn")- protected addBtn!: OrMwcInput;-- constructor() {- super();-- this.heading = i18next.t("selectAttributes");- this.setDialogContent();- this.setDialogActions();- this.dismissAction = null;-- this.styles = `- .attributes-header {- line-height: 48px;- padding: 0 15px;- background-color: ${unsafeCSS(DefaultColor2)};- font-weight: bold;- border-bottom: 1px solid ${unsafeCSS(DefaultColor2)};- }- footer.mdc-dialog__actions {- border-top: 1px solid ${unsafeCSS(DefaultColor5)};- }- #header {- background-color: ${unsafeCSS(DefaultColor4)} !important;- }- #dialog-content {- padding: 0;- }- `;- }-- public setShowOnlyDatapointAttrs(showOnlyDatapointAttrs: boolean | undefined): OrAttributePicker {- this.showOnlyDatapointAttrs = showOnlyDatapointAttrs;- return this;- }-- public setShowOnlyRuleStateAttrs(showOnlyRuleStateAttrs: boolean | undefined): OrAttributePicker {- this.showOnlyRuleStateAttrs = showOnlyRuleStateAttrs;- return this;- }-- public setAttributeFilter(attributeFilter: ((attribute: Attribute<any>) => boolean) | undefined): OrAttributePicker {- this.attributeFilter = attributeFilter;- return this;- }-- public setMultiSelect(multiSelect: boolean | undefined): OrAttributePicker {- this.multiSelect = multiSelect;- return this;- }-- public setSelectedAttributes(selectedAttributes: AttributeRef[]): OrAttributePicker {- this.selectedAttributes = selectedAttributes;- return this;- }-- public setSelectedAssets(selectedAssets: string[]): OrAttributePicker {- this.selectedAssets = selectedAssets;- this.setDialogContent();- return this;- }-- public setOpen(isOpen: boolean): OrAttributePicker {- super.setOpen(isOpen);- return this;- }-- public setHeading(heading: TemplateResult | string | undefined): OrAttributePicker {- super.setHeading(heading);- return this;- }-- public setContent(content: TemplateResult | (() => TemplateResult) | undefined): OrAttributePicker {- throw new Error("Cannot modify attribute picker content");- }-- public setActions(actions: DialogAction[] | undefined): OrAttributePicker {- throw new Error("Cannot modify attribute picker actions");- }-- public setDismissAction(action: DialogActionBase | null | undefined): OrAttributePicker {- throw new Error("Cannot modify attribute picker dismiss action");- }-- public setStyles(styles: string | TemplateResult | undefined): OrAttributePicker {- throw new Error("Cannot modify attribute picker styles");- }-- public setAvatar(avatar: boolean | undefined): OrAttributePicker {- throw new Error("Cannot modify attribute picker avatar setting");- }-- protected setDialogActions(): void {- this.actions = [- {- actionName: "cancel",- content: "cancel"- },- {- actionName: "add",- content: html`<or-mwc-input id="add-btn" class="button" label="add"- .type="${InputType.BUTTON}" ?disabled="${!this.selectedAttributes.length}"- @or-mwc-input-changed="${(ev: Event) => { if (!this.selectedAttributes.length) { ev.stopPropagation(); return false; } } }"></or-mwc-input>`,- action: () => {-- if (!this.selectedAttributes.length) {- return;- }-- this.dispatchEvent(new OrAttributePickerPickedEvent(this.selectedAttributes));- }- }- ];- }-- protected setDialogContent(): void {-- const getListItems: () => ListItem[] = () => {- if (!this.assetAttributes) {- return [];- }-- return this.assetAttributes.map((attribute) => {- return {- text: Util.getAttributeLabel(undefined, attribute, undefined, true),- value: attribute.name- } as ListItem- });- };-- let selectedAttribute: ListItem | undefined = undefined;- if (!this.multiSelect && this.selectedAttributes.length === 1 && this.selectedAttributes[0].name) {- selectedAttribute = {- text: Util.getAttributeLabel(undefined, this.selectedAttributes[0], undefined, true),- value: this.selectedAttributes[0].name- };- }-- this.content = () => html`- <div class="row" style="display: flex;height: 600px;width: 800px;border-top: 1px solid ${unsafeCSS(DefaultColor5)};">- <div class="col" style="width: 260px;overflow: auto;border-right: 1px solid ${unsafeCSS(DefaultColor5)};">- <or-asset-tree id="chart-asset-tree" readonly- .selectedIds="${ this.selectedAssets.length > 0 ? this.selectedAssets : null }"- @or-asset-tree-selection="${(ev: OrAssetTreeSelectionEvent) => this._onAssetSelectionChanged(ev)}">- </or-asset-tree>- </div>- <div class="col" style="flex: 1 1 auto;width: 260px;overflow: auto;">- ${this.assetAttributes && this.assetAttributes.length > 0 ? html`- <div class="attributes-header">- <or-translate value="attribute_plural"></or-translate>- </div>- ${this.multiSelect- ?- html`<div style="display: grid">- <or-mwc-list- id="attribute-selector" .type="${ListType.MULTI_CHECKBOX}" .listItems="${getListItems()}"- .values="${this.selectedAttributes.filter(attributeRef => attributeRef.id === this.asset!.id).map(attributeRef => attributeRef.name!)}"- @or-mwc-list-changed="${(ev: OrMwcListChangedEvent) => this._onAttributeSelectionChanged([...this.selectedAttributes.filter(attributeRef => attributeRef.id !== this.asset!.id),...ev.detail.map(li => {return {id: this.asset!.id!, name:li.value as string} as AttributeRef;})])}"></or-mwc-list>- </div>`- :- html`<or-mwc-input id="attribute-selector"- style="display:flex;"- .label="${i18next.t("attribute")}"- .type="${InputType.LIST}"- .options="${getListItems().map(item => ([item, item.text]))}"- @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {- this._onAttributeSelectionChanged(- [- {- id: this.asset!.id!,- name: (ev.detail.value as ListItem).value as string- } as AttributeRef- ]);- }}"></or-mwc-input>`}- ` : html`<div style="display: flex;align-items: center;text-align: center;height: 100%;padding: 0 20px;"><span style="width:100%">- <or-translate value="${- (this.assetAttributes && this.assetAttributes.length === 0) ?- ((this.showOnlyDatapointAttrs && this.showOnlyRuleStateAttrs) ? "noDatapointsOrRuleStateAttributes" :- this.showOnlyDatapointAttrs ? "noDatapointsAttributes" :- this.showOnlyRuleStateAttrs ? "noRuleStateAttributes" : "noAttributesToShow"- ) : "selectAssetOnTheLeft"}">- </or-translate></span></div>`}- </div>- `;- }-- protected async _onAssetSelectionChanged(event: OrAssetTreeSelectionEvent) {- this.assetAttributes = undefined;- if (!this.multiSelect) {- this.selectedAttributes = [];- }- this.addBtn.disabled = this.selectedAttributes.length === 0;- const assetTree = event.target as OrAssetTree;- assetTree.disabled = true;-- let selectedAsset = event.detail.newNodes.length === 0 ? undefined : event.detail.newNodes[0].asset;- this.asset = selectedAsset;-- if (selectedAsset) {- // Load the asset attributes- const assetResponse = await manager.rest.api.AssetResource.get(selectedAsset.id!);- selectedAsset = assetResponse.data;-- if (selectedAsset) {- this.assetAttributes = Object.values(selectedAsset.attributes!).map(attr => { return {...attr, id: selectedAsset!.id!}; })- .sort(Util.sortByString((attribute) => attribute.name!));+export class OrAttributePicker extends OrAssetAttributePicker {+}- if (this.attributeFilter){- this.assetAttributes = this.assetAttributes.filter((attr) => this.attributeFilter!(attr))- }+/**+ * TODO: Remove this, and export the ./assettype-attribute-picker file+ */+export class OrAssetTypeAttributePickerPickedEvent extends AssetTypeAttributePickerPickedEvent {- if (this.showOnlyDatapointAttrs && this.showOnlyRuleStateAttrs) {- this.assetAttributes = this.assetAttributes- .filter(e => e.meta && (e.meta[WellknownMetaItems.STOREDATAPOINTS] || e.meta[WellknownMetaItems.RULESTATE] || e.meta[WellknownMetaItems.AGENTLINK]));- } else if (this.showOnlyDatapointAttrs) {- this.assetAttributes = this.assetAttributes- .filter(e => e.meta && (e.meta[WellknownMetaItems.STOREDATAPOINTS] || e.meta[WellknownMetaItems.AGENTLINK]));- } else if (this.showOnlyRuleStateAttrs) {- this.assetAttributes = this.assetAttributes- .filter(e => e.meta && (e.meta[WellknownMetaItems.RULESTATE] || e.meta[WellknownMetaItems.AGENTLINK]));- }- }- }+}- assetTree.disabled = false;- }+/**+ * TODO: Remove this, and export the ./assettype-attribute-picker file+ */+@customElement("or-assettype-attribute-picker")+export class OrAssetTypeAttributePicker extends AssetTypeAttributePicker {- protected _onAttributeSelectionChanged(attributeRefs: AttributeRef[]) {- this.selectedAttributes = attributeRefs;- this.addBtn.disabled = this.selectedAttributes.length === 0;- }}