Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Added protocol message processor and socket implementation with test

Rich Turnere883b1c15014
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractSocketCamelMessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractSocketCamelMessageProcessor.java
new file mode 100644
index 000000000..2dd589076
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractSocketCamelMessageProcessor.java
@@ -0,0 +1,371 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.agent.protocol;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelPromise;
+import io.netty.handler.codec.ByteToMessageDecoder;
+import io.netty.handler.codec.MessageToByteEncoder;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.util.URISupport;
+import org.openremote.container.message.MessageBrokerContext;
+import org.openremote.model.syslog.SyslogCategory;
+import org.openremote.model.util.TextUtil;
+
+import java.net.SocketAddress;
+import java.util.*;
+import java.util.function.Consumer;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
+
+/**
+ * This is a {@link MessageProcessor} implementation for sockets.
+ * <p>
+ * It uses the camel netty component for managing the socket connection.
+ * <p>
+ * A limitation of this implementation is that it is not possible to do bi-directional
+ * communication over a single socket connection, instead a separate consumer and producer
+ * are required which do not share the underlying connection.
+ */
+public abstract class AbstractSocketCamelMessageProcessor<T> implements MessageProcessor<T> {
+ protected class MessageDecoder extends ByteToMessageDecoder {
+ protected List<T> messages = new ArrayList<>(1);
+
+ @Override
+ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
+ AbstractSocketCamelMessageProcessor.this.decode(in, messages);
+ if (!messages.isEmpty()) {
+ out.addAll(messages);
+ messages.clear();
+ }
+ }
+
+ @Override
+ public void channelActive(ChannelHandlerContext ctx) throws Exception {
+ super.channelActive(ctx);
+ onConnectionStatusChanged(ConnectionStatus.CONNECTED);
+ }
+
+ @Override
+ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+ super.channelInactive(ctx);
+ onConnectionStatusChanged(ConnectionStatus.DISCONNECTED);
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+ super.exceptionCaught(ctx, cause);
+ LOG.log(Level.SEVERE, "Exception occurred on endpoint: " + consumerEndpointUri.orElse(""), cause);
+ onConnectionStatusChanged(ConnectionStatus.ERROR);
+ }
+ }
+
+ protected class MessageEncoder extends MessageToByteEncoder<T> {
+ @Override
+ public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception {
+ super.connect(ctx, remoteAddress, localAddress, promise);
+ }
+
+ @Override
+ protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out) throws Exception {
+ AbstractSocketCamelMessageProcessor.this.encode(msg, out);
+ }
+ }
+
+ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractSocketCamelMessageProcessor.class);
+ protected static final Integer[] instanceCounter = new Integer[1];
+ protected static final String registryPrefix = "SocketMessageProcessor-";
+ protected final int instanceId;
+ protected String host;
+ protected int port;
+ protected Class<T> clazz;
+ protected final List<Consumer<T>> messageConsumers = new ArrayList<>();
+ protected final List<Consumer<ConnectionStatus>> connectionStatusConsumers = new ArrayList<>();
+ protected ConnectionStatus connectionStatus = ConnectionStatus.DISCONNECTED;
+ protected MessageBrokerContext messageBrokerContext;
+ protected ProducerTemplate producerTemplate;
+ protected Map<String, Object> options;
+ protected Optional<String> consumerEndpointUri;
+ protected Optional<String> producerEndpointUri;
+ protected boolean initialisationDone;
+
+ static {
+ instanceCounter[0] = 1;
+ }
+
+ public AbstractSocketCamelMessageProcessor(Class<T> clazz, String host, int port, MessageBrokerContext messageBrokerContext, ProducerTemplate producerTemplate, Map<String, Object> options) {
+ TextUtil.requireNonNullAndNonEmpty(host);
+ Objects.requireNonNull(clazz);
+ Objects.requireNonNull(messageBrokerContext);
+ Objects.requireNonNull(producerTemplate);
+ this.clazz = clazz;
+ this.host = host;
+ this.port = port;
+ this.messageBrokerContext = messageBrokerContext;
+ this.producerTemplate = producerTemplate;
+ this.options = options != null ? options : new HashMap<>();
+ synchronized (instanceCounter) {
+ instanceId = instanceCounter[0]++;
+ }
+ }
+
+ @Override
+ public synchronized void connect() {
+ if (connectionStatus == ConnectionStatus.CONNECTED) {
+ LOG.finest("Already connected");
+ return;
+ }
+
+ if (!initialisationDone) {
+ // Initialise channel pipeline factories
+ initialise();
+ initialisationDone = true;
+ }
+
+ if (!consumerEndpointUri.isPresent()) {
+ LOG.fine("No endpoint URI so cannot continue");
+ return;
+ }
+
+ // Create camel producer and consumer routes
+ try {
+ messageBrokerContext.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+
+ from(consumerEndpointUri.get())
+ .routeId("SocketMessageProcessor" + instanceId)
+ .process(exchange -> {
+ T message = exchange.getIn().getBody(clazz);
+ onMessageReceived(message);
+ });
+ }
+ });
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Failed to create camel route for this endpoint URI", e);
+ }
+ }
+
+ @Override
+ public synchronized void disconnect() {
+ if (connectionStatus == ConnectionStatus.DISCONNECTED) {
+ LOG.finest("Already disconnected");
+ return;
+ }
+
+ try {
+ messageBrokerContext.stopRoute("SocketMessageProcessor" + instanceId);
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Failed to stop camel route", e);
+ }
+ }
+
+ @Override
+ public void sendMessage(T message) {
+ if (!producerEndpointUri.isPresent()) {
+ LOG.fine("Cannot send message as producer endpoint is not present");
+ return;
+ }
+
+ if (connectionStatus != ConnectionStatus.CONNECTED) {
+ LOG.fine("Cannot send message: Status = " + connectionStatus);
+ return;
+ }
+
+ try {
+ producerTemplate.sendBody(producerEndpointUri.get(), message);
+ LOG.finer("Message sent");
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Message send failed", e);
+ }
+ }
+
+ public ConnectionStatus getConnectionStatus() {
+ return connectionStatus;
+ }
+
+ @Override
+ public synchronized void addConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {
+ if (!connectionStatusConsumers.contains(connectionStatusConsumer)) {
+ connectionStatusConsumers.add(connectionStatusConsumer);
+ }
+ }
+
+ @Override
+ public synchronized void removeConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {
+ connectionStatusConsumers.remove(connectionStatusConsumer);
+ }
+
+ @Override
+ public synchronized void addMessageConsumer(Consumer<T> messageConsumer) {
+ if (!messageConsumers.contains(messageConsumer)) {
+ messageConsumers.add(messageConsumer);
+ }
+ }
+
+ @Override
+ public synchronized void removeMessageConsumer(Consumer<T> messageConsumer) {
+ messageConsumers.remove(messageConsumer);
+ }
+
+ /**
+ * Implementations of this message processor need to implement this method in order
+ * to decode incoming data.
+ * <p>
+ * When one or more messages are available in the {@link ByteBuf} then the messages
+ * should be constructed and added to the messages list
+ */
+ protected abstract void decode(ByteBuf buf, List<T> messages) throws Exception;
+
+ protected abstract void encode(T message, ByteBuf buf) throws Exception;
+
+ protected synchronized void initialise() {
+/*
+ SimpleRegistry registry = messageBrokerContext.getRegistry();
+ Map<String, ChannelHandler> encoders = getEncoders();
+ Map<String, ChannelHandler> decoders = getDecoders();
+ Set<String> encoderNames = null;
+ Set<String> decoderNames = null;
+
+ if (encoders != null) {
+ encoderNames = encoders.keySet();
+ encoders.forEach(
+ (name, handler) -> {
+ registry.put(registryPrefix + name, handler);
+ }
+ );
+ }
+ if (decoders != null) {
+ decoderNames = decoders.keySet();
+ decoders.forEach(
+ (name, handler) -> {
+ registry.put(registryPrefix + name, handler);
+ }
+ );
+ }
+
+ buildEndpointUris(host, port, encoderNames, decoderNames, options);
+*/
+ }
+
+/*
+ protected Map<String, ChannelHandler> getEncoders() {
+ Map<String, ChannelHandler> encoders = new HashMap<>();
+
+ encoders.put("StandardEncoder", new ChannelHandlerFactory() {
+ @Override
+ public ChannelHandler newChannelHandler() {
+ return new MessageEncoder();
+ }
+
+ @Override
+ public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
+
+ }
+
+ @Override
+ public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
+
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+
+ }
+ });
+ return encoders;
+ }
+
+ protected Map<String, ChannelHandler> getDecoders() {
+ Map<String, ChannelHandler> decoders = new HashMap<>();
+
+ decoders.put("StandardDecoder", new ChannelHandlerFactory() {
+ @Override
+ public ChannelHandler newChannelHandler() {
+ return new MessageDecoder();
+ }
+
+ @Override
+ public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
+
+ }
+
+ @Override
+ public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
+
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+
+ }
+ });
+ return decoders;
+ }
+*/
+
+ protected synchronized void onMessageReceived(T message) {
+ LOG.finer("Message received");
+ messageConsumers.forEach(consumer -> {
+ consumer.accept(message);
+ });
+ }
+
+ protected void onConnectionStatusChanged(ConnectionStatus connectionStatus) {
+ this.connectionStatus = connectionStatus;
+
+ synchronized (connectionStatusConsumers) {
+ connectionStatusConsumers.forEach(
+ consumer -> consumer.accept(connectionStatus)
+ );
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected void buildEndpointUris(String host, int port, Set<String> encoderNames, Set<String> decoderNames, Map<String, Object> options) {
+ try {
+
+ String encodersStr = encoderNames != null ? "&encoders=#" + registryPrefix + String.join(",#" + registryPrefix, encoderNames) : "";
+ String decodersStr = decoderNames != null ? "&decoders=#" + registryPrefix + String.join(",#" + registryPrefix, decoderNames) : "";
+
+ // Build endpoint URI with options
+ String uri = "netty4:tcp://"
+ + host + ":" + port
+ + "?disconnectOnNoReply=false"
+ + "&clientMode=true"
+ + "&sync=false"
+ + "&allowDefaultCodec=false"
+ + "&keepAlive=true"
+ + "&option.child.keepAlive=true"
+ + "&disconnect=false";
+ uri = URISupport.appendParametersToURI(uri, options);
+ producerEndpointUri = Optional.of(uri + encodersStr);
+ consumerEndpointUri = Optional.of(uri + decodersStr);
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Unable to construct endpoint URI", e);
+ producerEndpointUri = Optional.empty();
+ consumerEndpointUri = Optional.empty();
+ }
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractSocketMessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractSocketMessageProcessor.java
new file mode 100644
index 000000000..4a559775b
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractSocketMessageProcessor.java
@@ -0,0 +1,336 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.agent.protocol;
+
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.*;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioSocketChannel;
+import io.netty.handler.codec.ByteToMessageDecoder;
+import io.netty.handler.codec.MessageToByteEncoder;
+import org.openremote.model.syslog.SyslogCategory;
+import org.openremote.model.util.TextUtil;
+
+import java.net.SocketAddress;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ScheduledFuture;
+import java.util.function.Consumer;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
+
+/**
+ * This is a {@link MessageProcessor} implementation for sockets.
+ * <p>
+ * It uses the netty component for managing the socket connection.
+ * <p>
+ * By default it uses a single {@link ByteToMessageDecoder} to intercept incoming data and to delegate the construction
+ * of messages to the abstract {@link #decode} method.
+ * <p>
+ * For outgoing messages it uses a single
+ * {@link MessageToByteEncoder} to delegate the filling of the {@link ByteBuf} to the abstract {@link #encode} method.
+ * <p>
+ * Consumers wanting to add and/or replace the default encoder/decoder should override {@link #initChannel} and insert
+ * the desired {@link ChannelHandler}s into the pipeline.
+ * <p>
+ * <b>NOTE: Care must be taken when working with Netty {@link ByteBuf} as Netty uses reference counting to manage their
+ * lifecycle. Refer to the Netty documentation for more information.</b>
+ */
+public abstract class AbstractSocketMessageProcessor<T> implements MessageProcessor<T> {
+
+ protected class MessageDecoder extends ByteToMessageDecoder {
+ protected List<T> messages = new ArrayList<>(1);
+
+ @Override
+ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
+ AbstractSocketMessageProcessor.this.decode(in, messages);
+ if (!messages.isEmpty()) {
+ // Don't pass them along the channel pipeline just consume them
+ messages.forEach(
+ AbstractSocketMessageProcessor.this::onMessageReceived
+ );
+ messages.clear();
+ }
+ }
+
+ @Override
+ public void channelActive(ChannelHandlerContext ctx) throws Exception {
+ super.channelActive(ctx);
+ }
+
+ @Override
+ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+ super.channelInactive(ctx);
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+ super.exceptionCaught(ctx, cause);
+ LOG.log(Level.SEVERE, "Exception occurred on in-bound message: ", cause);
+ onConnectionStatusChanged(ConnectionStatus.ERROR);
+ }
+ }
+
+ protected class MessageEncoder extends MessageToByteEncoder<T> {
+ @Override
+ public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception {
+ super.connect(ctx, remoteAddress, localAddress, promise);
+ }
+
+ @Override
+ protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out) throws Exception {
+ AbstractSocketMessageProcessor.this.encode(msg, out);
+ }
+ }
+
+ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractSocketMessageProcessor.class);
+ protected final static int INITIAL_RECONNECT_DELAY_MILLIS = 1000;
+ protected final static int MAX_RECONNECT_DELAY_MILLIS = 60000;
+ protected final static int RECONNECT_BACKOFF_MULTIPLIER = 2;
+ protected final List<Consumer<T>> messageConsumers = new ArrayList<>();
+ protected final List<Consumer<ConnectionStatus>> connectionStatusConsumers = new ArrayList<>();
+ protected String host;
+ protected int port;
+ protected ConnectionStatus connectionStatus = ConnectionStatus.DISCONNECTED;
+ protected ChannelFuture channelFuture;
+ protected Channel channel;
+ protected Bootstrap bootstrap;
+ protected EventLoopGroup workerGroup;
+ protected ProtocolExecutorService executorService;
+ protected ScheduledFuture reconnectTask;
+ protected int reconnectDelayMilliseconds = INITIAL_RECONNECT_DELAY_MILLIS;
+
+ public AbstractSocketMessageProcessor(String host, int port, ProtocolExecutorService executorService) {
+ TextUtil.requireNonNullAndNonEmpty(host);
+ this.host = host;
+ this.port = port;
+ this.executorService = executorService;
+ }
+
+ @Override
+ public synchronized void connect() {
+ if (connectionStatus != ConnectionStatus.DISCONNECTED && connectionStatus != ConnectionStatus.WAITING) {
+ LOG.finest("Must be disconnected before calling connect");
+ return;
+ }
+
+ LOG.fine("Connecting");
+ onConnectionStatusChanged(ConnectionStatus.CONNECTING);
+
+ if (workerGroup == null) {
+ // TODO: In Netty 5 you can pass in an executor service but could pass in thread factory for now
+ workerGroup = new NioEventLoopGroup(1);
+ bootstrap = new Bootstrap();
+ bootstrap.channel(NioSocketChannel.class);
+ bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000);
+ bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
+ bootstrap.group(workerGroup);
+
+ bootstrap.handler(new ChannelInitializer<SocketChannel>() {
+ @Override
+ public void initChannel(SocketChannel channel) throws Exception {
+ AbstractSocketMessageProcessor.this.initChannel(channel);
+ }
+ });
+ }
+
+ // Start the client and store the channel
+ channelFuture = bootstrap.connect(host, port);
+ channel = channelFuture.channel();
+
+ // Add channel callback - this gets called when the channel connects or when channel encounters an error
+ channelFuture.addListener(new ChannelFutureListener() {
+ @Override
+ public void operationComplete(ChannelFuture future) throws Exception {
+ synchronized (AbstractSocketMessageProcessor.this) {
+ channelFuture.removeListener(this);
+
+ if (connectionStatus == ConnectionStatus.DISCONNECTING) {
+ return;
+ }
+
+ if (future.isSuccess()) {
+ LOG.fine("Successfully connected to: " + host + ":" + port);
+ reconnectTask = null;
+ reconnectDelayMilliseconds = INITIAL_RECONNECT_DELAY_MILLIS;
+ onConnectionStatusChanged(ConnectionStatus.CONNECTED);
+ } else if (future.cause() != null) {
+ LOG.log(Level.INFO, "Connection error", future.cause());
+ // Failed to connect so schedule reconnection attempt
+ scheduleReconnect();
+ }
+ }
+ }
+ });
+
+ // Add closed callback
+ channel.closeFuture().addListener(future -> {
+ if (connectionStatus != ConnectionStatus.DISCONNECTING) {
+ scheduleReconnect();
+ }
+ });
+ }
+
+ @Override
+ public synchronized void disconnect() {
+ if (connectionStatus == ConnectionStatus.DISCONNECTING || connectionStatus == ConnectionStatus.DISCONNECTED) {
+ LOG.finest("Already disconnecting or disconnected");
+ return;
+ }
+
+ LOG.finest("Disconnecting");
+ onConnectionStatusChanged(ConnectionStatus.DISCONNECTING);
+
+ try {
+ if (reconnectTask != null) {
+ reconnectTask.cancel(false);
+ }
+
+ if (channelFuture != null) {
+ channelFuture.cancel(true);
+ channelFuture.sync();
+ channelFuture = null;
+ }
+
+ // Close the channel
+ if (channel != null) {
+ channel.close().sync();
+ channel = null;
+ }
+ } catch (InterruptedException ignored) {
+
+ } finally {
+ if (workerGroup != null) {
+ workerGroup.shutdownGracefully();
+ workerGroup = null;
+ }
+ onConnectionStatusChanged(ConnectionStatus.DISCONNECTED);
+ }
+ }
+
+ @Override
+ public void sendMessage(T message) {
+ if (connectionStatus != ConnectionStatus.CONNECTED) {
+ LOG.fine("Cannot send message: Status = " + connectionStatus);
+ return;
+ }
+
+ try {
+ channel.writeAndFlush(message);
+ LOG.finer("Message sent");
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Message send failed", e);
+ }
+ }
+
+ @Override
+ public ConnectionStatus getConnectionStatus() {
+ return connectionStatus;
+ }
+
+ @Override
+ public synchronized void addConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {
+ if (!connectionStatusConsumers.contains(connectionStatusConsumer)) {
+ connectionStatusConsumers.add(connectionStatusConsumer);
+ }
+ }
+
+ @Override
+ public synchronized void removeConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {
+ connectionStatusConsumers.remove(connectionStatusConsumer);
+ }
+
+ @Override
+ public synchronized void addMessageConsumer(Consumer<T> messageConsumer) {
+ if (!messageConsumers.contains(messageConsumer)) {
+ messageConsumers.add(messageConsumer);
+ }
+ }
+
+ @Override
+ public synchronized void removeMessageConsumer(Consumer<T> messageConsumer) {
+ messageConsumers.remove(messageConsumer);
+ }
+
+ /**
+ * Inserts the decoders and encoders into the channel pipeline
+ */
+ protected void initChannel(SocketChannel channel) {
+ channel.pipeline().addLast(new MessageDecoder());
+ channel.pipeline().addLast(new MessageEncoder());
+ }
+
+ protected synchronized void onMessageReceived(T message) {
+ LOG.finer("Message received");
+ messageConsumers.forEach(consumer -> consumer.accept(message));
+ }
+
+ protected void onConnectionStatusChanged(ConnectionStatus connectionStatus) {
+ this.connectionStatus = connectionStatus;
+
+ synchronized (connectionStatusConsumers) {
+ connectionStatusConsumers.forEach(
+ consumer -> consumer.accept(connectionStatus)
+ );
+ }
+ }
+
+ protected synchronized void scheduleReconnect() {
+ if (reconnectTask != null) {
+ return;
+ }
+
+ onConnectionStatusChanged(ConnectionStatus.WAITING);
+
+ if (reconnectDelayMilliseconds < MAX_RECONNECT_DELAY_MILLIS) {
+ reconnectDelayMilliseconds *= RECONNECT_BACKOFF_MULTIPLIER;
+ reconnectDelayMilliseconds = Math.min(MAX_RECONNECT_DELAY_MILLIS, reconnectDelayMilliseconds);
+ }
+
+ LOG.finest("Scheduling reconnection in '" + reconnectDelayMilliseconds + "' milliseconds");
+
+ reconnectTask = executorService.schedule(() -> {
+ synchronized (AbstractSocketMessageProcessor.this) {
+ reconnectTask = null;
+
+ // Attempt to reconnect if not disconnecting
+ if (connectionStatus != ConnectionStatus.DISCONNECTING && connectionStatus != ConnectionStatus.DISCONNECTED) {
+ connect();
+ }
+ }
+ }, reconnectDelayMilliseconds);
+ }
+
+
+ /**
+ * Implementations of this message processor need to implement this method in order
+ * to decode incoming data.
+ * <p>
+ * When one or more messages are available in the {@link ByteBuf} then the messages
+ * should be constructed and added to the messages list
+ */
+ protected abstract void decode(ByteBuf buf, List<T> messages) throws Exception;
+
+ protected abstract void encode(T message, ByteBuf buf) throws Exception;
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/ConnectionStatus.java b/agent/src/main/java/org/openremote/agent/protocol/ConnectionStatus.java
new file mode 100644
index 000000000..703994093
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/ConnectionStatus.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.agent.protocol;
+
+import org.openremote.model.attribute.MetaItem;
+
+/**
+ * Indicates the status of a protocol configuration (i.e. protocol instance); but can also be used internally by a
+ * protocol if desired such as in {@link MessageProcessor}.
+ */
+public enum ConnectionStatus {
+
+ /**
+ * Not connected.
+ */
+ DISCONNECTED,
+
+ /**
+ * Connection in progress.
+ */
+ CONNECTING,
+
+ /**
+ * Disconnection in progress.
+ */
+ DISCONNECTING,
+
+ /**
+ * Connected.
+ */
+ CONNECTED,
+
+ /**
+ * Disabled.
+ * <p>
+ * For protocol configurations this generally means that it is not enabled (i.e. it has a
+ * {@link org.openremote.model.asset.AssetMeta#ENABLED} {@link MetaItem} with a value of <code>false</code>).
+ */
+ DISABLED,
+
+ /**
+ * An operation is being performed that means the status cannot be exactly determined at this time (e.g. the
+ * trying to re-establish a connection to a remote server).
+ */
+ WAITING,
+
+ /**
+ * Connection is closed and cannot be re-used.
+ */
+ CLOSED,
+
+ /**
+ * An authentication related error has occurred.
+ */
+ ERROR_AUTHENTICATION,
+
+ /**
+ * A general error has occurred that prevents normal operation.
+ */
+ ERROR
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/MessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/MessageProcessor.java
new file mode 100644
index 000000000..80168c494
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/MessageProcessor.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.agent.protocol;
+
+import java.util.function.Consumer;
+
+/**
+ * This is an abstraction for encoding/decoding messages for communication 'over the wire' in a generic way.
+ * <p>
+ * Implementors are responsible for handling the low level communication and for providing consumers with a mechanism
+ * for encoding/decoding messages of type &lt;T&gt;
+ *
+ * @param <T> Defines the message type that the instance will encode/decode
+ */
+public interface MessageProcessor<T> {
+
+ /**
+ * Send a message over the wire
+ */
+ void sendMessage(T message);
+
+ /**
+ * Add a consumer of received messages
+ */
+ void addMessageConsumer(Consumer<T> messageConsumer);
+
+ /**
+ * Remove a consumer of received messages
+ */
+ void removeMessageConsumer(Consumer<T> messageConsumer);
+
+ /**
+ * Add a consumer of connection status
+ */
+ void addConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer);
+
+ /**
+ * Remove a consumer of connection status
+ */
+ void removeConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer);
+
+ /**
+ * Get current connection status
+ */
+ ConnectionStatus getConnectionStatus();
+
+ /**
+ * Connect to the device
+ */
+ void connect();
+
+ /**
+ * Disconnect from the device
+ */
+ void disconnect();
+}
diff --git a/manager/test/src/main/groovy/org/openremote/test/SimpleSocketServer.java b/manager/test/src/main/groovy/org/openremote/test/SimpleSocketServer.java
new file mode 100644
index 000000000..4eba1d803
--- /dev/null
+++ b/manager/test/src/main/groovy/org/openremote/test/SimpleSocketServer.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.test;
+
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.*;
+import io.netty.channel.group.ChannelGroup;
+import io.netty.channel.group.DefaultChannelGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+import io.netty.util.concurrent.GlobalEventExecutor;
+
+import java.util.logging.Logger;
+
+/**
+ * Class for creating a simple socket server that echos back any received messages. Adapted from Netty example:
+ * <p>
+ * <a href="https://netty.io/wiki/user-guide-for-4.x.html#wiki-h2-4">https://netty.io/wiki/user-guide-for-4.x.html#wiki-h2-4</a>
+ * <p>
+ * The server can be configured as {@link #broadcastMode} which means that received messages are echoed to all connected
+ * clients.
+ * <p>
+ * There is also the {@link #sendMessage(byte[])} method for broadcasting an arbitrary array of data to connected
+ * clients.
+ */
+public class SimpleSocketServer {
+ private static final Logger LOG = Logger.getLogger(SimpleSocketServer.class.getName());
+ private int port;
+ private ChannelFuture channelFuture;
+ private EventLoopGroup bossGroup;
+ private EventLoopGroup workerGroup;
+ private boolean broadcastMode;
+ ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
+
+ public SimpleSocketServer(int port, boolean broadcastMode) {
+ this.port = port;
+ this.broadcastMode = broadcastMode;
+ }
+
+ public void start() throws InterruptedException {
+ bossGroup = new NioEventLoopGroup(); // (1)
+ workerGroup = new NioEventLoopGroup();
+ try {
+ LOG.info("Starting socket server on port: " + port);
+ ServerBootstrap b = new ServerBootstrap(); // (2)
+ b.group(bossGroup, workerGroup)
+ .channel(NioServerSocketChannel.class) // (3)
+ .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
+ @Override
+ public void initChannel(SocketChannel ch) throws Exception {
+ ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
+ @Override
+ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+ allChannels.remove(ctx.channel());
+ super.channelInactive(ctx);
+ }
+
+ @Override
+ public void channelActive(ChannelHandlerContext ctx) throws Exception {
+ allChannels.add(ctx.channel());
+ super.channelActive(ctx);
+ }
+
+ @Override
+ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+ if (broadcastMode) {
+ allChannels.writeAndFlush(msg);
+ } else {
+ ctx.write(msg);
+ ctx.flush();
+ }
+ }
+ });
+ }
+ })
+ .option(ChannelOption.SO_BACKLOG, 128)
+ .childOption(ChannelOption.SO_KEEPALIVE, true);
+
+ // Bind and start to accept incoming connections.
+ channelFuture = b.bind(port).sync();
+
+ } catch (InterruptedException e) {
+ stop();
+ }
+ }
+
+ public void stop() throws InterruptedException {
+ LOG.fine("Stopping socket server on port: " + port);
+
+ if (channelFuture != null) {
+ channelFuture.channel().close().sync();
+ }
+
+ if (workerGroup != null) {
+ workerGroup.shutdownGracefully().sync();
+ }
+ if (bossGroup != null) {
+ bossGroup.shutdownGracefully().sync();
+ }
+ }
+
+ public void sendMessage(byte[] message) {
+ LOG.fine("Sending message to all channels");
+ ByteBuf out = Unpooled.copiedBuffer(message);
+ allChannels.writeAndFlush(out);
+ }
+}
diff --git a/manager/test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovy b/manager/test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovy
new file mode 100644
index 000000000..7f940fdea
--- /dev/null
+++ b/manager/test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovy
@@ -0,0 +1,198 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.test.protocol
+
+import io.netty.buffer.ByteBuf
+import io.netty.util.CharsetUtil
+import org.openremote.agent.protocol.AbstractSocketMessageProcessor
+import org.openremote.agent.protocol.ConnectionStatus
+import org.openremote.manager.server.concurrent.ManagerExecutorService
+import org.openremote.test.ManagerContainerTrait
+import org.openremote.test.SimpleSocketServer
+import spock.lang.Specification
+import spock.util.concurrent.PollingConditions
+
+/**
+ * This tests the {@link AbstractSocketMessageProcessor} by creating a simple echo socket
+ * server that the message processor communicates with
+ */
+class SocketMessageProcessorTest extends Specification implements ManagerContainerTrait {
+
+ def "Check socket message processor"() {
+
+ given: "expected conditions"
+ def conditions = new PollingConditions(timeout: 10, delay: 1)
+
+ and: "a simple socket echo server"
+ def socketServerPort = findEphemeralPort();
+ def socketServer = new SimpleSocketServer(socketServerPort, true);
+
+ and: "the container is started"
+ def serverPort = findEphemeralPort()
+ def container = startContainer(defaultConfig(serverPort), Collections.singletonList(new ManagerExecutorService()))
+ def protocolExecutorService = container.getService(ManagerExecutorService.class)
+
+ and: "a simple socket message processor"
+ def messageProcessor = new AbstractSocketMessageProcessor<String>(
+ "localhost",
+ socketServerPort,
+ protocolExecutorService) {
+
+ @Override
+ protected void decode(ByteBuf buf, List<String> messages) throws Exception {
+ ByteBuf bytes = buf.readBytes(buf.readableBytes());
+ String msg = bytes.toString(CharsetUtil.UTF_8)
+ bytes.release()
+ messages.add(msg)
+ }
+
+ @Override
+ protected void encode(String message, ByteBuf buf) throws Exception {
+ buf.writeBytes(message.getBytes(CharsetUtil.UTF_8))
+ }
+ }
+
+ and: "we add callback consumers to the message processor"
+ def connectionStatus = messageProcessor.getConnectionStatus()
+ String lastMessage;
+ messageProcessor.addMessageConsumer({
+ message -> lastMessage = message
+ })
+ messageProcessor.addConnectionStatusConsumer({
+ status -> connectionStatus = status
+ })
+
+ when: "the server is started"
+ socketServer.start()
+
+ then: "the server should be connected"
+ conditions.eventually {
+ assert socketServer.channelFuture.isDone()
+ assert socketServer.channelFuture.isSuccess()
+ }
+
+ when: "we call connect on the message processor"
+ messageProcessor.connect()
+
+ then: "the message processor status should become CONNECTED"
+ conditions.eventually {
+ assert messageProcessor.connectionStatus == ConnectionStatus.CONNECTED
+ assert connectionStatus == ConnectionStatus.CONNECTED
+ }
+
+ when: "the server sends a message"
+ socketServer.sendMessage("Hello world".getBytes(CharsetUtil.UTF_8))
+
+ then: "we should receive the message"
+ conditions.eventually {
+ assert lastMessage == "Hello world"
+ }
+
+ when: "we send a message to the server"
+ messageProcessor.sendMessage("Test")
+
+ then: "we should get the same message back"
+ conditions.eventually {
+ assert lastMessage == "Test"
+ }
+
+ when: "we request the message processor to disconnect"
+ messageProcessor.disconnect()
+
+ then: "the message processor should become DISCONNECTED"
+ conditions.eventually {
+ assert messageProcessor.connectionStatus == ConnectionStatus.DISCONNECTED
+ assert connectionStatus == ConnectionStatus.DISCONNECTED
+ }
+
+ when: "we reconnect the same message processor"
+ messageProcessor.connect()
+
+ then: "the message processor status should become CONNECTED"
+ conditions.eventually {
+ assert messageProcessor.connectionStatus == ConnectionStatus.CONNECTED
+ assert connectionStatus == ConnectionStatus.CONNECTED
+ }
+
+ when: "the server sends a message"
+ socketServer.sendMessage("Is there anyone there?".getBytes(CharsetUtil.UTF_8))
+
+ then: "we should receive the message"
+ conditions.eventually {
+ assert lastMessage == "Is there anyone there?"
+ }
+
+ when: "we send a message to the server"
+ messageProcessor.sendMessage("Yes there is!")
+
+ then: "we should get the same message back"
+ conditions.eventually {
+ assert lastMessage == "Yes there is!"
+ }
+
+ when: "we lose connection to the server"
+ socketServer.stop()
+
+ then: "the message processor status should change to WAITING"
+ conditions.eventually {
+ assert messageProcessor.connectionStatus == ConnectionStatus.WAITING
+ assert connectionStatus == ConnectionStatus.WAITING
+ }
+
+ when: "the connection to the server is restored"
+ socketServer.start()
+
+ then: "the message processor status should become CONNECTED"
+ conditions.eventually {
+ assert messageProcessor.connectionStatus == ConnectionStatus.CONNECTED
+ assert connectionStatus == ConnectionStatus.CONNECTED
+ }
+
+ when: "the server sends a message"
+ socketServer.sendMessage("Is there anyone there?".getBytes(CharsetUtil.UTF_8))
+
+ then: "we should receive the message"
+ conditions.eventually {
+ assert lastMessage == "Is there anyone there?"
+ }
+
+ when: "we send a message to the server"
+ messageProcessor.sendMessage("Yes there is!")
+
+ then: "we should get the same message back"
+ conditions.eventually {
+ assert lastMessage == "Yes there is!"
+ }
+
+ when: "we request the processor to disconnect"
+ messageProcessor.disconnect()
+
+ then: "the message processor should become DISCONNECTED"
+ conditions.eventually {
+ assert messageProcessor.connectionStatus == ConnectionStatus.DISCONNECTED
+ assert connectionStatus == ConnectionStatus.DISCONNECTED
+ }
+
+ cleanup: "the server should be stopped"
+ messageProcessor.disconnect()
+ socketServer.stop()
+ stopContainer(container);
+ }
+}