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 SerialMessageProcessor that uses NRJavaSerial
Rich Turnerb94470b4ac75
diff --git a/agent/build.gradle b/agent/build.gradleindex d6e189957..9be30e36e 100644--- a/agent/build.gradle+++ b/agent/build.gradle@@ -18,4 +18,6 @@ dependencies {}compile "org.fourthline.cling:cling-core:$clingVersion"++ compile "com.neuronrobotics:nrjavaserial:$nrjavaserialVersion"}\ No newline at end of filediff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractNettyMessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractNettyMessageProcessor.javanew file mode 100644index 000000000..8d7778ffa--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractNettyMessageProcessor.java@@ -0,0 +1,365 @@+/*+ * 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.rxtx.RxtxChannel;+import io.netty.channel.rxtx.RxtxDeviceAddress;+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 netty.+ * <p>+ * It uses the netty component for managing the 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 AbstractNettyMessageProcessor<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 {+ 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.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 {+ AbstractNettyMessageProcessor.this.encode(msg, out);+ }+ }++ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractNettyMessageProcessor.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 ConnectionStatus connectionStatus = ConnectionStatus.DISCONNECTED;+ protected ChannelFuture channelFuture;+ protected Channel channel;+ protected Bootstrap bootstrap;+ protected SocketAddress socketAddress;+ protected EventLoopGroup workerGroup;+ protected ProtocolExecutorService executorService;+ protected ScheduledFuture reconnectTask;+ protected int reconnectDelayMilliseconds = INITIAL_RECONNECT_DELAY_MILLIS;++ public AbstractNettyMessageProcessor(ProtocolExecutorService executorService) {+ this.executorService = executorService;+ }++ protected abstract Class<? extends Channel> getChannelClass();++ protected abstract SocketAddress getSocketAddress();++ protected abstract String getSocketAddressString();++ protected abstract EventLoopGroup getWorkerGroup();++ protected void configureChannel() {+ bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000);+ }++ @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; can only pass in thread factory for now+ workerGroup = getWorkerGroup();+ }++ bootstrap = new Bootstrap();+ bootstrap.channel(getChannelClass());+ configureChannel();+ bootstrap.group(workerGroup);++ bootstrap.handler(new ChannelInitializer() {+ @Override+ public void initChannel(Channel channel) throws Exception {+ AbstractNettyMessageProcessor.this.initChannel(channel);+ }+ });++ // Start the client and store the channel+ socketAddress = getSocketAddress();+ channelFuture = bootstrap.connect(socketAddress);+ 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 (AbstractNettyMessageProcessor.this) {+ channelFuture.removeListener(this);++ if (connectionStatus == ConnectionStatus.DISCONNECTING) {+ return;+ }++ if (future.isSuccess()) {+ LOG.fine("Successfully connected to: " + getSocketAddressString());+ 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;+ }++ socketAddress = 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.finest("Message sent");+ // Don't block here as it can cause deadlock+// ChannelFuture future = channel.writeAndFlush(message).sync();+// if (future.isCancelled()) {+// LOG.info("Message send cancelled");+// } else if (!future.isSuccess()) {+// LOG.log(Level.WARNING, "Message send failed", future.cause());+// } else {+// LOG.finest("Message sent");+// }+ } catch (Exception e) {+ LOG.log(Level.WARNING, "Message send failed", e);+ }+ }++ @Override+ public ConnectionStatus getConnectionStatus() {+ return connectionStatus;+ }++ @Override+ public void addConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {+ synchronized (connectionStatusConsumers) {+ if (!connectionStatusConsumers.contains(connectionStatusConsumer)) {+ connectionStatusConsumers.add(connectionStatusConsumer);+ }+ }+ }++ @Override+ public void removeConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {+ synchronized (connectionStatusConsumers) {+ 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(Channel channel) {+ channel.pipeline().addLast(new MessageDecoder());+ channel.pipeline().addLast(new MessageEncoder());+ }++ protected void onMessageReceived(T message) {+ if (connectionStatus != ConnectionStatus.CONNECTED) {+ return;+ }+ LOG.finest("Message received notifying consumers");+ messageConsumers.forEach(consumer -> consumer.accept(message));+ }++ protected synchronized 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 (AbstractNettyMessageProcessor.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/AbstractSerialMessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractSerialMessageProcessor.javanew file mode 100644index 000000000..79dde3f28--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractSerialMessageProcessor.java@@ -0,0 +1,75 @@+/*+ * 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.channel.Channel;+import io.netty.channel.EventLoopGroup;+import io.netty.channel.ThreadPerChannelEventLoopGroup;+import io.netty.channel.local.LocalEventLoopGroup;+import io.netty.channel.oio.OioEventLoopGroup;+import io.netty.channel.rxtx.RxtxChannel;+import io.netty.channel.rxtx.RxtxDeviceAddress;+import io.netty.channel.socket.nio.NioSocketChannel;+import org.openremote.model.syslog.SyslogCategory;+import org.openremote.model.util.TextUtil;++import java.net.SocketAddress;+import java.util.Objects;+import java.util.logging.Logger;++import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;++/**+ * This is a {@link MessageProcessor} implementation for serial ports.+ */+public abstract class AbstractSerialMessageProcessor<T> extends AbstractNettyMessageProcessor<T> {++ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractSerialMessageProcessor.class);+ protected String port;+ protected int baudRate;++ public AbstractSerialMessageProcessor(String port, Integer baudRate, ProtocolExecutorService executorService) {+ super(executorService);+ TextUtil.requireNonNullAndNonEmpty(port);+ Objects.requireNonNull(baudRate);+ this.port = port;+ this.baudRate = baudRate;+ }++ @Override+ protected Class<? extends Channel> getChannelClass() {+ return NrJavaSerialChannel.class;+ }++ @Override+ protected SocketAddress getSocketAddress() {+ return new NrJavaSerialAddress(port, 38400);+ }++ @Override+ protected String getSocketAddressString() {+ return port;+ }++ @Override+ protected EventLoopGroup getWorkerGroup() {+ return new OioEventLoopGroup(1);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractSocketCamelMessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractSocketCamelMessageProcessor.javadeleted file mode 100644index 2dd589076..000000000--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractSocketCamelMessageProcessor.java+++ /dev/null@@ -1,371 +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.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.javaindex c8d181550..75430d64e 100644--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractSocketMessageProcessor.java+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractSocketMessageProcessor.java@@ -19,334 +19,59 @@*/package org.openremote.agent.protocol;-import io.netty.bootstrap.Bootstrap;-import io.netty.buffer.ByteBuf;-import io.netty.channel.*;+import io.netty.channel.Channel;+import io.netty.channel.ChannelOption;+import io.netty.channel.EventLoopGroup;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.InetSocketAddress;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);- }- }+public abstract class AbstractSocketMessageProcessor<T> extends AbstractNettyMessageProcessor<T> {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) {+ super(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; can only 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();- }- });+ protected Class<? extends Channel> getChannelClass() {+ return NioSocketChannel.class;}@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);- }+ protected SocketAddress getSocketAddress() {+ return new InetSocketAddress(host, port);}@Override- public void sendMessage(T message) {- if (connectionStatus != ConnectionStatus.CONNECTED) {- LOG.fine("Cannot send message: Status = " + connectionStatus);- return;- }-- try {- channel.writeAndFlush(message);- LOG.finest("Message sent");- // Don't block here as it can cause deadlock-// ChannelFuture future = channel.writeAndFlush(message).sync();-// if (future.isCancelled()) {-// LOG.info("Message send cancelled");-// } else if (!future.isSuccess()) {-// LOG.log(Level.WARNING, "Message send failed", future.cause());-// } else {-// LOG.finest("Message sent");-// }- } catch (Exception e) {- LOG.log(Level.WARNING, "Message send failed", e);- }+ protected String getSocketAddressString() {+ return host + ":" + port;}@Override- public ConnectionStatus getConnectionStatus() {- return connectionStatus;+ protected EventLoopGroup getWorkerGroup() {+ return new NioEventLoopGroup(1);}@Override- public void addConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {- synchronized (connectionStatusConsumers) {- if (!connectionStatusConsumers.contains(connectionStatusConsumer)) {- connectionStatusConsumers.add(connectionStatusConsumer);- }- }+ protected void configureChannel() {+ super.configureChannel();+ bootstrap.option(ChannelOption.SO_KEEPALIVE, true);}-- @Override- public void removeConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {- synchronized (connectionStatusConsumers) {- 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 void onMessageReceived(T message) {- if (connectionStatus != ConnectionStatus.CONNECTED) {- return;- }- LOG.finest("Message received notifying consumers");- messageConsumers.forEach(consumer -> consumer.accept(message));- }-- protected synchronized 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/NrJavaSerialAddress.java b/agent/src/main/java/org/openremote/agent/protocol/NrJavaSerialAddress.javanew file mode 100644index 000000000..84c5e43ac--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/NrJavaSerialAddress.java@@ -0,0 +1,36 @@+/*+ * 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.channel.rxtx.RxtxDeviceAddress;++public class NrJavaSerialAddress extends RxtxDeviceAddress {++ protected int baudRate;++ public NrJavaSerialAddress(String port, int baudRate) {+ super(port);+ this.baudRate = baudRate;+ }++ public int getBaudRate() {+ return baudRate;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/NrJavaSerialChannel.java b/agent/src/main/java/org/openremote/agent/protocol/NrJavaSerialChannel.javanew file mode 100644index 000000000..0ecf91f4f--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/NrJavaSerialChannel.java@@ -0,0 +1,84 @@+/*+ * 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 gnu.io.NRSerialPort;+import gnu.io.SerialPort;+import io.netty.channel.ConnectTimeoutException;+import io.netty.channel.rxtx.RxtxChannel;++import java.net.SocketAddress;+import java.nio.channels.ConnectionPendingException;++import static io.netty.channel.rxtx.RxtxChannelOption.*;++public class NrJavaSerialChannel extends RxtxChannel {++ private boolean open = true;+ protected SerialPort serialPort;+ protected NrJavaSerialAddress deviceAddress;++ @Override+ public boolean isOpen() {+ return open;+ }++ @Override+ protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {+ NrJavaSerialAddress remote = (NrJavaSerialAddress) remoteAddress;+ final NRSerialPort serial = new NRSerialPort(remote.value(), remote.getBaudRate());+ serial.connect();+ serialPort = serial.getSerialPortInstance();+ if (serialPort == null) {+ // No exception is thrown on connect failure so throw one+ throw new ConnectTimeoutException("Failed to establish connection to COM port: " + remote.value());+ }+ serialPort.enableReceiveTimeout(config().getOption(READ_TIMEOUT));+ deviceAddress = remote;+ }++ @Override+ protected void doInit() throws Exception {+ serialPort.setSerialPortParams(+ config().getOption(BAUD_RATE),+ config().getOption(DATA_BITS).value(),+ config().getOption(STOP_BITS).value(),+ config().getOption(PARITY_BIT).value()+ );+ serialPort.setDTR(config().getOption(DTR));+ serialPort.setRTS(config().getOption(RTS));++ activate(serialPort.getInputStream(), serialPort.getOutputStream());+ }++ @Override+ protected void doClose() throws Exception {+ open = false;+ try {+ super.doClose();+ } finally {+ if (serialPort != null) {+ serialPort.removeEventListener();+ serialPort.close();+ serialPort = null;+ }+ }+ }+}diff --git a/gradle.properties b/gradle.propertiesindex db5698422..bd4f1aecf 100644--- a/gradle.properties+++ b/gradle.properties@@ -31,4 +31,5 @@ droolsVersion = 6.5.0.FinalquartzVersion= 2.2.3calimeroVersion = 2.4-SNAPSHOTclingVersion = 2.1.1-uuidGeneratorVersion = 3.1.3\ No newline at end of file+uuidGeneratorVersion = 3.1.3+nrjavaserialVersion = 3.13.0\ No newline at end of file