Search in sources :

Example 6 with Attribute

use of org.openremote.model.attribute.Attribute in project openremote by openremote.

the class ZWaveProtocol method doLinkAttribute.

@Override
protected synchronized void doLinkAttribute(String assetId, Attribute<?> attribute, ZWaveAgentLink agentLink) {
    if (network == null) {
        return;
    }
    int nodeId = agentLink.getDeviceNodeId().orElse(0);
    int endpoint = agentLink.getDeviceEndpoint().orElse(0);
    String linkName = agentLink.getDeviceValue().orElse("");
    AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
    Class<?> clazz = (attribute == null ? null : attribute.getType().getType());
    Consumer<Value> sensorValueConsumer = value -> updateLinkedAttribute(new AttributeState(attributeRef, toAttributeValue(value, clazz)));
    sensorValueConsumerMap.put(attributeRef, sensorValueConsumer);
    network.addSensorValueConsumer(nodeId, endpoint, linkName, sensorValueConsumer);
}
Also used : AssetTreeNode(org.openremote.model.asset.AssetTreeNode) AttributeState(org.openremote.model.attribute.AttributeState) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) ColourRGB(org.openremote.model.value.impl.ColourRGB) AttributeRef(org.openremote.model.attribute.AttributeRef) ProtocolAssetDiscovery(org.openremote.model.protocol.ProtocolAssetDiscovery) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Value(org.openremote.protocol.zwave.model.commandclasses.channel.value.Value) Logger(java.util.logging.Logger) AbstractProtocol(org.openremote.agent.protocol.AbstractProtocol) Container(org.openremote.model.Container) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) Consumer(java.util.function.Consumer) List(java.util.List) Future(java.util.concurrent.Future) Attribute(org.openremote.model.attribute.Attribute) AttributeEvent(org.openremote.model.attribute.AttributeEvent) Map(java.util.Map) AgentLink.getOrThrowAgentLinkProperty(org.openremote.model.asset.agent.AgentLink.getOrThrowAgentLinkProperty) SyslogCategory(org.openremote.model.syslog.SyslogCategory) AttributeState(org.openremote.model.attribute.AttributeState) AttributeRef(org.openremote.model.attribute.AttributeRef) Value(org.openremote.protocol.zwave.model.commandclasses.channel.value.Value)

Example 7 with Attribute

use of org.openremote.model.attribute.Attribute in project openremote by openremote.

the class AssetStorageService method publishModificationEvents.

protected void publishModificationEvents(PersistenceEvent<Asset<?>> persistenceEvent) {
    Asset<?> asset = persistenceEvent.getEntity();
    switch(persistenceEvent.getCause()) {
        case CREATE:
            // Fully load the asset
            Asset<?> loadedAsset = find(new AssetQuery().ids(asset.getId()));
            if (loadedAsset == null) {
                return;
            }
            if (LOG.isLoggable(Level.FINER)) {
                LOG.finer("Asset created: " + loadedAsset.toStringAll());
            } else {
                LOG.fine("Asset created: " + loadedAsset);
            }
            clientEventService.publishEvent(new AssetEvent(AssetEvent.Cause.CREATE, loadedAsset, null));
            // ));
            break;
        case UPDATE:
            String[] updatedProperties = persistenceEvent.getPropertyNames();
            boolean attributesChanged = Arrays.asList(updatedProperties).contains("attributes");
            // String[] updatedProperties = Arrays.stream(persistenceEvent.getPropertyNames()).filter(propertyName -> {
            // Object oldValue = persistenceEvent.getPreviousState(propertyName);
            // Object newValue = persistenceEvent.getCurrentState(propertyName);
            // return !Objects.deepEquals(oldValue, newValue);
            // }).toArray(String[]::new);
            // Fully load the asset
            loadedAsset = find(new AssetQuery().ids(asset.getId()));
            if (loadedAsset == null) {
                return;
            }
            LOG.finer("Asset updated: " + persistenceEvent);
            clientEventService.publishEvent(new AssetEvent(AssetEvent.Cause.UPDATE, loadedAsset, updatedProperties));
            // Did any attributes change if so raise attribute events on the event bus
            if (attributesChanged) {
                AttributeMap oldAttributes = persistenceEvent.getPreviousState("attributes");
                AttributeMap newAttributes = persistenceEvent.getCurrentState("attributes");
                // Get removed attributes and raise an attribute event with deleted flag in attribute state
                oldAttributes.stream().filter(oldAttribute -> newAttributes.stream().noneMatch(newAttribute -> oldAttribute.getName().equals(newAttribute.getName()))).forEach(obsoleteAttribute -> clientEventService.publishEvent(AttributeEvent.deletedAttribute(asset.getId(), obsoleteAttribute.getName())));
                // Get new or modified attributes
                getAddedOrModifiedAttributes(oldAttributes.values(), newAttributes.values()).forEach(newOrModifiedAttribute -> publishAttributeEvent(asset, newOrModifiedAttribute));
            }
            break;
        case DELETE:
            if (LOG.isLoggable(Level.FINER)) {
                LOG.finer("Asset deleted: " + asset.toStringAll());
            } else {
                LOG.fine("Asset deleted: " + asset);
            }
            clientEventService.publishEvent(new AssetEvent(AssetEvent.Cause.DELETE, asset, null));
            // Raise attribute event with deleted flag for each attribute
            AttributeMap deletedAttributes = asset.getAttributes();
            deletedAttributes.forEach(obsoleteAttribute -> clientEventService.publishEvent(AttributeEvent.deletedAttribute(asset.getId(), obsoleteAttribute.getName())));
            break;
    }
}
Also used : ValuePredicate.asPredicateOrTrue(org.openremote.model.query.filter.ValuePredicate.asPredicateOrTrue) ClientRole(org.openremote.model.security.ClientRole) AuthContext(org.openremote.container.security.AuthContext) NoResultException(javax.persistence.NoResultException) ValueUtil(org.openremote.model.util.ValueUtil) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AttributeEvent(org.openremote.model.attribute.AttributeEvent) GroupAsset(org.openremote.model.asset.impl.GroupAsset) TextUtil(org.openremote.model.util.TextUtil) ConstraintViolation(javax.validation.ConstraintViolation) LogicGroup(org.openremote.model.query.LogicGroup) Attribute.getAddedOrModifiedAttributes(org.openremote.model.attribute.Attribute.getAddedOrModifiedAttributes) Predicate(java.util.function.Predicate) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) ACCESS_RESTRICTED_READ(org.openremote.model.value.MetaItemType.ACCESS_RESTRICTED_READ) Query(javax.persistence.Query) StringArrayType(com.vladmihalcea.hibernate.type.array.StringArrayType) org.openremote.model(org.openremote.model) RouteBuilder(org.apache.camel.builder.RouteBuilder) PERSISTENCE_TOPIC(org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC) AssetInfo(org.openremote.model.event.shared.AssetInfo) EventSubscription(org.openremote.model.event.shared.EventSubscription) TextUtil.isNullOrEmpty(org.openremote.model.util.TextUtil.isNullOrEmpty) SharedEvent(org.openremote.model.event.shared.SharedEvent) GatewayService(org.openremote.manager.gateway.GatewayService) java.sql(java.sql) IntStream(java.util.stream.IntStream) AttributeMap(org.openremote.model.attribute.AttributeMap) EventSubscriptionAuthorizer(org.openremote.manager.event.EventSubscriptionAuthorizer) java.util(java.util) ACCESS_PUBLIC_READ(org.openremote.model.value.MetaItemType.ACCESS_PUBLIC_READ) CLIENT_EVENT_TOPIC(org.openremote.manager.event.ClientEventService.CLIENT_EVENT_TOPIC) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) Session(org.hibernate.Session) TypedQuery(javax.persistence.TypedQuery) Supplier(java.util.function.Supplier) Level(java.util.logging.Level) AbstractReturningWork(org.hibernate.jdbc.AbstractReturningWork) PGobject(org.postgresql.util.PGobject) Attribute(org.openremote.model.attribute.Attribute) PersistenceService(org.openremote.container.persistence.PersistenceService) org.openremote.model.query.filter(org.openremote.model.query.filter) BiConsumer(java.util.function.BiConsumer) ManagerWebService(org.openremote.manager.web.ManagerWebService) org.openremote.model.asset(org.openremote.model.asset) MessageBrokerService(org.openremote.container.message.MessageBrokerService) User(org.openremote.model.security.User) Access(org.openremote.model.query.AssetQuery.Access) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) MetaItemType(org.openremote.model.value.MetaItemType) AssetQuery(org.openremote.model.query.AssetQuery) Pair(org.openremote.model.util.Pair) EntityManager(javax.persistence.EntityManager) Consumer(java.util.function.Consumer) EventRequestResponseWrapper(org.openremote.model.event.shared.EventRequestResponseWrapper) ClientEventService(org.openremote.manager.event.ClientEventService) ConstraintViolationException(javax.validation.ConstraintViolationException) TimerService(org.openremote.container.timer.TimerService) ConsoleResourceImpl(org.openremote.manager.asset.console.ConsoleResourceImpl) PredicateBuilder.or(org.apache.camel.builder.PredicateBuilder.or) PersistenceService.isPersistenceEventForEntityType(org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType) AttributeMap(org.openremote.model.attribute.AttributeMap) AssetQuery(org.openremote.model.query.AssetQuery)

Example 8 with Attribute

use of org.openremote.model.attribute.Attribute in project openremote by openremote.

the class StorageSimulatorProtocol method doLinkedAttributeWrite.

@SuppressWarnings("unchecked")
@Override
protected void doLinkedAttributeWrite(Attribute<?> attribute, StorageSimulatorAgentLink agentLink, AttributeEvent event, Object processedValue) {
    // Power attribute is updated only by this protocol not by clients
    if (attribute.getName().equals(POWER.getName())) {
        return;
    }
    updateLinkedAttribute(new AttributeState(event.getAttributeRef(), processedValue));
    // Push write value into the asset and update
    String assetId = event.getAssetId();
    ((Attribute<Object>) attribute).setValue(processedValue);
    ElectricityStorageAsset asset = assetService.findAsset(assetId, ElectricityStorageAsset.class);
    asset.addOrReplaceAttributes(attribute);
    updateStorageAsset(asset);
}
Also used : AttributeState(org.openremote.model.attribute.AttributeState) ElectricityStorageAsset(org.openremote.model.asset.impl.ElectricityStorageAsset) Attribute(org.openremote.model.attribute.Attribute)

Example 9 with Attribute

use of org.openremote.model.attribute.Attribute in project openremote by openremote.

the class AbstractProtocol method start.

@Override
public void start(Container container) throws Exception {
    timerService = container.getService(TimerService.class);
    executorService = container.getExecutorService();
    assetService = container.getService(ProtocolAssetService.class);
    predictedAssetService = container.getService(ProtocolPredictedAssetService.class);
    messageBrokerContext = container.getService(MessageBrokerService.class).getContext();
    withLock(getProtocolName() + "::start", () -> {
        try {
            messageBrokerContext.addRoutes(new RouteBuilder() {

                @Override
                public void configure() throws Exception {
                    from(ACTUATOR_TOPIC).routeId("Actuator-" + getProtocolName() + getAgent().getId()).process(exchange -> {
                        Protocol<?> protocolInstance = exchange.getIn().getHeader(ACTUATOR_TOPIC_TARGET_PROTOCOL, Protocol.class);
                        if (protocolInstance != AbstractProtocol.this) {
                            return;
                        }
                        AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
                        Attribute<?> linkedAttribute = getLinkedAttributes().get(event.getAttributeRef());
                        if (linkedAttribute == null) {
                            LOG.info("Attempt to write to attribute that is not actually linked to this protocol '" + AbstractProtocol.this + "': " + linkedAttribute);
                            return;
                        }
                        processLinkedAttributeWrite(event);
                    });
                }
            });
            doStart(container);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    });
    this.producerTemplate = container.getService(MessageBrokerService.class).getProducerTemplate();
}
Also used : Protocol(org.openremote.model.asset.agent.Protocol) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) AttributeRef(org.openremote.model.attribute.AttributeRef) HashMap(java.util.HashMap) AgentLink(org.openremote.model.asset.agent.AgentLink) HashSet(java.util.HashSet) Attribute(org.openremote.model.attribute.Attribute) AttributeEvent(org.openremote.model.attribute.AttributeEvent) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ProducerTemplate(org.apache.camel.ProducerTemplate) SyslogCategory(org.openremote.model.syslog.SyslogCategory) MessageBrokerService(org.openremote.container.message.MessageBrokerService) AttributeState(org.openremote.model.attribute.AttributeState) MetaItemType(org.openremote.model.value.MetaItemType) Pair(org.openremote.model.util.Pair) Set(java.util.Set) Logger(java.util.logging.Logger) Container(org.openremote.model.Container) PROTOCOL(org.openremote.model.syslog.SyslogCategory.PROTOCOL) TimeUnit(java.util.concurrent.TimeUnit) RouteBuilder(org.apache.camel.builder.RouteBuilder) TimerService(org.openremote.container.timer.TimerService) MessageBrokerContext(org.openremote.container.message.MessageBrokerContext) Agent(org.openremote.model.asset.agent.Agent) GlobalLock(org.openremote.container.concurrent.GlobalLock) ProtocolUtil.hasDynamicWriteValue(org.openremote.model.protocol.ProtocolUtil.hasDynamicWriteValue) ProtocolUtil(org.openremote.model.protocol.ProtocolUtil) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) RouteBuilder(org.apache.camel.builder.RouteBuilder) Attribute(org.openremote.model.attribute.Attribute) Protocol(org.openremote.model.asset.agent.Protocol) TimerService(org.openremote.container.timer.TimerService) AttributeEvent(org.openremote.model.attribute.AttributeEvent)

Example 10 with Attribute

use of org.openremote.model.attribute.Attribute in project openremote by openremote.

the class AssetDatapointService method purgeDataPoints.

protected void purgeDataPoints() {
    LOG.info("Starting data points purge daily task");
    try {
        // Get list of attributes that have custom durations
        List<Asset<?>> assets = assetStorageService.findAll(new AssetQuery().attributes(new AttributePredicate().meta(new NameValuePredicate(MetaItemType.DATA_POINTS_MAX_AGE_DAYS, null))));
        List<Pair<String, Attribute<?>>> attributes = assets.stream().map(asset -> asset.getAttributes().stream().filter(assetAttribute -> assetAttribute.hasMeta(MetaItemType.DATA_POINTS_MAX_AGE_DAYS)).map(assetAttribute -> new Pair<String, Attribute<?>>(asset.getId(), assetAttribute)).collect(toList())).flatMap(List::stream).collect(toList());
        // Purge data points not in the above list using default duration
        LOG.fine("Purging data points of attributes that use default max age days of " + maxDatapointAgeDays);
        persistenceService.doTransaction(em -> em.createQuery("delete from AssetDatapoint dp " + "where dp.timestamp < :dt" + buildWhereClause(attributes, true)).setParameter("dt", Date.from(timerService.getNow().truncatedTo(DAYS).minus(maxDatapointAgeDays, DAYS))).executeUpdate());
        if (!attributes.isEmpty()) {
            // Purge data points that have specific age constraints
            Map<Integer, List<Pair<String, Attribute<?>>>> ageAttributeRefMap = attributes.stream().collect(groupingBy(attributeRef -> attributeRef.value.getMetaValue(MetaItemType.DATA_POINTS_MAX_AGE_DAYS).orElse(maxDatapointAgeDays)));
            ageAttributeRefMap.forEach((age, attrs) -> {
                LOG.fine("Purging data points of " + attrs.size() + " attributes that use a max age of " + age);
                try {
                    persistenceService.doTransaction(em -> em.createQuery("delete from AssetDatapoint dp " + "where dp.timestamp < :dt" + buildWhereClause(attrs, false)).setParameter("dt", Date.from(timerService.getNow().truncatedTo(DAYS).minus(age, DAYS))).executeUpdate());
                } catch (Exception e) {
                    LOG.log(Level.SEVERE, "An error occurred whilst deleting data points, this should not happen", e);
                }
            });
        }
    } catch (Exception e) {
        LOG.log(Level.WARNING, "Failed to run data points purge", e);
    }
    LOG.info("Finished data points purge daily task");
}
Also used : AssetStorageService(org.openremote.manager.asset.AssetStorageService) Arrays(java.util.Arrays) ScheduledFuture(java.util.concurrent.ScheduledFuture) AssetProcessingException(org.openremote.manager.asset.AssetProcessingException) AttributeRef(org.openremote.model.attribute.AttributeRef) LocalDateTime(java.time.LocalDateTime) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) AttributeWriteFailure(org.openremote.model.attribute.AttributeWriteFailure) STORE_DATA_POINTS(org.openremote.model.value.MetaItemType.STORE_DATA_POINTS) MapAccess.getInteger(org.openremote.container.util.MapAccess.getInteger) MapAccess.getString(org.openremote.container.util.MapAccess.getString) Level(java.util.logging.Level) UniqueIdentifierGenerator(org.openremote.container.util.UniqueIdentifierGenerator) Attribute(org.openremote.model.attribute.Attribute) Duration(java.time.Duration) Map(java.util.Map) NameValuePredicate(org.openremote.model.query.filter.NameValuePredicate) ManagerWebService(org.openremote.manager.web.ManagerWebService) Path(java.nio.file.Path) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) Asset(org.openremote.model.asset.Asset) MetaItemType(org.openremote.model.value.MetaItemType) AssetQuery(org.openremote.model.query.AssetQuery) Pair(org.openremote.model.util.Pair) AssetDatapoint(org.openremote.model.datapoint.AssetDatapoint) AttributePredicate(org.openremote.model.query.filter.AttributePredicate) EntityManager(javax.persistence.EntityManager) Instant(java.time.Instant) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) File(java.io.File) ZoneId(java.time.ZoneId) Container(org.openremote.model.Container) Date(java.sql.Date) TimeUnit(java.util.concurrent.TimeUnit) DAYS(java.time.temporal.ChronoUnit.DAYS) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Paths(java.nio.file.Paths) TimerService(org.openremote.container.timer.TimerService) AssetUpdateProcessor(org.openremote.manager.asset.AssetUpdateProcessor) Source(org.openremote.model.attribute.AttributeEvent.Source) Attribute(org.openremote.model.attribute.Attribute) AssetQuery(org.openremote.model.query.AssetQuery) MapAccess.getString(org.openremote.container.util.MapAccess.getString) AttributePredicate(org.openremote.model.query.filter.AttributePredicate) AssetProcessingException(org.openremote.manager.asset.AssetProcessingException) MapAccess.getInteger(org.openremote.container.util.MapAccess.getInteger) Asset(org.openremote.model.asset.Asset) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) NameValuePredicate(org.openremote.model.query.filter.NameValuePredicate) Pair(org.openremote.model.util.Pair)

Aggregations

Attribute (org.openremote.model.attribute.Attribute)18 Logger (java.util.logging.Logger)13 Level (java.util.logging.Level)11 AttributeEvent (org.openremote.model.attribute.AttributeEvent)10 Consumer (java.util.function.Consumer)9 Container (org.openremote.model.Container)9 ValueUtil (org.openremote.model.util.ValueUtil)9 java.util (java.util)8 AttributeState (org.openremote.model.attribute.AttributeState)8 SyslogCategory (org.openremote.model.syslog.SyslogCategory)8 ConnectionStatus (org.openremote.model.asset.agent.ConnectionStatus)7 AttributeRef (org.openremote.model.attribute.AttributeRef)7 Pair (org.openremote.model.util.Pair)7 MetaItemType (org.openremote.model.value.MetaItemType)7 Asset (org.openremote.model.asset.Asset)6 Map (java.util.Map)5 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)5 TimeUnit (java.util.concurrent.TimeUnit)5 Collectors (java.util.stream.Collectors)5 AbstractProtocol (org.openremote.agent.protocol.AbstractProtocol)5