Search in sources :

Example 1 with AgentLink

use of org.openremote.model.asset.agent.AgentLink in project openremote by openremote.

the class AgentService method startAgent.

protected void startAgent(Agent<?, ?, ?> agent) {
    withLock(getClass().getSimpleName() + "::startAgent", () -> {
        Protocol<?> protocol = null;
        try {
            protocol = agent.getProtocolInstance();
            protocolInstanceMap.put(agent.getId(), protocol);
            LOG.fine("Starting protocol instance: " + protocol);
            protocol.start(container);
            LOG.fine("Started protocol instance:" + protocol);
            LOG.finer("Linking attributes to protocol instance: " + protocol);
            // Get all assets that have attributes with agent link meta for this agent
            List<Asset<?>> assets = assetStorageService.findAll(new AssetQuery().attributes(new AttributePredicate().meta(new NameValuePredicate(AGENT_LINK, new StringPredicate(agent.getId()), false, new NameValuePredicate.Path("id")))));
            LOG.finer("Found '" + assets.size() + "' asset(s) with attributes linked to this protocol instance: " + protocol);
            assets.forEach(asset -> getGroupedAgentLinkAttributes(asset.getAttributes().stream(), assetAttribute -> assetAttribute.getMetaValue(AGENT_LINK).map(agentLink -> agentLink.getId().equals(agent.getId())).orElse(false)).forEach((agnt, attributes) -> linkAttributes(agnt, asset.getId(), attributes)));
        } catch (Exception e) {
            if (protocol != null) {
                try {
                    protocol.stop(container);
                } catch (Exception ignored) {
                }
            }
            protocolInstanceMap.remove(agent.getId());
            LOG.log(Level.SEVERE, "Failed to start protocol instance for agent: " + agent, e);
            sendAttributeEvent(new AttributeEvent(agent.getId(), Agent.STATUS.getName(), ConnectionStatus.ERROR));
        }
    });
}
Also used : Protocol(org.openremote.model.asset.agent.Protocol) AssetProcessingException(org.openremote.manager.asset.AssetProcessingException) AssetProcessingService(org.openremote.manager.asset.AssetProcessingService) ASSET_QUEUE(org.openremote.manager.asset.AssetProcessingService.ASSET_QUEUE) ProtocolInstanceDiscovery(org.openremote.model.protocol.ProtocolInstanceDiscovery) ACTUATOR_TOPIC(org.openremote.model.asset.agent.Protocol.ACTUATOR_TOPIC) AgentLink(org.openremote.model.asset.agent.AgentLink) Future(java.util.concurrent.Future) TextUtil(org.openremote.model.util.TextUtil) Attribute.getAddedOrModifiedAttributes(org.openremote.model.attribute.Attribute.getAddedOrModifiedAttributes) AssetTreeNode(org.openremote.model.asset.AssetTreeNode) Predicate(java.util.function.Predicate) ProtocolAssetDiscovery(org.openremote.model.protocol.ProtocolAssetDiscovery) ContainerService(org.openremote.model.ContainerService) AttributePredicate(org.openremote.model.query.filter.AttributePredicate) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Container(org.openremote.model.Container) Stream(java.util.stream.Stream) StringPredicate(org.openremote.model.query.filter.StringPredicate) RouteBuilder(org.apache.camel.builder.RouteBuilder) PERSISTENCE_TOPIC(org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC) org.openremote.model.attribute(org.openremote.model.attribute) Agent(org.openremote.model.asset.agent.Agent) PathPredicate(org.openremote.model.query.filter.PathPredicate) GatewayService(org.openremote.manager.gateway.GatewayService) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) AssetStorageService(org.openremote.manager.asset.AssetStorageService) GatewayService.isNotForGateway(org.openremote.manager.gateway.GatewayService.isNotForGateway) java.util(java.util) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) Level(java.util.logging.Level) GlobalLock.withLockReturning(org.openremote.container.concurrent.GlobalLock.withLockReturning) AGENT_LINK(org.openremote.model.value.MetaItemType.AGENT_LINK) Collectors.mapping(java.util.stream.Collectors.mapping) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) NameValuePredicate(org.openremote.model.query.filter.NameValuePredicate) ManagerWebService(org.openremote.manager.web.ManagerWebService) PersistenceEvent(org.openremote.model.PersistenceEvent) MessageBrokerService(org.openremote.container.message.MessageBrokerService) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) Asset(org.openremote.model.asset.Asset) AssetQuery(org.openremote.model.query.AssetQuery) Pair(org.openremote.model.util.Pair) ProtocolAssetService(org.openremote.agent.protocol.ProtocolAssetService) EntityManager(javax.persistence.EntityManager) HEADER_SOURCE(org.openremote.model.attribute.AttributeEvent.HEADER_SOURCE) Consumer(java.util.function.Consumer) SENSOR_QUEUE(org.openremote.model.asset.agent.Protocol.SENSOR_QUEUE) ClientEventService(org.openremote.manager.event.ClientEventService) ProtocolAssetImport(org.openremote.model.protocol.ProtocolAssetImport) Collectors.toList(java.util.stream.Collectors.toList) TimerService(org.openremote.container.timer.TimerService) AssetUpdateProcessor(org.openremote.manager.asset.AssetUpdateProcessor) PersistenceService.isPersistenceEventForEntityType(org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType) Source(org.openremote.model.attribute.AttributeEvent.Source) StringPredicate(org.openremote.model.query.filter.StringPredicate) AssetQuery(org.openremote.model.query.AssetQuery) Asset(org.openremote.model.asset.Asset) NameValuePredicate(org.openremote.model.query.filter.NameValuePredicate) AttributePredicate(org.openremote.model.query.filter.AttributePredicate) AssetProcessingException(org.openremote.manager.asset.AssetProcessingException)

Example 2 with AgentLink

use of org.openremote.model.asset.agent.AgentLink in project openremote by openremote.

the class AssetViewActivity method onAgentStatusEvent.

protected void onAgentStatusEvent(AgentStatusEvent event) {
    for (AttributeView attributeView : attributeViews) {
        AssetAttribute assetAttribute = attributeView.getAttribute();
        Optional<AttributeRef> assetAttributeRef = assetAttribute.getReference();
        if (asset.getWellKnownType() == AssetType.AGENT) {
            if (assetAttributeRef.map(ref -> ref.equals(event.getProtocolConfiguration())).orElse(false)) {
                attributeView.setStatus(event.getConnectionStatus());
            }
        } else {
            AgentLink.getAgentLink(assetAttribute).filter(agentLink -> agentLink.equals(event.getProtocolConfiguration())).ifPresent(agentLink -> {
                attributeView.setStatus(event.getConnectionStatus());
            });
        }
    }
}
Also used : SimulatorState(org.openremote.model.simulator.SimulatorState) DatapointInterval(org.openremote.model.datapoint.DatapointInterval) AssetMapper(org.openremote.app.client.assets.AssetMapper) Environment(org.openremote.app.client.Environment) ProtocolConfiguration(org.openremote.model.asset.agent.ProtocolConfiguration) AttributeRef(org.openremote.model.attribute.AttributeRef) AssetDatapointResource(org.openremote.model.datapoint.AssetDatapointResource) AttributeViewImpl(org.openremote.app.client.assets.attributes.AttributeViewImpl) ObjectValueMapper(org.openremote.app.client.interop.value.ObjectValueMapper) FormButton(org.openremote.app.client.widget.FormButton) NumberDatapoint(org.openremote.model.datapoint.NumberDatapoint) ArrayList(java.util.ArrayList) AgentLink(org.openremote.model.asset.agent.AgentLink) Inject(javax.inject.Inject) ReadAssetAttributesEvent(org.openremote.model.asset.ReadAssetAttributesEvent) TenantFilter(org.openremote.model.event.shared.TenantFilter) AttributeEvent(org.openremote.model.attribute.AttributeEvent) URL(com.google.gwt.http.client.URL) AbstractAttributeViewExtension(org.openremote.app.client.assets.attributes.AbstractAttributeViewExtension) AttributeView(org.openremote.app.client.assets.attributes.AttributeView) AgentStatusEventMapper(org.openremote.app.client.assets.AgentStatusEventMapper) Consumer(org.openremote.model.interop.Consumer) AgentResource(org.openremote.model.asset.agent.AgentResource) MapResource(org.openremote.model.map.MapResource) AgentStatusEvent(org.openremote.model.asset.agent.AgentStatusEvent) AssetType(org.openremote.model.asset.AssetType) DatapointBrowser(org.openremote.app.client.datapoint.DatapointBrowser) JsonEditor(org.openremote.app.client.app.dialog.JsonEditor) Constants(org.openremote.model.Constants) AssetResource(org.openremote.model.asset.AssetResource) Provider(com.google.inject.Provider) List(java.util.List) AssetBrowser(org.openremote.app.client.assets.browser.AssetBrowser) NumberDatapointArrayMapper(org.openremote.app.client.datapoint.NumberDatapointArrayMapper) Optional(java.util.Optional) Values(org.openremote.model.value.Values) TextUtil.isNullOrEmpty(org.openremote.model.util.TextUtil.isNullOrEmpty) AssetAttribute(org.openremote.model.asset.AssetAttribute) Datapoint(org.openremote.model.datapoint.Datapoint) Collections(java.util.Collections) Simulator(org.openremote.app.client.simulator.Simulator) AttributeExecuteStatus(org.openremote.model.attribute.AttributeExecuteStatus) AttributeView(org.openremote.app.client.assets.attributes.AttributeView) AttributeRef(org.openremote.model.attribute.AttributeRef) AssetAttribute(org.openremote.model.asset.AssetAttribute)

Example 3 with AgentLink

use of org.openremote.model.asset.agent.AgentLink in project openremote by openremote.

the class HTTPProtocol method doLinkAttribute.

@Override
protected void doLinkAttribute(String assetId, Attribute<?> attribute, HTTPAgentLink agentLink) {
    AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
    String method = agentLink.getMethod().map(Enum::name).orElse(DEFAULT_HTTP_METHOD);
    String path = agentLink.getPath().orElse(null);
    String contentType = agentLink.getContentType().orElse(null);
    Map<String, List<String>> headers = agentLink.getHeaders().orElse(null);
    Map<String, List<String>> queryParams = agentLink.getQueryParameters().orElse(null);
    Integer pollingMillis = agentLink.getPollingMillis().map(millis -> Math.max(millis, MIN_POLLING_MILLIS)).orElse(null);
    boolean pagingEnabled = agentLink.getPagingMode().orElse(false);
    String pollingAttribute = agentLink.getPollingAttribute().orElse(null);
    if (!TextUtil.isNullOrEmpty(pollingAttribute)) {
        synchronized (pollingLinkedAttributeMap) {
            AttributeRef pollingSourceRef = new AttributeRef(attributeRef.getId(), pollingAttribute);
            pollingLinkedAttributeMap.compute(pollingSourceRef, (ref, links) -> {
                if (links == null) {
                    links = new HashSet<>();
                }
                links.add(attributeRef);
                return links;
            });
        }
    }
    String body = agentLink.getWriteValue().orElse(null);
    if (client == null) {
        LOG.warning("Client is undefined: " + this);
        return;
    }
    HttpClientRequest clientRequest = buildClientRequest(path, method, headers != null ? WebTargetBuilder.mapToMultivaluedMap(headers, new MultivaluedHashMap<>()) : null, queryParams != null ? WebTargetBuilder.mapToMultivaluedMap(queryParams, new MultivaluedHashMap<>()) : null, pagingEnabled, contentType);
    LOG.fine("Creating HTTP request for attributeRef '" + clientRequest + "': " + attributeRef);
    requestMap.put(attributeRef, clientRequest);
    Optional.ofNullable(pollingMillis).ifPresent(seconds -> pollingMap.put(attributeRef, schedulePollingRequest(attributeRef, agentLink, clientRequest, body, seconds)));
}
Also used : java.util(java.util) ScheduledFuture(java.util.concurrent.ScheduledFuture) Protocol(org.openremote.model.asset.agent.Protocol) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) URISyntaxException(java.net.URISyntaxException) AttributeRef(org.openremote.model.attribute.AttributeRef) ResponseBuilderImpl(org.jboss.resteasy.specimpl.ResponseBuilderImpl) ValueUtil(org.openremote.model.util.ValueUtil) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) HttpMethod(javax.ws.rs.HttpMethod) WebTargetBuilder(org.openremote.container.web.WebTargetBuilder) Level(java.util.logging.Level) AgentLink(org.openremote.model.asset.agent.AgentLink) MediaType(javax.ws.rs.core.MediaType) Attribute(org.openremote.model.attribute.Attribute) AttributeEvent(org.openremote.model.attribute.AttributeEvent) SyslogCategory(org.openremote.model.syslog.SyslogCategory) TextUtil(org.openremote.model.util.TextUtil) URI(java.net.URI) AttributeState(org.openremote.model.attribute.AttributeState) OAuthGrant(org.openremote.model.auth.OAuthGrant) ValueType(org.openremote.model.value.ValueType) QUERY_PARAMETERS_PROPERTY(org.openremote.container.web.QueryParameterInjectorFilter.QUERY_PARAMETERS_PROPERTY) URIBuilder(org.apache.http.client.utils.URIBuilder) Invocation(javax.ws.rs.client.Invocation) Logger(java.util.logging.Logger) Entity(javax.ws.rs.client.Entity) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) AbstractProtocol(org.openremote.agent.protocol.AbstractProtocol) Container(org.openremote.model.Container) PROTOCOL(org.openremote.model.syslog.SyslogCategory.PROTOCOL) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) BuiltResponse(org.jboss.resteasy.specimpl.BuiltResponse) Headers(org.jboss.resteasy.core.Headers) Response(javax.ws.rs.core.Response) Type(java.lang.reflect.Type) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) Annotation(java.lang.annotation.Annotation) WebTargetBuilder.createClient(org.openremote.container.web.WebTargetBuilder.createClient) UsernamePassword(org.openremote.model.auth.UsernamePassword) WebTarget(javax.ws.rs.client.WebTarget) QueryParameterInjectorFilter(org.openremote.container.web.QueryParameterInjectorFilter) ProtocolUtil(org.openremote.model.protocol.ProtocolUtil) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) AttributeRef(org.openremote.model.attribute.AttributeRef)

Example 4 with AgentLink

use of org.openremote.model.asset.agent.AgentLink in project openremote by openremote.

the class ValueUtil method doInitialise.

/**
 * Initialise the asset model and throw an {@link IllegalStateException} exception if a problem is detected; this
 * can be called by applications at startup to fail hard and fast if the asset model is un-usable
 */
protected static void doInitialise() throws IllegalStateException {
    assetInfoMap = new HashMap<>();
    assetTypeMap = new HashMap<>();
    agentLinkMap = new HashMap<>();
    metaItemDescriptors = new ArrayList<>();
    valueDescriptors = new ArrayList<>();
    generator = null;
    // Provide basic Object Mapper and enhance once asset model is initialised
    JSON = configureObjectMapper(new ObjectMapper());
    LOG.info("Initialising asset model...");
    Map<Class<? extends Asset<?>>, List<NameHolder>> assetDescriptorProviders = new TreeMap<>(new ClassHierarchyComparator());
    // noinspection RedundantCast
    assetDescriptorProviders.put((Class<? extends Asset<?>>) (Class<?>) Asset.class, new ArrayList<>(getDescriptorFields(Asset.class)));
    getModelProviders().forEach(assetModelProvider -> {
        LOG.fine("Processing asset model provider: " + assetModelProvider.getClass().getSimpleName());
        LOG.fine("Auto scan = " + assetModelProvider.useAutoScan());
        if (assetModelProvider.useAutoScan()) {
            Set<Class<? extends Asset<?>>> assetClasses = getAssetClasses(assetModelProvider);
            LOG.fine("Found " + assetClasses.size() + " asset class(es)");
            assetClasses.forEach(assetClass -> assetDescriptorProviders.computeIfAbsent(assetClass, aClass -> new ArrayList<>(getDescriptorFields(aClass))));
            ModelDescriptors modelDescriptors = assetModelProvider.getClass().getAnnotation(ModelDescriptors.class);
            if (modelDescriptors != null) {
                for (ModelDescriptor modelDescriptor : modelDescriptors.value()) {
                    Class<? extends Asset<?>> assetClass = (Class<? extends Asset<?>>) modelDescriptor.assetType();
                    assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
                        if (list == null) {
                            list = new ArrayList<>();
                        }
                        list.addAll(getDescriptorFields(modelDescriptor.provider()));
                        return list;
                    });
                }
            }
        }
        if (assetModelProvider.getAssetDescriptors() != null) {
            for (AssetDescriptor<?> assetDescriptor : assetModelProvider.getAssetDescriptors()) {
                Class<? extends Asset<?>> assetClass = assetDescriptor.getType();
                assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
                    if (list == null) {
                        list = new ArrayList<>();
                    }
                    list.add(assetDescriptor);
                    return list;
                });
            }
        }
        if (assetModelProvider.getAttributeDescriptors() != null) {
            assetModelProvider.getAttributeDescriptors().forEach((assetClass, attributeDescriptors) -> assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
                if (list == null) {
                    list = new ArrayList<>();
                }
                list.addAll(attributeDescriptors);
                return list;
            }));
        }
        if (assetModelProvider.getMetaItemDescriptors() != null) {
            assetModelProvider.getMetaItemDescriptors().forEach((assetClass, metaDescriptors) -> assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
                if (list == null) {
                    list = new ArrayList<>();
                }
                list.addAll(metaDescriptors);
                return list;
            }));
        }
        if (assetModelProvider.getValueDescriptors() != null) {
            assetModelProvider.getValueDescriptors().forEach((assetClass, valueDescriptors) -> assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
                if (list == null) {
                    list = new ArrayList<>();
                }
                list.addAll(valueDescriptors);
                return list;
            }));
        }
    });
    // Build each asset info checking that no conflicts occur
    Map<Class<? extends Asset<?>>, List<NameHolder>> copy = new HashMap<>(assetDescriptorProviders);
    assetDescriptorProviders.forEach((assetClass, descriptors) -> {
        // Skip abstract classes as a start point - they should be in the class hierarchy of concrete class
        if (!Modifier.isAbstract(assetClass.getModifiers())) {
            AssetTypeInfo assetInfo = buildAssetInfo(assetClass, copy);
            assetInfoMap.put(assetClass, assetInfo);
            assetTypeMap.put(assetInfo.getAssetDescriptor().getName(), assetClass);
            if (assetInfo.getAssetDescriptor() instanceof AgentDescriptor) {
                AgentDescriptor<?, ?, ?> agentDescriptor = (AgentDescriptor<?, ?, ?>) assetInfo.getAssetDescriptor();
                String agentLinkName = agentDescriptor.getAgentLinkClass().getSimpleName();
                if (agentLinkMap.containsKey(agentLinkName) && agentLinkMap.get(agentLinkName) != agentDescriptor.getAgentLinkClass()) {
                    throw new IllegalStateException("AgentLink simple class name must be unique, duplicate found for: " + agentDescriptor.getAgentLinkClass());
                }
                agentLinkMap.put(agentLinkName, agentDescriptor.getAgentLinkClass());
            }
        }
    });
    // Check each value type implements serializable interface
    List<ValueDescriptor<?>> nonSerializableValueDescriptors = new ArrayList<>();
    valueDescriptors.forEach(vd -> {
        if (!Serializable.class.isAssignableFrom(vd.getType())) {
            nonSerializableValueDescriptors.add(vd);
        }
    });
    if (!nonSerializableValueDescriptors.isEmpty()) {
        String vds = nonSerializableValueDescriptors.stream().map(ValueDescriptor::toString).collect(Collectors.joining(",\n"));
        throw new IllegalStateException("One or more value types do not implement java.io.Serializable: " + vds);
    }
    // Call on finished on each provider
    assetModelProviders.forEach(AssetModelProvider::onAssetModelFinished);
    // Add agent link sub types to object mapper (need to avoid circular dependency)
    NamedType[] agentLinkSubTypes = Arrays.stream(getAgentLinkClasses()).map(agentLinkClass -> new NamedType(agentLinkClass, agentLinkClass.getSimpleName())).toArray(NamedType[]::new);
    JSON.registerSubtypes(agentLinkSubTypes);
    doSchemaInit();
}
Also used : Reflections(org.reflections.Reflections) ModelDescriptor(org.openremote.model.ModelDescriptor) com.fasterxml.jackson.databind.node(com.fasterxml.jackson.databind.node) AgentLink(org.openremote.model.asset.agent.AgentLink) BigDecimal(java.math.BigDecimal) AgentDescriptor(org.openremote.model.asset.agent.AgentDescriptor) JavaTimeModule(com.fasterxml.jackson.datatype.jsr310.JavaTimeModule) NamedType(com.fasterxml.jackson.databind.jsontype.NamedType) BigInteger(java.math.BigInteger) SyslogCategory(org.openremote.model.syslog.SyslogCategory) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ConstraintViolation(javax.validation.ConstraintViolation) java.lang.reflect(java.lang.reflect) Entity(javax.persistence.Entity) ConstructorDetector(com.fasterxml.jackson.databind.cfg.ConstructorDetector) Predicate(java.util.function.Predicate) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AssetTypeInfo(org.openremote.model.asset.AssetTypeInfo) Validator(javax.validation.Validator) JsonAutoDetect(com.fasterxml.jackson.annotation.JsonAutoDetect) NotNull(javax.validation.constraints.NotNull) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Jdk8Module(com.fasterxml.jackson.datatype.jdk8.Jdk8Module) ClasspathHelper(org.reflections.util.ClasspathHelper) SimpleFilterProvider(com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider) Serializable(java.io.Serializable) ModelDescriptors(org.openremote.model.ModelDescriptors) JsonSchemaGenerator(com.kjetland.jackson.jsonSchema.JsonSchemaGenerator) Agent(org.openremote.model.asset.agent.Agent) IntStream(java.util.stream.IntStream) java.util(java.util) AssetDescriptor(org.openremote.model.asset.AssetDescriptor) Modifier.isStatic(java.lang.reflect.Modifier.isStatic) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Level(java.util.logging.Level) Attribute(org.openremote.model.attribute.Attribute) Validation(javax.validation.Validation) PropertyAccessor(com.fasterxml.jackson.annotation.PropertyAccessor) AssetModelProvider(org.openremote.model.AssetModelProvider) com.fasterxml.jackson.databind(com.fasterxml.jackson.databind) ConfigurationBuilder(org.reflections.util.ConfigurationBuilder) Asset(org.openremote.model.asset.Asset) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SerializationHelper(org.hibernate.internal.util.SerializationHelper) ParameterNamesModule(com.fasterxml.jackson.module.paramnames.ParameterNamesModule) SubTypesScanner(org.reflections.scanners.SubTypesScanner) org.openremote.model.value(org.openremote.model.value) Modifier.isPublic(java.lang.reflect.Modifier.isPublic) JsonCreator(com.fasterxml.jackson.annotation.JsonCreator) StandardModelProvider(org.openremote.model.StandardModelProvider) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) MODEL_AND_VALUES(org.openremote.model.syslog.SyslogCategory.MODEL_AND_VALUES) Serializable(java.io.Serializable) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AssetModelProvider(org.openremote.model.AssetModelProvider) NamedType(com.fasterxml.jackson.databind.jsontype.NamedType) Asset(org.openremote.model.asset.Asset) AgentDescriptor(org.openremote.model.asset.agent.AgentDescriptor) ModelDescriptors(org.openremote.model.ModelDescriptors) AssetTypeInfo(org.openremote.model.asset.AssetTypeInfo) ModelDescriptor(org.openremote.model.ModelDescriptor)

Example 5 with AgentLink

use of org.openremote.model.asset.agent.AgentLink in project openremote by openremote.

the class ProtocolUtil method createGenericAttributeMessageConsumer.

public static Consumer<String> createGenericAttributeMessageConsumer(String assetId, Attribute<?> attribute, AgentLink<?> agentLink, Supplier<Long> currentMillisSupplier, Consumer<AttributeState> stateConsumer) {
    ValueFilter[] matchFilters = agentLink.getMessageMatchFilters().orElse(null);
    ValuePredicate matchPredicate = agentLink.getMessageMatchPredicate().orElse(null);
    if (matchPredicate == null) {
        return null;
    }
    return message -> {
        if (!TextUtil.isNullOrEmpty(message)) {
            Object messageFiltered = applyValueFilters(message, matchFilters);
            if (messageFiltered != null) {
                if (matchPredicate.asPredicate(currentMillisSupplier).test(messageFiltered)) {
                    Protocol.LOG.finest("Inbound message meets attribute matching meta so writing state to state consumer for attribute: asssetId=" + assetId + ", attribute=" + attribute.getName());
                    stateConsumer.accept(new AttributeState(assetId, attribute.getName(), message));
                }
            }
        }
    };
}
Also used : NULL_LITERAL(org.openremote.model.util.ValueUtil.NULL_LITERAL) Protocol(org.openremote.model.asset.agent.Protocol) ArrayUtils(org.apache.commons.lang3.ArrayUtils) Hex(org.apache.commons.codec.binary.Hex) ValueUtil(org.openremote.model.util.ValueUtil) DYNAMIC_VALUE_PLACEHOLDER(org.openremote.model.asset.agent.Protocol.DYNAMIC_VALUE_PLACEHOLDER) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Level(java.util.logging.Level) ValueUtil.applyValueFilters(org.openremote.model.util.ValueUtil.applyValueFilters) AgentLink(org.openremote.model.asset.agent.AgentLink) Attribute(org.openremote.model.attribute.Attribute) Locale(java.util.Locale) TextUtil(org.openremote.model.util.TextUtil) JsonNodeType(com.fasterxml.jackson.databind.node.JsonNodeType) AttributeState(org.openremote.model.attribute.AttributeState) ValueType(org.openremote.model.value.ValueType) BinaryCodec(org.apache.commons.codec.binary.BinaryCodec) ValuePredicate(org.openremote.model.query.filter.ValuePredicate) Pair(org.openremote.model.util.Pair) Consumer(java.util.function.Consumer) ValueFilter(org.openremote.model.value.ValueFilter) TsIgnore(org.openremote.model.util.TsIgnore) Optional(java.util.Optional) AttributeLink(org.openremote.model.attribute.AttributeLink) AttributeExecuteStatus(org.openremote.model.attribute.AttributeExecuteStatus) AttributeState(org.openremote.model.attribute.AttributeState) ValuePredicate(org.openremote.model.query.filter.ValuePredicate) ValueFilter(org.openremote.model.value.ValueFilter)

Aggregations

AgentLink (org.openremote.model.asset.agent.AgentLink)5 Level (java.util.logging.Level)4 java.util (java.util)3 Consumer (java.util.function.Consumer)3 Logger (java.util.logging.Logger)3 Protocol (org.openremote.model.asset.agent.Protocol)3 Attribute (org.openremote.model.attribute.Attribute)3 Optional (java.util.Optional)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 AttributeEvent (org.openremote.model.attribute.AttributeEvent)2 AttributeExecuteStatus (org.openremote.model.attribute.AttributeExecuteStatus)2 AttributeRef (org.openremote.model.attribute.AttributeRef)2 AttributeState (org.openremote.model.attribute.AttributeState)2 SyslogCategory (org.openremote.model.syslog.SyslogCategory)2 TextUtil (org.openremote.model.util.TextUtil)2 ValueUtil (org.openremote.model.util.ValueUtil)2 ValueType (org.openremote.model.value.ValueType)2 JsonAutoDetect (com.fasterxml.jackson.annotation.JsonAutoDetect)1 JsonCreator (com.fasterxml.jackson.annotation.JsonCreator)1 JsonInclude (com.fasterxml.jackson.annotation.JsonInclude)1