Search in sources :

Example 1 with PROTOCOL

use of org.openremote.model.syslog.SyslogCategory.PROTOCOL in project openremote by openremote.

the class SNMPProtocol method doStart.

@Override
protected void doStart(Container container) throws Exception {
    String snmpBindHost = agent.getBindHost().orElseThrow(() -> {
        String msg = "No SNMP bind host provided for protocol: " + this;
        LOG.info(msg);
        return new IllegalArgumentException(msg);
    });
    Integer snmpBindPort = agent.getBindPort().orElse(162);
    SNMPAgent.SNMPVersion snmpVersion = agent.getSNMPVersion().orElse(SNMPAgent.SNMPVersion.V2c);
    String snmpUri = String.format("snmp:%s:%d?protocol=udp&type=TRAP&snmpVersion=%d", snmpBindHost, snmpBindPort, snmpVersion.getVersion());
    messageBrokerContext.addRoutes(new RouteBuilder() {

        @Override
        public void configure() {
            from(snmpUri).routeId(getProtocolName() + getAgent().getId()).process(exchange -> {
                SnmpMessage msg = exchange.getIn(SnmpMessage.class);
                LOG.fine(String.format("Message received: %s", msg));
                PDU pdu = msg.getSnmpMessage();
                AttributeRef wildCardAttributeRef;
                if ((wildCardAttributeRef = oidMap.get("*")) != null) {
                    ObjectNode wildCardValue = ValueUtil.createJsonObject();
                    pdu.getVariableBindings().forEach(variableBinding -> {
                        wildCardValue.put(variableBinding.getOid().format(), variableBinding.toValueString());
                    });
                    updateLinkedAttribute(new AttributeState(wildCardAttributeRef, wildCardValue));
                }
                pdu.getVariableBindings().forEach(variableBinding -> {
                    AttributeRef attributeRef = oidMap.get(variableBinding.getOid().format());
                    if (attributeRef != null) {
                        updateLinkedAttribute(new AttributeState(attributeRef, variableBinding.toValueString()));
                    }
                });
            });
        }
    });
    setConnectionStatus(ConnectionStatus.CONNECTED);
}
Also used : AttributeState(org.openremote.model.attribute.AttributeState) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) AttributeRef(org.openremote.model.attribute.AttributeRef) HashMap(java.util.HashMap) ValueUtil(org.openremote.model.util.ValueUtil) Logger(java.util.logging.Logger) PDU(org.snmp4j.PDU) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) AbstractProtocol(org.openremote.agent.protocol.AbstractProtocol) Container(org.openremote.model.Container) PROTOCOL(org.openremote.model.syslog.SyslogCategory.PROTOCOL) SnmpMessage(org.apache.camel.component.snmp.SnmpMessage) RouteBuilder(org.apache.camel.builder.RouteBuilder) Attribute(org.openremote.model.attribute.Attribute) AttributeEvent(org.openremote.model.attribute.AttributeEvent) Map(java.util.Map) SyslogCategory(org.openremote.model.syslog.SyslogCategory) PDU(org.snmp4j.PDU) AttributeState(org.openremote.model.attribute.AttributeState) RouteBuilder(org.apache.camel.builder.RouteBuilder) AttributeRef(org.openremote.model.attribute.AttributeRef) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) SnmpMessage(org.apache.camel.component.snmp.SnmpMessage)

Example 2 with PROTOCOL

use of org.openremote.model.syslog.SyslogCategory.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 3 with PROTOCOL

use of org.openremote.model.syslog.SyslogCategory.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)

Example 4 with PROTOCOL

use of org.openremote.model.syslog.SyslogCategory.PROTOCOL in project openremote by openremote.

the class AbstractHTTPServerProtocol method deploy.

protected void deploy(DeploymentInfo deploymentInfo) {
    LOG.info("Deploying JAX-RS deployment for protocol instance : " + this);
    DeploymentManager manager = Servlets.defaultContainer().addDeployment(deploymentInfo);
    manager.deploy();
    HttpHandler httpHandler;
    // Get realm from owning agent asset
    String agentRealm = agent.getRealm();
    if (TextUtil.isNullOrEmpty(agentRealm)) {
        throw new IllegalStateException("Cannot determine the realm that this agent belongs to");
    }
    try {
        httpHandler = manager.start();
        // Wrap the handler to inject the realm
        HttpHandler handlerWrapper = exchange -> {
            exchange.getRequestHeaders().put(HttpString.tryFromString(Constants.REALM_PARAM_NAME), agentRealm);
            httpHandler.handleRequest(exchange);
        };
        WebService.RequestHandler requestHandler = pathStartsWithHandler(deploymentInfo.getDeploymentName(), deploymentInfo.getContextPath(), handlerWrapper);
        LOG.info("Registering HTTP Server Protocol request handler '" + this.getClass().getSimpleName() + "' for request path: " + deploymentInfo.getContextPath());
        // Add the handler before the greedy deployment handler
        webService.getRequestHandlers().add(0, requestHandler);
        deployment = new DeploymentInstance(deploymentInfo, requestHandler);
    } catch (ServletException e) {
        LOG.severe("Failed to deploy deployment: " + deploymentInfo.getDeploymentName());
    }
}
Also used : java.util(java.util) ServletException(javax.servlet.ServletException) Application(javax.ws.rs.core.Application) ServletInfo(io.undertow.servlet.api.ServletInfo) HttpString(io.undertow.util.HttpString) Level(java.util.logging.Level) Servlets(io.undertow.servlet.Servlets) AgentLink(org.openremote.model.asset.agent.AgentLink) Lists(com.google.common.collect.Lists) ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) Attribute(org.openremote.model.attribute.Attribute) SyslogCategory(org.openremote.model.syslog.SyslogCategory) TextUtil(org.openremote.model.util.TextUtil) org.openremote.container.web(org.openremote.container.web) Constants(org.openremote.model.Constants) Logger(java.util.logging.Logger) DeploymentManager(io.undertow.servlet.api.DeploymentManager) Collectors(java.util.stream.Collectors) HttpServlet30Dispatcher(org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher) AbstractProtocol(org.openremote.agent.protocol.AbstractProtocol) HttpHandler(io.undertow.server.HttpHandler) Container(org.openremote.model.Container) PROTOCOL(org.openremote.model.syslog.SyslogCategory.PROTOCOL) IdentityService(org.openremote.container.security.IdentityService) CorsFilter(org.jboss.resteasy.plugins.interceptors.CorsFilter) JacksonConfig(org.openremote.container.json.JacksonConfig) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) Agent(org.openremote.model.asset.agent.Agent) Pattern(java.util.regex.Pattern) WebService.pathStartsWithHandler(org.openremote.container.web.WebService.pathStartsWithHandler) ServletException(javax.servlet.ServletException) HttpHandler(io.undertow.server.HttpHandler) DeploymentManager(io.undertow.servlet.api.DeploymentManager) HttpString(io.undertow.util.HttpString)

Aggregations

Logger (java.util.logging.Logger)4 Container (org.openremote.model.Container)4 Attribute (org.openremote.model.attribute.Attribute)4 SyslogCategory (org.openremote.model.syslog.SyslogCategory)4 PROTOCOL (org.openremote.model.syslog.SyslogCategory.PROTOCOL)4 AbstractProtocol (org.openremote.agent.protocol.AbstractProtocol)3 Agent (org.openremote.model.asset.agent.Agent)3 AgentLink (org.openremote.model.asset.agent.AgentLink)3 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Level (java.util.logging.Level)2 RouteBuilder (org.apache.camel.builder.RouteBuilder)2 ConnectionStatus (org.openremote.model.asset.agent.ConnectionStatus)2 AttributeEvent (org.openremote.model.attribute.AttributeEvent)2 AttributeRef (org.openremote.model.attribute.AttributeRef)2 AttributeState (org.openremote.model.attribute.AttributeState)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 Lists (com.google.common.collect.Lists)1 ByteBuf (io.netty.buffer.ByteBuf)1 Unpooled (io.netty.buffer.Unpooled)1