Search in sources :

Example 1 with Protocol

use of org.openremote.model.asset.agent.Protocol 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 Protocol

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

the class SimulatorService method getSimulatorState.

/**
 * Get info about all attributes linked to this instance (for frontend usage)
 */
protected SimulatorState getSimulatorState(SimulatorProtocol protocolInstance) {
    return withLockReturning(protocolInstance.getProtocolInstanceUri() + "::getSimulatorInfo", () -> {
        LOG.info("Getting simulator info for protocol instance: " + protocolInstance);
        // We need asset names instead of identifiers for user-friendly display
        List<String> linkedAssetIds = protocolInstance.getLinkedAttributes().keySet().stream().map(AttributeRef::getId).distinct().collect(Collectors.toList());
        List<String> assetNames = assetStorageService.findNames(linkedAssetIds.toArray(new String[0]));
        if (assetNames.size() != linkedAssetIds.size()) {
            LOG.warning("Retrieved asset names don't match requested asset IDs");
            return null;
        }
        SimulatorAttributeInfo[] attributeInfos = protocolInstance.getLinkedAttributes().entrySet().stream().map(refAttributeEntry -> {
            String assetName = assetNames.get(linkedAssetIds.indexOf(refAttributeEntry.getKey().getId()));
            return new SimulatorAttributeInfo(assetName, refAttributeEntry.getKey().getId(), refAttributeEntry.getValue(), protocolInstance.getReplayMap().containsKey(refAttributeEntry.getKey()));
        }).toArray(SimulatorAttributeInfo[]::new);
        return new SimulatorState(protocolInstance.getAgent().getId(), attributeInfos);
    });
}
Also used : AssetStorageService(org.openremote.manager.asset.AssetStorageService) MessageBrokerService(org.openremote.container.message.MessageBrokerService) SimulatorState(org.openremote.model.simulator.SimulatorState) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) AuthContext(org.openremote.container.security.AuthContext) Protocol(org.openremote.model.asset.agent.Protocol) CLIENT_EVENT_TOPIC(org.openremote.manager.event.ClientEventService.CLIENT_EVENT_TOPIC) AttributeRef(org.openremote.model.attribute.AttributeRef) SimulatorProtocol(org.openremote.agent.protocol.simulator.SimulatorProtocol) ContainerService(org.openremote.model.ContainerService) RequestSimulatorState(org.openremote.model.simulator.RequestSimulatorState) Constants(org.openremote.model.Constants) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Container(org.openremote.model.Container) GlobalLock.withLockReturning(org.openremote.container.concurrent.GlobalLock.withLockReturning) ClientEventService(org.openremote.manager.event.ClientEventService) List(java.util.List) RouteBuilder(org.apache.camel.builder.RouteBuilder) ClientEventService.getSessionKey(org.openremote.manager.event.ClientEventService.getSessionKey) AgentService(org.openremote.manager.agent.AgentService) SimulatorAttributeInfo(org.openremote.model.simulator.SimulatorAttributeInfo) AttributeRef(org.openremote.model.attribute.AttributeRef) SimulatorAttributeInfo(org.openremote.model.simulator.SimulatorAttributeInfo) SimulatorState(org.openremote.model.simulator.SimulatorState) RequestSimulatorState(org.openremote.model.simulator.RequestSimulatorState)

Example 3 with Protocol

use of org.openremote.model.asset.agent.Protocol 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 4 with Protocol

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

the class AbstractIOClientProtocol method getGenericStringEncodersAndDecoders.

/**
 * Supplies a set of encoders/decoders that convert from/to {@link String} to/from {@link ByteBuf} based on the generic protocol {@link Attribute}s
 */
public static Supplier<ChannelHandler[]> getGenericStringEncodersAndDecoders(AbstractNettyIOClient<String, ?> client, IOAgent<?, ?, ?> agent) {
    boolean hexMode = agent.getMessageConvertHex().orElse(false);
    boolean binaryMode = agent.getMessageConvertBinary().orElse(false);
    Charset charset = agent.getMessageCharset().map(Charset::forName).orElse(CharsetUtil.UTF_8);
    int maxLength = agent.getMessageMaxLength().orElse(Integer.MAX_VALUE);
    String[] delimiters = agent.getMessageDelimiters().orElse(new String[0]);
    boolean stripDelimiter = agent.getMessageStripDelimiter().orElse(false);
    return () -> {
        List<ChannelHandler> encodersDecoders = new ArrayList<>();
        if (hexMode || binaryMode) {
            encodersDecoders.add(new AbstractNettyIOClient.MessageToByteEncoder<>(String.class, client, (msg, out) -> {
                byte[] bytes = hexMode ? ProtocolUtil.bytesFromHexString(msg) : ProtocolUtil.bytesFromBinaryString(msg);
                out.writeBytes(bytes);
            }));
            if (delimiters.length > 0) {
                ByteBuf[] byteDelimiters = Arrays.stream(delimiters).map(delim -> Unpooled.wrappedBuffer(hexMode ? ProtocolUtil.bytesFromHexString(delim) : ProtocolUtil.bytesFromBinaryString(delim))).toArray(ByteBuf[]::new);
                encodersDecoders.add(new DelimiterBasedFrameDecoder(maxLength, stripDelimiter, byteDelimiters));
            } else {
                encodersDecoders.add(new FixedLengthFrameDecoder(maxLength));
            }
            // Incoming messages will be bytes
            encodersDecoders.add(new AbstractNettyIOClient.ByteToMessageDecoder<>(client, (byteBuf, messages) -> {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.readBytes(bytes);
                String msg = hexMode ? ProtocolUtil.bytesToHexString(bytes) : ProtocolUtil.bytesToBinaryString(bytes);
                messages.add(msg);
            }));
        } else {
            encodersDecoders.add(new StringEncoder(charset));
            if (agent.getMessageMaxLength().isPresent()) {
                encodersDecoders.add(new FixedLengthFrameDecoder(maxLength));
            } else {
                ByteBuf[] byteDelimiters;
                if (delimiters.length > 0) {
                    byteDelimiters = Arrays.stream(delimiters).map(delim -> Unpooled.wrappedBuffer(delim.getBytes(charset))).toArray(ByteBuf[]::new);
                } else {
                    byteDelimiters = Delimiters.lineDelimiter();
                }
                encodersDecoders.add(new DelimiterBasedFrameDecoder(maxLength, stripDelimiter, byteDelimiters));
            }
            encodersDecoders.add(new StringDecoder(charset));
            encodersDecoders.add(new AbstractNettyIOClient.MessageToMessageDecoder<>(String.class, client));
        }
        return encodersDecoders.toArray(new ChannelHandler[0]);
    };
}
Also used : Arrays(java.util.Arrays) Protocol(org.openremote.model.asset.agent.Protocol) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) Supplier(java.util.function.Supplier) Unpooled(io.netty.buffer.Unpooled) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) AgentLink(org.openremote.model.asset.agent.AgentLink) ByteBuf(io.netty.buffer.ByteBuf) Charset(java.nio.charset.Charset) Attribute(org.openremote.model.attribute.Attribute) AttributeEvent(org.openremote.model.attribute.AttributeEvent) CharsetUtil(io.netty.util.CharsetUtil) SyslogCategory(org.openremote.model.syslog.SyslogCategory) StringEncoder(io.netty.handler.codec.string.StringEncoder) Logger(java.util.logging.Logger) DelimiterBasedFrameDecoder(io.netty.handler.codec.DelimiterBasedFrameDecoder) FixedLengthFrameDecoder(io.netty.handler.codec.FixedLengthFrameDecoder) AbstractProtocol(org.openremote.agent.protocol.AbstractProtocol) Container(org.openremote.model.Container) PROTOCOL(org.openremote.model.syslog.SyslogCategory.PROTOCOL) List(java.util.List) StringDecoder(io.netty.handler.codec.string.StringDecoder) ChannelHandler(io.netty.channel.ChannelHandler) Agent(org.openremote.model.asset.agent.Agent) ProtocolUtil(org.openremote.model.protocol.ProtocolUtil) Delimiters(io.netty.handler.codec.Delimiters) DelimiterBasedFrameDecoder(io.netty.handler.codec.DelimiterBasedFrameDecoder) Charset(java.nio.charset.Charset) StringDecoder(io.netty.handler.codec.string.StringDecoder) ChannelHandler(io.netty.channel.ChannelHandler) ByteBuf(io.netty.buffer.ByteBuf) StringEncoder(io.netty.handler.codec.string.StringEncoder) FixedLengthFrameDecoder(io.netty.handler.codec.FixedLengthFrameDecoder) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

Logger (java.util.logging.Logger)4 Container (org.openremote.model.Container)4 Protocol (org.openremote.model.asset.agent.Protocol)4 RouteBuilder (org.apache.camel.builder.RouteBuilder)3 MessageBrokerService (org.openremote.container.message.MessageBrokerService)3 Agent (org.openremote.model.asset.agent.Agent)3 AgentLink (org.openremote.model.asset.agent.AgentLink)3 ConnectionStatus (org.openremote.model.asset.agent.ConnectionStatus)3 List (java.util.List)2 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2 Level (java.util.logging.Level)2 Collectors (java.util.stream.Collectors)2 GlobalLock.withLock (org.openremote.container.concurrent.GlobalLock.withLock)2 GlobalLock.withLockReturning (org.openremote.container.concurrent.GlobalLock.withLockReturning)2 TimerService (org.openremote.container.timer.TimerService)2 AssetStorageService (org.openremote.manager.asset.AssetStorageService)2 ClientEventService (org.openremote.manager.event.ClientEventService)2 ManagerIdentityService (org.openremote.manager.security.ManagerIdentityService)2 ContainerService (org.openremote.model.ContainerService)2 AttributeRef (org.openremote.model.attribute.AttributeRef)2