Search in sources :

Example 1 with Protocol

use of org.openremote.agent.protocol.Protocol in project openremote by openremote.

the class HttpClientProtocol method doLinkAttribute.

@Override
protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
    AttributeRef protocolConfigurationRef = protocolConfiguration.getReferenceOrThrow();
    Pair<ResteasyWebTarget, List<Integer>> clientAndFailureCodes;
    clientAndFailureCodes = clientMap.get(protocolConfigurationRef);
    WebTarget client = clientAndFailureCodes != null ? clientAndFailureCodes.key : null;
    if (client == null) {
        LOG.warning("Attempt to link attribute to non existent protocol configuration: " + attribute.getReferenceOrThrow());
        return;
    }
    String method = Values.getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_METHOD, StringValue.class, false, true).map(StringValue::getString).orElse(DEFAULT_HTTP_METHOD);
    String path = Values.getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_PATH, StringValue.class, false, true).map(StringValue::getString).orElse(null);
    String contentType = Values.getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_CONTENT_TYPE, StringValue.class, false, true).map(StringValue::getString).orElse(null);
    Value body = attribute.getMetaItem(META_ATTRIBUTE_BODY).flatMap(AbstractValueHolder::getValue).orElse(null);
    List<Integer> failureCodes = attribute.getMetaItem(META_FAILURE_CODES).flatMap(AbstractValueHolder::getValueAsArray).flatMap(arrayValue -> Values.getArrayElements(arrayValue, NumberValue.class, true, false, number -> Values.getIntegerCoerced(number).orElse(null))).map(fCodes -> {
        if (clientAndFailureCodes.value != null) {
            fCodes.addAll(clientAndFailureCodes.value);
        }
        return fCodes;
    }).orElseGet(() -> {
        if (clientAndFailureCodes.value != null) {
            return clientAndFailureCodes.value;
        }
        return null;
    });
    MultivaluedMap<String, String> headers = Values.getMetaItemValueOrThrow(attribute, META_HEADERS, ObjectValue.class, false, true).flatMap(objectValue -> getMultivaluedMap(objectValue, true)).orElse(null);
    MultivaluedMap<String, String> queryParams = Values.getMetaItemValueOrThrow(attribute, META_QUERY_PARAMETERS, ObjectValue.class, false, true).flatMap(objectValue -> getMultivaluedMap(objectValue, false)).orElse(null);
    Optional<Integer> pollingSeconds = Values.getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_POLLING_SECONDS, NumberValue.class, false, true).map(polling -> Values.getIntegerCoerced(polling).map(seconds -> seconds < 1 ? null : seconds).orElseThrow(() -> new IllegalArgumentException("Polling seconds meta item must be an integer >= 1")));
    final AttributeRef attributeRef = attribute.getReferenceOrThrow();
    boolean updateConnectionStatus = !pollingMap.containsKey(protocolConfigurationRef);
    HttpClientRequest clientRequest = buildClientRequest(client, path, method, headers, queryParams, failureCodes, updateConnectionStatus, body, contentType);
    LOG.fine("Creating HTTP request for linked attribute '" + clientRequest + "': " + attributeRef);
    requestMap.put(attributeRef, clientRequest);
    pollingSeconds.ifPresent(seconds -> pollingMap.put(attributeRef, schedulePollingRequest(attributeRef, protocolConfigurationRef, clientRequest, seconds)));
}
Also used : ScheduledFuture(java.util.concurrent.ScheduledFuture) ProtocolConfiguration(org.openremote.model.asset.agent.ProtocolConfiguration) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) HashMap(java.util.HashMap) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) HttpMethod(javax.ws.rs.HttpMethod) Level(java.util.logging.Level) Container(org.openremote.container.Container) MediaType(javax.ws.rs.core.MediaType) Future(java.util.concurrent.Future) Map(java.util.Map) TextUtil(org.openremote.model.util.TextUtil) PROTOCOL_NAMESPACE(org.openremote.model.Constants.PROTOCOL_NAMESPACE) AbstractValueHolder(org.openremote.model.AbstractValueHolder) Pair(org.openremote.model.util.Pair) IOException(java.io.IOException) 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) AssetMeta(org.openremote.model.asset.AssetMeta) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) List(java.util.List) org.openremote.model.value(org.openremote.model.value) Response(javax.ws.rs.core.Response) org.openremote.model.attribute(org.openremote.model.attribute) Optional(java.util.Optional) WebTarget(javax.ws.rs.client.WebTarget) AssetAttribute(org.openremote.model.asset.AssetAttribute) Protocol(org.openremote.agent.protocol.Protocol) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) List(java.util.List) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) WebTarget(javax.ws.rs.client.WebTarget)

Example 2 with Protocol

use of org.openremote.agent.protocol.Protocol in project openremote by openremote.

the class AgentService method linkAttributes.

protected void linkAttributes(AssetAttribute protocolConfiguration, Collection<AssetAttribute> attributes) {
    withLock(getClass().getSimpleName() + "::linkAttributes", () -> {
        LOG.fine("Linking all attributes that use protocol attribute: " + protocolConfiguration);
        Protocol protocol = getProtocol(protocolConfiguration);
        if (protocol == null) {
            LOG.severe("Cannot link protocol attributes as protocol is null: " + protocolConfiguration);
            return;
        }
        attributes.removeIf(attr -> linkedAttributes.contains(attr.getReferenceOrThrow()));
        linkedAttributes.addAll(attributes.stream().map(AssetAttribute::getReferenceOrThrow).collect(Collectors.toList()));
        try {
            LOG.finest("Linking protocol attributes to: " + protocol.getProtocolName());
            protocol.linkAttributes(attributes, protocolConfiguration);
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, "Ignoring error on linking attributes to protocol: " + protocol.getProtocolName(), ex);
            // Update the status of this protocol configuration to error
            publishProtocolConnectionStatus(protocolConfiguration.getReferenceOrThrow(), ERROR);
        }
    });
}
Also used : Protocol(org.openremote.agent.protocol.Protocol)

Example 3 with Protocol

use of org.openremote.agent.protocol.Protocol in project openremote by openremote.

the class AgentService method unlinkAttributes.

protected void unlinkAttributes(AssetAttribute protocolConfiguration, Collection<AssetAttribute> attributes) {
    withLock(getClass().getSimpleName() + "::unlinkAttributes", () -> {
        LOG.fine("Unlinking all attributes that use protocol attribute: " + protocolConfiguration);
        Protocol protocol = getProtocol(protocolConfiguration);
        if (protocol == null) {
            LOG.severe("Cannot unlink protocol attributes as protocol is null: " + protocolConfiguration);
            return;
        }
        attributes.removeIf(attr -> !linkedAttributes.contains(attr.getReferenceOrThrow()));
        linkedAttributes.removeAll(attributes.stream().map(AssetAttribute::getReferenceOrThrow).collect(Collectors.toList()));
        try {
            LOG.finest("Unlinking protocol attributes from: " + protocol.getProtocolName());
            protocol.unlinkAttributes(attributes, protocolConfiguration);
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, "Ignoring error on unlinking attributes from protocol: " + protocol.getProtocolName(), ex);
            // Update the status of this protocol configuration to error
            publishProtocolConnectionStatus(protocolConfiguration.getReferenceOrThrow(), ERROR);
        }
    });
}
Also used : Protocol(org.openremote.agent.protocol.Protocol)

Example 4 with Protocol

use of org.openremote.agent.protocol.Protocol in project openremote by openremote.

the class LocalAgentConnector method getDiscoveredLinkedAttributes.

@Override
public Asset[] getDiscoveredLinkedAttributes(AttributeRef protocolConfigurationRef, FileInfo fileInfo) throws IllegalArgumentException, UnsupportedOperationException, IllegalStateException {
    Optional<Pair<Protocol, AssetAttribute>> protocolAndConfigOptional = getProtocolAndConfig(protocolConfigurationRef);
    if (!protocolAndConfigOptional.isPresent()) {
        throw new IllegalArgumentException("Protocol not found for: " + protocolConfigurationRef);
    }
    Pair<Protocol, AssetAttribute> protocolAndConfig = protocolAndConfigOptional.get();
    // Check protocol is of correct type
    if (!(protocolAndConfigOptional.get().key instanceof ProtocolLinkedAttributeImport)) {
        LOG.info("Protocol not of type '" + ProtocolLinkedAttributeImport.class.getSimpleName() + "'");
        throw new UnsupportedOperationException("Protocol doesn't support linked attribute import:" + protocolAndConfigOptional.get().key.getProtocolDisplayName());
    }
    ProtocolLinkedAttributeImport discoveryProtocol = (ProtocolLinkedAttributeImport) protocolAndConfig.key;
    return discoveryProtocol.discoverLinkedAssetAttributes(protocolAndConfig.value, fileInfo);
}
Also used : ProtocolLinkedAttributeImport(org.openremote.agent.protocol.ProtocolLinkedAttributeImport) AssetAttribute(org.openremote.model.asset.AssetAttribute) Protocol(org.openremote.agent.protocol.Protocol) Pair(org.openremote.model.util.Pair)

Example 5 with Protocol

use of org.openremote.agent.protocol.Protocol in project openremote by openremote.

the class AgentService method processAssetChange.

/**
 * Looks for new, modified and obsolete AGENT_LINK attributes and links / unlinks them
 * with the protocol
 */
protected void processAssetChange(Asset asset, PersistenceEvent persistenceEvent) {
    LOG.finest("Processing asset persistence event: " + persistenceEvent.getCause());
    switch(persistenceEvent.getCause()) {
        case INSERT:
            // Asset insert persistence events can be fired before the agent insert persistence event
            // so need to check that all protocol configs exist - any that don't we will exclude here
            // and handle in agent insert
            // If an agent insert just occurred then we will end up trying to link the attribute again
            // so we keep track of linked attributes to avoid this
            // Link any AGENT_LINK attributes to their referenced protocol
            Map<AssetAttribute, List<AssetAttribute>> groupedAgentLinksAttributes = getGroupedAgentLinkAttributes(asset.getAttributesStream(), attribute -> true, attribute -> LOG.warning("Linked protocol configuration not found: " + attribute));
            groupedAgentLinksAttributes.forEach(this::linkAttributes);
            break;
        case UPDATE:
            List<String> propertyNames = Arrays.asList(persistenceEvent.getPropertyNames());
            // Check if attributes of the asset have been modified
            int attributesIndex = propertyNames.indexOf("attributes");
            if (attributesIndex < 0) {
                return;
            }
            // Attributes have possibly changed so need to compare old and new state to determine any changes to
            // AGENT_LINK attributes
            List<AssetAttribute> oldAgentLinkedAttributes = attributesFromJson((ObjectValue) persistenceEvent.getPreviousState()[attributesIndex], asset.getId()).filter(AgentLink::hasAgentLink).collect(Collectors.toList());
            List<AssetAttribute> newAgentLinkedAttributes = attributesFromJson((ObjectValue) persistenceEvent.getCurrentState()[attributesIndex], asset.getId()).filter(AgentLink::hasAgentLink).collect(Collectors.toList());
            // Unlink thing attributes that are in old but not in new
            getGroupedAgentLinkAttributes(getAddedOrModifiedAttributes(newAgentLinkedAttributes, oldAgentLinkedAttributes, key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME)), attribute -> true).forEach(this::unlinkAttributes);
            // Link thing attributes that are in new but not in old
            getGroupedAgentLinkAttributes(getAddedOrModifiedAttributes(oldAgentLinkedAttributes, newAgentLinkedAttributes, key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME)), attribute -> true, attribute -> LOG.warning("Linked protocol configuration not found: " + attribute)).forEach(this::linkAttributes);
            break;
        case DELETE:
            {
                // Unlink any AGENT_LINK attributes from the referenced protocol
                Map<AssetAttribute, List<AssetAttribute>> groupedAgentLinkAndProtocolAttributes = getGroupedAgentLinkAttributes(asset.getAttributesStream(), attribute -> true);
                groupedAgentLinkAndProtocolAttributes.forEach(this::unlinkAttributes);
                break;
            }
    }
}
Also used : PersistenceEvent(org.openremote.container.persistence.PersistenceEvent) java.util(java.util) ClientRole(org.openremote.model.security.ClientRole) WebService(org.openremote.container.web.WebService) AssetAttribute.getAddedOrModifiedAttributes(org.openremote.model.asset.AssetAttribute.getAddedOrModifiedAttributes) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) AttributeRef(org.openremote.model.attribute.AttributeRef) SENSOR_QUEUE(org.openremote.agent.protocol.Protocol.SENSOR_QUEUE) ASSET_QUEUE(org.openremote.manager.asset.AssetProcessingService.ASSET_QUEUE) ObjectValue(org.openremote.model.value.ObjectValue) Point(com.vividsolutions.jts.geom.Point) Level(java.util.logging.Level) ACTUATOR_TOPIC(org.openremote.agent.protocol.Protocol.ACTUATOR_TOPIC) GlobalLock.withLockReturning(org.openremote.container.concurrent.GlobalLock.withLockReturning) Container(org.openremote.container.Container) TenantFilter(org.openremote.model.event.shared.TenantFilter) ContainerService(org.openremote.container.ContainerService) AttributeEvent(org.openremote.model.attribute.AttributeEvent) org.openremote.model.asset(org.openremote.model.asset) AGENT(org.openremote.model.asset.AssetType.AGENT) AgentLink.getAgentLink(org.openremote.model.asset.agent.AgentLink.getAgentLink) MessageBrokerService(org.openremote.container.message.MessageBrokerService) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) SENSOR(org.openremote.model.attribute.AttributeEvent.Source.SENSOR) Predicate(java.util.function.Predicate) Pair(org.openremote.model.util.Pair) VALUE_TIMESTAMP_FIELD_NAME(org.openremote.model.AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME) AssetAttribute.attributesFromJson(org.openremote.model.asset.AssetAttribute.attributesFromJson) ProtocolAssetService(org.openremote.agent.protocol.ProtocolAssetService) EntityManager(javax.persistence.EntityManager) Logger(java.util.logging.Logger) MessageBrokerSetupService(org.openremote.container.message.MessageBrokerSetupService) Collectors(java.util.stream.Collectors) HEADER_SOURCE(org.openremote.model.attribute.AttributeEvent.HEADER_SOURCE) TextUtil.isValidURN(org.openremote.model.util.TextUtil.isValidURN) org.openremote.manager.asset(org.openremote.manager.asset) Consumer(java.util.function.Consumer) ClientEventService(org.openremote.manager.event.ClientEventService) Stream(java.util.stream.Stream) org.openremote.model.asset.agent(org.openremote.model.asset.agent) RouteBuilder(org.apache.camel.builder.RouteBuilder) TimerService(org.openremote.container.timer.TimerService) Source(org.openremote.model.attribute.AttributeEvent.Source) TextUtil.isNullOrEmpty(org.openremote.model.util.TextUtil.isNullOrEmpty) GlobalLock(org.openremote.container.concurrent.GlobalLock) Protocol(org.openremote.agent.protocol.Protocol) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) Point(com.vividsolutions.jts.geom.Point)

Aggregations

Protocol (org.openremote.agent.protocol.Protocol)7 Level (java.util.logging.Level)4 Logger (java.util.logging.Logger)4 Container (org.openremote.container.Container)4 GlobalLock.withLock (org.openremote.container.concurrent.GlobalLock.withLock)4 Consumer (java.util.function.Consumer)3 Collectors (java.util.stream.Collectors)3 EntityManager (javax.persistence.EntityManager)3 RouteBuilder (org.apache.camel.builder.RouteBuilder)3 ContainerService (org.openremote.container.ContainerService)3 MessageBrokerService (org.openremote.container.message.MessageBrokerService)3 MessageBrokerSetupService (org.openremote.container.message.MessageBrokerSetupService)3 TimerService (org.openremote.container.timer.TimerService)3 ClientEventService (org.openremote.manager.event.ClientEventService)3 ManagerIdentityService (org.openremote.manager.security.ManagerIdentityService)3 AgentLink.getAgentLink (org.openremote.model.asset.agent.AgentLink.getAgentLink)3 ConnectionStatus (org.openremote.model.asset.agent.ConnectionStatus)3 AttributeEvent (org.openremote.model.attribute.AttributeEvent)3 HEADER_SOURCE (org.openremote.model.attribute.AttributeEvent.HEADER_SOURCE)3 Source (org.openremote.model.attribute.AttributeEvent.Source)3