100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Added TCP Server protocol
Rich Turner96a5fc117669
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractNettyMessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractNettyMessageProcessor.javaindex 31df1cdb3..e08ab5a6e 100644--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractNettyMessageProcessor.java+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractNettyMessageProcessor.java@@ -56,49 +56,43 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;*/public abstract class AbstractNettyMessageProcessor<T> implements MessageProcessor<T> {- protected class MessageDecoder extends ByteToMessageDecoder {+ public class MessageDecoder extends ByteToMessageDecoder {protected List<T> messages = new ArrayList<>(1);@Override- protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {+ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {AbstractNettyMessageProcessor.this.decode(in, messages);+if (!messages.isEmpty()) {// Don't pass them along the channel pipeline just consume them- messages.forEach(- AbstractNettyMessageProcessor.this::onMessageReceived- );+ messages.forEach(AbstractNettyMessageProcessor.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);- }-@Overridepublic 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);+ AbstractNettyMessageProcessor.this.onEncodeException(ctx, cause);}}- protected class MessageEncoder extends MessageToByteEncoder<T> {+ public class MessageEncoder extends MessageToByteEncoder<T> {@Overridepublic 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 {+ protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out) {AbstractNettyMessageProcessor.this.encode(msg, out);}++ @Override+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {+ super.exceptionCaught(ctx, cause);+ AbstractNettyMessageProcessor.this.onDecodeException(ctx, cause);+ }}private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractNettyMessageProcessor.class);@@ -155,7 +149,7 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcessbootstrap.handler(new ChannelInitializer() {@Override- public void initChannel(Channel channel) throws Exception {+ public void initChannel(Channel channel) {AbstractNettyMessageProcessor.this.initChannel(channel);}});@@ -168,7 +162,7 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess// Add channel callback - this gets called when the channel connects or when channel encounters an errorchannelFuture.addListener(new ChannelFutureListener() {@Override- public void operationComplete(ChannelFuture future) throws Exception {+ public void operationComplete(ChannelFuture future) {synchronized (AbstractNettyMessageProcessor.this) {channelFuture.removeListener(this);@@ -177,10 +171,9 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess}if (future.isSuccess()) {- LOG.fine("Successfully connected to: " + getSocketAddressString());+ LOG.log(Level.INFO, "Connection initialising");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@@ -298,6 +291,30 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess* Inserts the decoders and encoders into the channel pipeline*/protected void initChannel(Channel channel) {+ channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {+ @Override+ public void channelActive(ChannelHandlerContext ctx) throws Exception {+ synchronized (AbstractNettyMessageProcessor.this) {+ LOG.fine("Connected: " + getSocketAddressString());+ onConnectionStatusChanged(ConnectionStatus.CONNECTED);+ }+ super.channelActive(ctx);+ }++ @Override+ public void channelInactive(ChannelHandlerContext ctx) throws Exception {+ synchronized (AbstractNettyMessageProcessor.this) {+ if (connectionStatus != ConnectionStatus.DISCONNECTING) {+ // This is a connection failure so ignore as reconnect logic will handle it+ return;+ }++ LOG.fine("Disconnected: " + getSocketAddressString());+ onConnectionStatusChanged(ConnectionStatus.DISCONNECTED);+ }+ super.channelInactive(ctx);+ }+ });channel.pipeline().addLast(new MessageDecoder());channel.pipeline().addLast(new MessageEncoder());}@@ -310,6 +327,16 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcessmessageConsumers.forEach(consumer -> consumer.accept(message));}+ protected void onDecodeException(ChannelHandlerContext ctx, Throwable cause) {+ LOG.log(Level.SEVERE, "Exception occurred on in-bound message: ", cause);+ onConnectionStatusChanged(ConnectionStatus.ERROR);+ }++ protected void onEncodeException(ChannelHandlerContext ctx, Throwable cause) {+ LOG.log(Level.SEVERE, "Exception occurred on out-bound message: ", cause);+ onConnectionStatusChanged(ConnectionStatus.ERROR);+ }+protected synchronized void onConnectionStatusChanged(ConnectionStatus connectionStatus) {this.connectionStatus = connectionStatus;@@ -354,7 +381,7 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess* 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 decode(ByteBuf buf, List<T> messages);- protected abstract void encode(T message, ByteBuf buf) throws Exception;+ protected abstract void encode(T message, ByteBuf buf);}diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.javaindex 7472a1eff..fb6845d2b 100644--- a/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java@@ -21,6 +21,7 @@ package org.openremote.agent.protocol.http;import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;import org.openremote.agent.protocol.AbstractProtocol;+import org.openremote.agent.protocol.Protocol;import org.openremote.container.Container;import org.openremote.model.AbstractValueHolder;import org.openremote.model.asset.AssetAttribute;@@ -78,7 +79,10 @@ import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;* <h1>Response filtering</h1>* <p>* Any {@link Attribute} whose value is to be set by the HTTP server response (i.e. it has an {@link- * #META_ATTRIBUTE_POLLING_SECONDS} {@link MetaItem}) can use the standard <h1>Connection Status</h1>+ * #META_ATTRIBUTE_POLLING_SECONDS} {@link MetaItem}) can use the standard {@link Protocol#META_PROTOCOL_FILTERS} in+ * order to filter the received HTTP response.+ *+ * <h1>Connection Status</h1>* <p>* The {@link ConnectionStatus} of the {@link ProtocolConfiguration} is determined by the ping {@link* org.openremote.model.attribute.MetaItem}s on the protocol configuration. If specified then the {@linkdiff --git a/agent/src/main/java/org/openremote/agent/protocol/io/AbstractIoServer.java b/agent/src/main/java/org/openremote/agent/protocol/io/AbstractIoServer.javanew file mode 100644index 000000000..05cbf3b71--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/io/AbstractIoServer.java@@ -0,0 +1,312 @@+/*+ * 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.io;++import io.netty.bootstrap.ServerBootstrap;+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.util.concurrent.GlobalEventExecutor;+import org.openremote.model.asset.agent.ConnectionStatus;+import org.openremote.model.syslog.SyslogCategory;++import java.net.SocketAddress;+import java.util.ArrayList;+import java.util.List;+import java.util.function.BiConsumer;+import java.util.logging.Level;+import java.util.logging.Logger;++import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;++/**+ * Abstract implementation of {@link IoServer} that uses the Netty library.+ */+// TODO: In Netty 5 you can pass in an executor service; can only pass in thread factory for now+public abstract class AbstractIoServer<T, U extends Channel> implements IoServer<T, U> {++ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractIoServer.class);+ protected int clientLimit = 0; // 0 means no limit+ protected ServerBootstrap bootstrap;+ protected ChannelFuture channelFuture;+ protected EventLoopGroup workerGroup;+ protected boolean started;+ protected final ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);+ protected final List<BiConsumer<U, T>> messageConsumers = new ArrayList<>();+ protected final List<BiConsumer<U, ConnectionStatus>> connectionStatusConsumers = new ArrayList<>();++ @Override+ public synchronized void start() {+ if (started) {+ return;+ }++ LOG.fine("Starting IO Server: " + getInstanceIdentifier());+ started = true;++ if (workerGroup == null) {+ workerGroup = getWorkerGroup();+ }++ workerGroup = new NioEventLoopGroup();++ try {+ bootstrap = new ServerBootstrap();+ bootstrap.channel(getServerChannelClass());+ bootstrap.group(workerGroup);+ bootstrap.localAddress(getLocalAddress());+ configureServerChannelOptions();+ configureClientChannelOptions();++ bootstrap.childHandler(new ChannelInitializer<U>() {+ @Override+ protected void initChannel(U channel) {+ AbstractIoServer.this.initClientChannel(channel);+ }+ });++ // Bind and start to accept incoming connections.+ channelFuture = bootstrap.bind().sync();+ allChannels.add(channelFuture.channel());++ } catch (Exception e) {+ LOG.log(Level.SEVERE, "An error occurred whilst starting the server so shutting down", e);+ stop();+ }+ }++ @Override+ public synchronized void stop() {+ if (!started) {+ return;+ }++ LOG.fine("Stopping IO Server: " + getInstanceIdentifier());+ started = false;++ try {+ if (channelFuture != null) {+ channelFuture.channel().close().sync();+ }++ if (workerGroup != null) {+ workerGroup.shutdownGracefully().sync();+ }+ } catch (InterruptedException ignored) {+ } finally {+ channelFuture = null;+ workerGroup = null;+ bootstrap = null;+ }+ }++ @Override+ public void addMessageConsumer(BiConsumer<U, T> messageConsumer) {+ LOG.finest("Adding message consumer");+ synchronized (messageConsumers) {+ messageConsumers.add(messageConsumer);+ }+ }++ @Override+ public void removeMessageConsumer(BiConsumer<U, T> messageConsumer) {+ LOG.finest("Removing message consumer");+ synchronized (messageConsumers) {+ messageConsumers.remove(messageConsumer);+ }+ }++ @Override+ public void addConnectionStatusConsumer(BiConsumer<U, ConnectionStatus> connectionStatusConsumer) {+ synchronized (connectionStatusConsumers) {+ connectionStatusConsumers.add(connectionStatusConsumer);+ }+ }++ @Override+ public void removeConnectionStatusConsumer(BiConsumer<U, ConnectionStatus> connectionStatusConsumer) {+ synchronized (connectionStatusConsumers) {+ connectionStatusConsumers.remove(connectionStatusConsumer);+ }+ }++ @Override+ public ConnectionStatus getConnectionStatus(U client) {+ return client.isActive() ? ConnectionStatus.CONNECTED : ConnectionStatus.DISCONNECTED;+ }++ @Override+ public void disconnectClient(U client) {+ LOG.finer("Disconnecting client: " + getClientDescriptor(client));+ client.close();+ }++ public boolean isStarted() {+ return started;+ }++ /**+ * Initialise the specified client channel (will be called when a new client connection is made)+ */+ protected void initClientChannel(U channel) {+ LOG.fine("Client initialising: " + getClientDescriptor(channel));++ // Add handler to track when a channel becomes active and to handle exceptions+ channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {+ @Override+ public void channelActive(ChannelHandlerContext ctx) throws Exception {+ onClientConnected(channel);+ super.channelActive(ctx);+ }++ @Override+ public void channelInactive(ChannelHandlerContext ctx) throws Exception {+ onClientDisconnected(channel);+ super.channelInactive(ctx);+ }++ @Override+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {+ onDecodeException(ctx, cause);+ super.exceptionCaught(ctx, cause);+ }+ });++ channel.pipeline().addLast(new ChannelOutboundHandlerAdapter() {+ @Override+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {+ onEncodeException(ctx, cause);+ super.exceptionCaught(ctx, cause);+ }+ });++ addDecoders(channel);+ addEncoders(channel);++ // Add handler to route the final messages+ channel.pipeline().addLast(new SimpleChannelInboundHandler<T>() {+ @Override+ protected void channelRead0(ChannelHandlerContext ctx, T msg) {+ onMessageReceived(channel, msg);+ }+ });+ }++ protected void onClientDisconnected(U client) {+ LOG.fine("Client disconnected: " + getClientDescriptor(client));+ // Channel group manages removal of stale channels but whilst we're here+ allChannels.remove(client);+ sendClientConnectionStatus(client, ConnectionStatus.DISCONNECTED);+ }++ protected void onClientConnected(U client) {+ LOG.fine("Client connected: " + getClientDescriptor(client));+ allChannels.add(client);+ sendClientConnectionStatus(client, ConnectionStatus.CONNECTED);+ }++ protected void sendClientConnectionStatus(U channel, ConnectionStatus connectionStatus) {+ synchronized (connectionStatusConsumers) {+ connectionStatusConsumers.forEach(statusConsumer+ -> statusConsumer.accept(channel, connectionStatus));+ }+ }++ protected void onMessageReceived(U channel, T message) {+ synchronized (messageConsumers) {+ messageConsumers.forEach(messageConsumer -> messageConsumer.accept(channel, message));+ }+ }++ protected void onDecodeException(ChannelHandlerContext ctx, Throwable cause) {+ LOG.log(Level.SEVERE, "Exception occurred on in-bound message: ", cause);+ // Forcibly close the client connection+ ctx.channel().close();+ }++ protected void onEncodeException(ChannelHandlerContext ctx, Throwable cause) {+ LOG.log(Level.SEVERE, "Exception occurred on out-bound message: ", cause);+ ctx.channel().close();+ }++ /**+ * Configure options to be applied to the server's own IO channel+ */+ protected void configureServerChannelOptions() {+ bootstrap.option(ChannelOption.SO_BACKLOG, clientLimit);+ }++ /**+ * Configure options to be applied to each client's IO channel+ */+ protected void configureClientChannelOptions() {+ bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);+ }++ @Override+ public void sendMessage(T message, U client) {+ try {+ client.writeAndFlush(message);+ LOG.finest("Message sent to client: " + getClientDescriptor(client));+ } catch (Exception e) {+ LOG.log(Level.WARNING, "Message send failed", e);+ }+ }++ @Override+ public void sendMessage(T message) {+ try {+ allChannels.writeAndFlush(message);+ LOG.finest("Message sent to all clients");+ } catch (Exception e) {+ LOG.log(Level.WARNING, "Message send failed", e);+ }+ }++ /**+ * Get a string identifier that uniquely identifies the current instance of this server. e.g. tcp://IP:PORT+ */+ protected abstract String getInstanceIdentifier();++ /**+ * Get the class to use for the server channel+ */+ protected abstract Class<? extends ServerChannel> getServerChannelClass();++ /**+ * Get the worker group event loop for the server+ */+ protected abstract EventLoopGroup getWorkerGroup();++ /**+ * Get the socket address to which this server should bind+ */+ protected abstract SocketAddress getLocalAddress();++ /**+ * Should return a descriptor to identify the speficied client for use in log files etc.+ */+ protected abstract String getClientDescriptor(U client);++ protected abstract void addDecoders(U channel);++ protected abstract void addEncoders(U channel);+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/io/IoServer.java b/agent/src/main/java/org/openremote/agent/protocol/io/IoServer.javanew file mode 100644index 000000000..5f30ae718--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/io/IoServer.java@@ -0,0 +1,88 @@+/*+ * 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.io;++import org.openremote.model.asset.agent.ConnectionStatus;++import java.util.function.BiConsumer;+import java.util.function.Consumer;++/**+ * Represents an IO server that accepts incoming clients.+ * <p>+ * Implementors are responsible for handling the low level communication and for providing consumers with a mechanism+ * for encoding/decoding messages of type <T>+ *+ * @param <T> Defines the message type that the server can send/receive+ * @param <U> Defines the client identifier type that can be used to uniquely identify clients connected to this server+ */+public interface IoServer<T, U> {++ /**+ * Send a message to a client+ */+ void sendMessage(T message, U client);++ /**+ * Send a message to all clients+ */+ void sendMessage(T message);++ /**+ * Add a consumer of received messages+ */+ void addMessageConsumer(BiConsumer<U, T> messageConsumer);++ /**+ * Remove a consumer of received messages+ */+ void removeMessageConsumer(BiConsumer<U, T> messageConsumer);++ /**+ * Add a consumer of client connection status changes+ */+ void addConnectionStatusConsumer(BiConsumer<U, ConnectionStatus> connectionStatusConsumer);++ /**+ * Remove a consumer of client connection status changes+ */+ void removeConnectionStatusConsumer(BiConsumer<U, ConnectionStatus> connectionStatusConsumer);++ /**+ * Get current connection status of a client (either {@link ConnectionStatus#CONNECTED} or+ * {@link ConnectionStatus#DISCONNECTED})+ */+ ConnectionStatus getConnectionStatus(U client);++ /**+ * Forcibly close the connection to a client+ */+ void disconnectClient(U client);++ /**+ * Start the server+ */+ void start();++ /**+ * Stop the server+ */+ void stop();+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpServerProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpServerProtocol.javanew file mode 100644index 000000000..2ad9f1534--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpServerProtocol.java@@ -0,0 +1,126 @@+/*+ * 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.tcp;++import io.netty.channel.socket.SocketChannel;+import org.openremote.agent.protocol.AbstractProtocol;+import org.openremote.model.AbstractValueHolder;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.agent.ConnectionStatus;+import org.openremote.model.asset.agent.ProtocolConfiguration;+import org.openremote.model.attribute.Attribute;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.value.StringValue;+import org.openremote.model.value.Values;++import java.util.HashMap;+import java.util.Map;+import java.util.Optional;+import java.util.function.BiConsumer;+import java.util.logging.Logger;++import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;++/**+ * This is an abstract protocol for creating TCP Server protocols. This allows TCP clients to connect and exchange data.+ * It is up to the concrete implementations whether or not linked {@link Attribute}s can be used with this protocol and+ * to define the semantics of these linked attributes.+ * <p>+ * <h1>Protocol Configurations</h1>+ * An instance is created by defining a {@link ProtocolConfiguration} with the following {@link MetaItem}s:+ * <ul>+ * <li>{@link #META_PROTOCOL_PORT} <b>(required)</b></li>+ * <li>{@link #META_PROTOCOL_BIND_ADDRESS}</li>+ * </ul>+ */+public abstract class AbstractTcpServerProtocol<T extends TcpServer<U>, U> extends AbstractProtocol {++ public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":tcpServer";++ /**+ * Sets the port that this server will bind to.+ */+ public static final String META_PROTOCOL_PORT = PROTOCOL_NAME + ":port";+ /**+ * Sets the network interface that this server will bind to; if not defined then the server+ * will bind to all network interfaces.+ */+ public static final String META_PROTOCOL_BIND_ADDRESS = PROTOCOL_NAME + ":bindAddress";++ private static final Logger LOG = Logger.getLogger(AbstractTcpServerProtocol.class.getName());+ protected Map<AttributeRef, T> tcpServerMap = new HashMap<>();++ @Override+ protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ final AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();++ if (!protocolConfiguration.isEnabled()) {+ updateStatus(protocolRef, ConnectionStatus.DISABLED);+ return;+ }++ int port = protocolConfiguration.getMetaItem(META_PROTOCOL_PORT)+ .flatMap(AbstractValueHolder::getValueAsInteger)+ .orElseThrow(() ->+ new IllegalArgumentException("Missing or invalid require meta item: " + META_PROTOCOL_PORT));++ Optional<StringValue> bindAddress = Values.getMetaItemValueOrThrow(+ protocolConfiguration,+ META_PROTOCOL_BIND_ADDRESS,+ StringValue.class,+ false,+ true+ );++ LOG.info("Creating TCP server instance");+ T tcpServer = createTcpServer(port, bindAddress.map(StringValue::getString).orElse(null), protocolConfiguration);+ tcpServerMap.put(protocolRef, tcpServer);+ startTcpServer(protocolRef, tcpServer);+ updateStatus(protocolRef, ConnectionStatus.CONNECTED);+ }++ @Override+ protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ final AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();++ T tcpServer = tcpServerMap.remove(protocolRef);++ if (tcpServer == null) {+ return;+ }++ LOG.info("Removing TCP server instance");+ stopTcpServer(protocolRef, tcpServer);+ updateStatus(protocolRef, ConnectionStatus.DISCONNECTED);+ }++ protected abstract T createTcpServer(int port, String bindAddress, AssetAttribute protocolConfiguration);++ protected void startTcpServer(AttributeRef protocolRef, T tcpServer) {+ LOG.info("Starting TCP server instance");+ tcpServer.start();+ }++ protected void stopTcpServer(AttributeRef protocolRef, T tcpServer) {+ LOG.info("Stopping TCP server instance");+ tcpServer.stop();+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/tcp/TcpServer.java b/agent/src/main/java/org/openremote/agent/protocol/tcp/TcpServer.javanew file mode 100644index 000000000..3b94183fb--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/tcp/TcpServer.java@@ -0,0 +1,69 @@+/*+ * 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.tcp;++import io.netty.channel.EventLoopGroup;+import io.netty.channel.ServerChannel;+import io.netty.channel.nio.NioEventLoopGroup;+import io.netty.channel.socket.SocketChannel;+import io.netty.channel.socket.nio.NioServerSocketChannel;+import org.openremote.agent.protocol.io.AbstractIoServer;++import java.net.InetSocketAddress;+import java.net.SocketAddress;++/**+ * Abstract IO Server for creating TCP socket servers that clients can connect to. Concrete implementation need+ * to configure the pipeline with the necessary encoders and decoders to ensure messages of type <T> are+ * generated/consumed at/from the end/start of the pipeline.+ */+public abstract class TcpServer<T> extends AbstractIoServer<T, SocketChannel> {++ protected SocketAddress localAddress;++ public TcpServer(InetSocketAddress localAddress) {+ this.localAddress = localAddress;+ }++ @Override+ protected String getInstanceIdentifier() {+ return localAddress == null ? null : "tcp://" + localAddress;+ }++ @Override+ protected Class<? extends ServerChannel> getServerChannelClass() {+ return NioServerSocketChannel.class;+ }++ @Override+ protected EventLoopGroup getWorkerGroup() {+ return new NioEventLoopGroup();+ }++ @Override+ protected SocketAddress getLocalAddress() {+ return localAddress;+ }++ @Override+ protected String getClientDescriptor(SocketChannel client) {+ return client == null || client.remoteAddress() == null ? null : "tcp://" + client.remoteAddress();+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/tcp/TcpStringServer.java b/agent/src/main/java/org/openremote/agent/protocol/tcp/TcpStringServer.javanew file mode 100644index 000000000..4045284ec--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/tcp/TcpStringServer.java@@ -0,0 +1,61 @@+/*+ * 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.tcp;++import io.netty.buffer.Unpooled;+import io.netty.channel.socket.SocketChannel;+import io.netty.handler.codec.DelimiterBasedFrameDecoder;+import io.netty.handler.codec.string.StringDecoder;+import io.netty.handler.codec.string.StringEncoder;++import java.net.InetSocketAddress;++/**+ * This is an {@link TcpServer} implementation that handles {@link String} messages.+ * <p>+ * Uses {@link DelimiterBasedFrameDecoder} and {@link StringDecoder}.+ */+public class TcpStringServer extends TcpServer<String> {++ protected String delimiter;+ protected int maxFrameLength;+ protected boolean stripDelimiter;++ public TcpStringServer(InetSocketAddress localAddress, String delimiter, int maxFrameLength, boolean stripDelimiter) {+ super(localAddress);+ this.delimiter = delimiter;+ this.maxFrameLength = maxFrameLength;+ this.stripDelimiter = stripDelimiter;+ }++ @Override+ protected void addDecoders(SocketChannel channel) {+ // Add delimiter and string decoders to do the work+ channel.pipeline().addLast(+ new DelimiterBasedFrameDecoder(maxFrameLength, stripDelimiter, Unpooled.wrappedBuffer(delimiter.getBytes()))+ );+ channel.pipeline().addLast(new StringDecoder());+ }++ @Override+ protected void addEncoders(SocketChannel channel) {+ channel.pipeline().addLast(new StringEncoder());+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusPacketEncoderDecoder.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusPacketEncoderDecoder.javaindex 1684d3d4e..7ab35539f 100644--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusPacketEncoderDecoder.java+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusPacketEncoderDecoder.java@@ -28,7 +28,7 @@ import static org.openremote.agent.protocol.velbus.VelbusPacket.MAX_PACKET_SIZE;public final class VelbusPacketEncoderDecoder {private VelbusPacketEncoderDecoder() {}- public static void decode(ByteBuf buf, List<VelbusPacket> messages) throws Exception {+ public static void decode(ByteBuf buf, List<VelbusPacket> messages) {int startIndex = buf.indexOf(0, buf.capacity() - 1, VelbusPacket.STX);if (startIndex < 0) {@@ -71,7 +71,7 @@ public final class VelbusPacketEncoderDecoder {}}- public static void encode(VelbusPacket message, ByteBuf buf) throws Exception {+ public static void encode(VelbusPacket message, ByteBuf buf) {buf.writeBytes(message.pack());}}diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialMessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialMessageProcessor.javaindex 7c639d0c6..74ac5539a 100644--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialMessageProcessor.java+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialMessageProcessor.java@@ -32,12 +32,12 @@ public class VelbusSerialMessageProcessor extends AbstractSerialMessageProcessor}@Override- protected void decode(ByteBuf buf, List<VelbusPacket> messages) throws Exception {+ protected void decode(ByteBuf buf, List<VelbusPacket> messages) {VelbusPacketEncoderDecoder.decode(buf, messages);}@Override- protected void encode(VelbusPacket message, ByteBuf buf) throws Exception {+ protected void encode(VelbusPacket message, ByteBuf buf) {VelbusPacketEncoderDecoder.encode(message, buf);}}diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSocketMessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSocketMessageProcessor.javaindex 16ee2fc40..a6b775a64 100644--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSocketMessageProcessor.java+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSocketMessageProcessor.java@@ -31,12 +31,12 @@ public class VelbusSocketMessageProcessor extends AbstractSocketMessageProcessorsuper(host, port, executorService);}@Override- protected void decode(ByteBuf buf, List<VelbusPacket> messages) throws Exception {+ protected void decode(ByteBuf buf, List<VelbusPacket> messages) {VelbusPacketEncoderDecoder.decode(buf, messages);}@Override- protected void encode(VelbusPacket message, ByteBuf buf) throws Exception {+ protected void encode(VelbusPacket message, ByteBuf buf) {VelbusPacketEncoderDecoder.encode(message, buf);}}diff --git a/gradle.properties b/gradle.propertiesindex b4c4163a6..516aa815b 100644--- a/gradle.properties+++ b/gradle.properties@@ -38,5 +38,5 @@ uuidGeneratorVersion = 3.1.3nrjavaserialVersion = 3.13.0saxonHEVersion = 9.8.0-3jmxtermVersion = 1.0.0-nettyVersion = 4.1.16.Final+nettyVersion = 4.1.19.FinalflywaydbVersion = 4.2.0\ No newline at end of filediff --git a/test/src/main/groovy/org/openremote/test/SimpleSocketServer.java b/test/src/main/groovy/org/openremote/test/SimpleSocketServer.javadeleted file mode 100644index 4eba1d803..000000000--- a/test/src/main/groovy/org/openremote/test/SimpleSocketServer.java+++ /dev/null@@ -1,127 +0,0 @@-/*- * 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/test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovyindex 9caa77e6b..1dd4446fc 100644--- a/test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovy@@ -22,10 +22,11 @@ package org.openremote.test.protocolimport io.netty.buffer.ByteBufimport io.netty.util.CharsetUtilimport org.openremote.agent.protocol.AbstractSocketMessageProcessor+import org.openremote.agent.protocol.tcp.TcpStringServerimport org.openremote.model.asset.agent.ConnectionStatusimport org.openremote.manager.concurrent.ManagerExecutorServiceimport org.openremote.test.ManagerContainerTrait-import org.openremote.test.SimpleSocketServer+import spock.lang.Specificationimport spock.util.concurrent.PollingConditions@@ -42,7 +43,10 @@ class SocketMessageProcessorTest extends Specification implements ManagerContainand: "a simple socket echo server"def socketServerPort = findEphemeralPort()- def socketServer = new SimpleSocketServer(socketServerPort, true)+ def socketServer = new TcpStringServer(new InetSocketAddress(socketServerPort), ";", Integer.MAX_VALUE, true)+ socketServer.addMessageConsumer({+ channel, message -> socketServer.sendMessage(message)+ })and: "the container is started"def serverPort = findEphemeralPort()@@ -56,7 +60,7 @@ class SocketMessageProcessorTest extends Specification implements ManagerContainprotocolExecutorService) {@Override- protected void decode(ByteBuf buf, List<String> messages) throws Exception {+ protected void decode(ByteBuf buf, List<String> messages) {ByteBuf bytes = buf.readBytes(buf.readableBytes())String msg = bytes.toString(CharsetUtil.UTF_8)bytes.release()@@ -64,7 +68,7 @@ class SocketMessageProcessorTest extends Specification implements ManagerContain}@Override- protected void encode(String message, ByteBuf buf) throws Exception {+ protected void encode(String message, ByteBuf buf) {buf.writeBytes(message.getBytes(CharsetUtil.UTF_8))}}@@ -82,7 +86,7 @@ class SocketMessageProcessorTest extends Specification implements ManagerContainwhen: "the server is started"socketServer.start()- then: "the server should be connected"+ then: "the server should be running"conditions.eventually {assert socketServer.channelFuture.isDone()assert socketServer.channelFuture.isSuccess()@@ -98,7 +102,7 @@ class SocketMessageProcessorTest extends Specification implements ManagerContain}when: "the server sends a message"- socketServer.sendMessage("Hello world".getBytes(CharsetUtil.UTF_8))+ socketServer.sendMessage("Hello world")then: "we should receive the message"conditions.eventually {@@ -106,7 +110,7 @@ class SocketMessageProcessorTest extends Specification implements ManagerContain}when: "we send a message to the server"- messageProcessor.sendMessage("Test")+ messageProcessor.sendMessage("Test;")then: "we should get the same message back"conditions.eventually {@@ -129,10 +133,11 @@ class SocketMessageProcessorTest extends Specification implements ManagerContainconditions.eventually {assert messageProcessor.connectionStatus == ConnectionStatus.CONNECTEDassert connectionStatus == ConnectionStatus.CONNECTED+ assert socketServer.allChannels.size() == 2}when: "the server sends a message"- socketServer.sendMessage("Is there anyone there?".getBytes(CharsetUtil.UTF_8))+ socketServer.sendMessage("Is there anyone there?")then: "we should receive the message"conditions.eventually {@@ -140,7 +145,7 @@ class SocketMessageProcessorTest extends Specification implements ManagerContain}when: "we send a message to the server"- messageProcessor.sendMessage("Yes there is!")+ messageProcessor.sendMessage("Yes there is!;")then: "we should get the same message back"conditions.eventually {@@ -166,7 +171,7 @@ class SocketMessageProcessorTest extends Specification implements ManagerContain}when: "the server sends a message"- socketServer.sendMessage("Is there anyone there?".getBytes(CharsetUtil.UTF_8))+ socketServer.sendMessage("Is there anyone there?")then: "we should receive the message"conditions.eventually {@@ -174,7 +179,7 @@ class SocketMessageProcessorTest extends Specification implements ManagerContain}when: "we send a message to the server"- messageProcessor.sendMessage("Yes there is!")+ messageProcessor.sendMessage("Yes there is!;")then: "we should get the same message back"conditions.eventually {