Skip to content

armgit / core

Public Imported from GitHub
0

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

Protocol related updates (UdpClientProtocol WIP)

Rich Turnerc0e28d89512b
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
index 958d93bca..58ff9d846 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
@@ -121,15 +121,7 @@ public abstract class AbstractProtocol implements Protocol {
static {
attributeMetaItemDescriptors = Arrays.asList(
- new MetaItemDescriptorImpl(
- META_PROTOCOL_FILTERS,
- ValueType.ARRAY,
- false,
- null,
- null,
- 1,
- null,
- false, null, null, null)
+ META_ATTRIBUTE_FILTERS
);
}
@@ -200,6 +192,7 @@ public abstract class AbstractProtocol implements Protocol {
protocolConfiguration.getReferenceOrThrow(),
new LinkedProtocolInfo(protocolConfiguration, statusConsumer, ConnectionStatus.CONNECTING)
);
+ statusConsumer.accept(ConnectionStatus.CONNECTING);
doLinkProtocolConfiguration(protocolConfiguration);
});
}
@@ -209,6 +202,7 @@ public abstract class AbstractProtocol implements Protocol {
withLock(getProtocolName() + "::unlinkProtocolConfiguration", () -> {
LOG.finer("Unlinking protocol configuration from protocol '" + getProtocolName() + "': " + protocolConfiguration);
doUnlinkProtocolConfiguration(protocolConfiguration);
+ updateStatus(protocolConfiguration.getReferenceOrThrow(), ConnectionStatus.DISCONNECTED);
linkedProtocolConfigurations.remove(protocolConfiguration.getReferenceOrThrow());
});
}
@@ -367,7 +361,7 @@ public abstract class AbstractProtocol implements Protocol {
} catch (Exception e) {
LOG.log(
Level.SEVERE,
- "Message filter threw and exception during processing of message: "
+ "Message filter threw an exception during processing of message: "
+ filter.getClass().getName(),
e);
value = null;
diff --git a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
index e4c031344..109f5bcf0 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
@@ -19,20 +19,26 @@
*/
package org.openremote.agent.protocol;
+import org.apache.commons.codec.binary.BinaryCodec;
+import org.apache.commons.codec.binary.Hex;
import org.openremote.agent.protocol.filter.MessageFilter;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
import org.openremote.model.AbstractValueHolder;
-import org.openremote.model.asset.*;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetType;
import org.openremote.model.asset.agent.ConnectionStatus;
import org.openremote.model.asset.agent.ProtocolConfiguration;
import org.openremote.model.asset.agent.ProtocolDescriptor;
import org.openremote.model.attribute.*;
+import org.openremote.model.util.TextUtil;
import org.openremote.model.value.ArrayValue;
import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.ValueType;
import java.io.IOException;
+import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -42,6 +48,8 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
+import static org.openremote.model.attribute.MetaItemDescriptor.Access.ACCESS_PRIVATE;
+import static org.openremote.model.attribute.MetaItemDescriptorImpl.*;
/**
* A protocol is a thread-safe singleton {@link ContainerService} that connects devices and
@@ -88,9 +96,14 @@ import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
* receive and send value change messages with values of that type.
* <p>
* Generic protocols should implement support for filtering state messages from devices (or services) before the
- * protocol updates the linked attribute, to implement this protocols should use the {@link #META_PROTOCOL_FILTERS}
+ * protocol updates the linked attribute, to implement this protocols should use the {@link #META_ATTRIBUTE_FILTERS}
* {@link MetaItem}.
* <p>
+ * <h1>Dynamic value injection</h1>
+ * This allows values to be dynamically injected into strings when a protocol linked attribute write occurs; the value
+ * contained within the {@link AttributeEvent} can be dynamically injected into the string by using the
+ * {@value Protocol#DYNAMIC_VALUE_PLACEHOLDER} as a placeholder and this will be dynamically replaced at request time.
+ * <p>
* NOTE: That {@link #linkProtocolConfiguration} will always be called
* before {@link #linkAttributes} and {@link #unlinkAttributes} will always be called before
* {@link #unlinkProtocolConfiguration}.
@@ -146,17 +159,76 @@ public interface Protocol extends ContainerService {
* where each {@link ObjectValue} represents a serialised {@link MessageFilter}. The message should pass through the
* filters in array order.
*/
- String META_PROTOCOL_FILTERS = PROTOCOL_NAMESPACE + ":filters";
+ MetaItemDescriptor META_ATTRIBUTE_FILTERS = metaItemArray(
+ PROTOCOL_NAMESPACE + ":filters",
+ ACCESS_PRIVATE,
+ false,
+ null);
+ /**
+ * Can be used by protocols that support it to indicate that string values should be converted to/from bytes from/to
+ * HEX string representation (e.g. 34FD87)
+ */
+ MetaItemDescriptor META_PROTOCOL_CONVERT_HEX = metaItemFixedBoolean(PROTOCOL_NAMESPACE + ":convertHex", ACCESS_PRIVATE, false);
- // TODO: Some of these options should be configurable depending on expected load etc.
+ /**
+ * Can be used by protocols that support it to indicate that string values should be converted to/from bytes from/to
+ * binary string representation (e.g. 1001010111)
+ */
+ MetaItemDescriptor META_PROTOCOL_CONVERT_BINARY = metaItemFixedBoolean(PROTOCOL_NAMESPACE + ":convertBinary", ACCESS_PRIVATE, false);
+
+ /**
+ * Charset to use when converting byte[] to a string (should default to UTF8 if not specified); values must be string
+ * that matches a charset as defined in {@link java.nio.charset.Charset}
+ */
+ MetaItemDescriptor META_PROTOCOL_CHARSET = metaItemString(
+ PROTOCOL_NAMESPACE + ":charset",
+ ACCESS_PRIVATE,
+ false,
+ Charset.availableCharsets().keySet().toArray(new String[0])
+ );
+
+ /**
+ * Value to be used for attribute writes, protocols that support this should also support dynamic value insertion,
+ * see interface javadoc for more details
+ */
+ MetaItemDescriptor META_ATTRIBUTE_WRITE_VALUE = new MetaItemDescriptorImpl(
+ PROTOCOL_NAMESPACE + ":writeValue",
+ ValueType.ANY,
+ ACCESS_PRIVATE,
+ false,
+ TextUtil.REGEXP_PATTERN_STRING_NON_EMPTY,
+ PatternFailure.STRING_EMPTY.name(),
+ 1,
+ null,
+ false,
+ null,
+ null,
+ null);
+ /**
+ * Polling frequency in milliseconds for {@link Attribute}s whose value should be polled; can be set on the
+ * {@link ProtocolConfiguration} or the {@link Attribute} (the latter takes precedence).
+ */
+ MetaItemDescriptor META_POLLING_MILLIS = metaItemInteger(
+ PROTOCOL_NAMESPACE + ":pollingMillis",
+ ACCESS_PRIVATE,
+ false,
+ 1000,
+ null);
+
+ // TODO: Some of these options should be configurable depending on expected load etc.
// Message topic for communicating from asset/thing to protocol layer (asset attribute changed, trigger actuator)
String ACTUATOR_TOPIC = "seda://ActuatorTopic?multipleConsumers=true&concurrentConsumers=1&waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=true&limitConcurrentConsumers=false&size=1000";
// Message queue for communicating from protocol to asset/thing layer (sensor changed, trigger asset attribute update)
String SENSOR_QUEUE = "seda://SensorQueue?waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=false&size=25000";
+ String DYNAMIC_VALUE_PLACEHOLDER = "{$value}";
+
+ String DYNAMIC_VALUE_PLACEHOLDER_REGEXP = "\"?\\{\\$value}\"?";
+
+
/**
* Get the name for this protocol
*/
@@ -230,7 +302,7 @@ public interface Protocol extends ContainerService {
return Optional.empty();
}
- Optional<ArrayValue> arrayValueOptional = attribute.getMetaItem(META_PROTOCOL_FILTERS)
+ Optional<ArrayValue> arrayValueOptional = attribute.getMetaItem(META_ATTRIBUTE_FILTERS)
.flatMap(AbstractValueHolder::getValueAsArray);
if (!arrayValueOptional.isPresent()) {
@@ -266,4 +338,30 @@ public interface Protocol extends ContainerService {
throw new IllegalArgumentException(ioException);
}
}
+
+ static String bytesToHexString(byte[] bytes) {
+ return Hex.encodeHexString(bytes);
+ }
+
+ static byte[] bytesFromHexString(String hex) {
+ try {
+ return Hex.decodeHex(hex.toCharArray());
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Failed to convert hex string to bytes", e);
+ return new byte[0];
+ }
+ }
+
+ static String bytesToBinaryString(byte[] bytes) {
+ return BinaryCodec.toAsciiString(bytes);
+ }
+
+ static byte[] bytesFromBinaryString(String binary) {
+ try {
+ return BinaryCodec.fromAscii(binary.toCharArray());
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Failed to convert hex string to bytes", e);
+ return new byte[0];
+ }
+ }
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/filter/MessageFilter.java b/agent/src/main/java/org/openremote/agent/protocol/filter/MessageFilter.java
index 4f5eab2a4..fdeed0960 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/filter/MessageFilter.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/filter/MessageFilter.java
@@ -56,7 +56,7 @@ public abstract class MessageFilter<T extends Value> {
/**
* Apply this filter to the supplied message
*/
- public abstract Value process(T message);
+ public abstract Value process(T message);
/**
* Convert this filter to an {@link ObjectValue}
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.java
index a7c03bafb..1f722b1f7 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
@@ -34,6 +34,7 @@ import org.openremote.model.attribute.MetaItemType;
import org.openremote.model.asset.agent.ConnectionStatus;
import org.openremote.model.asset.agent.ProtocolConfiguration;
import org.openremote.model.attribute.*;
+import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.Pair;
import org.openremote.model.util.TextUtil;
import org.openremote.model.value.*;
@@ -59,6 +60,7 @@ import java.util.logging.Logger;
import static org.openremote.container.concurrent.GlobalLock.withLock;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
+import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
import static org.openremote.model.util.TextUtil.*;
/**
@@ -72,27 +74,31 @@ import static org.openremote.model.util.TextUtil.*;
* items: <ul> <li>{@link #META_PROTOCOL_BASE_URI} (<b>required</b>)</li> <li>{@link #META_PROTOCOL_USERNAME}</li>
* <li>{@link #META_PROTOCOL_PASSWORD}</li> <li>{@link #META_PROTOCOL_OAUTH_GRANT}</li> <li>{@link
* #META_PROTOCOL_PING_PATH}</li> <li>{@link #META_PROTOCOL_PING_METHOD}</li> <li>{@link #META_PROTOCOL_PING_BODY}</li>
- * <li>{@link #META_PROTOCOL_PING_QUERY_PARAMETERS}</li> <li>{@link #META_PROTOCOL_PING_SECONDS}</li> <li>{@link
+ * <li>{@link #META_PROTOCOL_PING_QUERY_PARAMETERS}</li> <li>{@link #META_PROTOCOL_PING_MILLIS}</li> <li>{@link
* #META_PROTOCOL_FOLLOW_REDIRECTS}</li> <li>{@link #META_FAILURE_CODES}</li> <li>{@link #META_HEADERS}</li> </ul>
* <h1>Linked Attributes</h1>
* <p>
* {@link Attribute}s that are linked to this protocol using an {@link MetaItemType#AGENT_LINK} {@link MetaItem} support
* the following meta items: <ul> <li>{@link #META_ATTRIBUTE_PATH} (<b>if not supplied then base URI is used</b>)</li>
- * <li>{@link #META_ATTRIBUTE_METHOD}</li> <li>{@link #META_ATTRIBUTE_BODY}</li> <li>{@link
- * #META_ATTRIBUTE_POLLING_SECONDS} (<b>required if attribute value should be set by the response received from this
- * endpoint</b>)</li> <li>{@link #META_QUERY_PARAMETERS}</li> <li>{@link #META_FAILURE_CODES}</li> <li>{@link #META_HEADERS}</li> </ul>
+ * <li>{@link #META_ATTRIBUTE_METHOD}</li> <li>{@link Protocol#META_ATTRIBUTE_WRITE_VALUE} (used as the body of the
+ * request for writes)</li> <li>{@link #META_POLLING_MILLIS} (<b>required if attribute value should be set by
+ * the response received from this endpoint</b>)</li> <li>{@link #META_QUERY_PARAMETERS}</li>
+ * <li>{@link #META_FAILURE_CODES}</li>
+ * <li>{@link #META_HEADERS}</li>
+ * <li>{@link Protocol#META_ATTRIBUTE_FILTERS}</li>
+ * </ul>
* <p>
* <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 {@link Protocol#META_PROTOCOL_FILTERS} in
+ * #META_POLLING_MILLIS} {@link MetaItem}) can use the standard {@link Protocol#META_ATTRIBUTE_FILTERS} in
* order to filter the received HTTP response.
* <p>
* <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 {@link
- * #META_PROTOCOL_PING_PATH} will be called every {@link #META_PROTOCOL_PING_SECONDS} this should be a lightweight
+ * #META_PROTOCOL_PING_PATH} will be called every {@link #META_PROTOCOL_PING_MILLIS} this should be a lightweight
* endpoint (i.e. no response body or small response body) and if the HTTP server requires authentication then this ping
* endpoint should also be a secured endpoint to validate the credentials.
* <p>
@@ -110,9 +116,9 @@ import static org.openremote.model.util.TextUtil.*;
* <b>NOTE: if an exception is thrown during the request that means no response is returned then this is treated as if
* a 500 response has been received</b>
* <h1>Dynamic value injection</h1>
- * This allows the {@link #META_ATTRIBUTE_PATH} and/or {@link #META_ATTRIBUTE_BODY} to contain the linked
+ * This allows the {@link #META_ATTRIBUTE_PATH} and/or {@link Protocol#META_ATTRIBUTE_WRITE_VALUE} to contain the linked
* {@link Attribute} value when sending requests. To dynamically inject the attribute value use
- * {@value #DYNAMIC_VALUE_PLACEHOLDER} as a placeholder and this will be dynamically replaced at request time.
+ * {@value Protocol#DYNAMIC_VALUE_PLACEHOLDER} as a placeholder and this will be dynamically replaced at request time.
* <h2>Path example</h2>
* {@link #META_ATTRIBUTE_PATH} = "volume/set/{$value}" and request received to set attribute value to 100. Actual path
* used for the request = "volume/set/100"
@@ -130,10 +136,10 @@ import static org.openremote.model.util.TextUtil.*;
* Request received to set attribute value to true. Actual query parameters injected into the request =
* "param1=val1&param1=val2&param2=12232&param3=true"
* <h2>Body examples</h2>
- * {@link #META_ATTRIBUTE_BODY} = '<?xml version="1.0" encoding="UTF-8"?>{$value}</xml>' and request received to set attribute value to 100. Actual body
+ * {@link Protocol#META_ATTRIBUTE_WRITE_VALUE} = '<?xml version="1.0" encoding="UTF-8"?>{$value}</xml>' and request received to set attribute value to 100. Actual body
* used for the request = "{volume: 100}"
* <p>
- * {@link #META_ATTRIBUTE_BODY} = '{myObject: "{$value}"}' and request received to set attribute value to:
+ * {@link Protocol#META_ATTRIBUTE_WRITE_VALUE} = '{myObject: "{$value}"}' and request received to set attribute value to:
* <blockquote><pre>
* {@code
* {
@@ -369,9 +375,9 @@ public class HttpClientProtocol extends AbstractProtocol {
*/
public static final String META_PROTOCOL_PING_QUERY_PARAMETERS = PROTOCOL_NAME + ":pingQueryParameters";
/**
- * Ping frequency in seconds (integer default: {@value #DEFAULT_PING_SECONDS})
+ * Ping frequency in seconds (integer default: {@value #DEFAULT_PING_MILLIS})
*/
- public static final String META_PROTOCOL_PING_SECONDS = PROTOCOL_NAME + ":pingSeconds";
+ public static final String META_PROTOCOL_PING_MILLIS = PROTOCOL_NAME + ":pingMillis";
/**
* Flag to indicate whether redirect responses from the HTTP server should be followed (boolean)
*/
@@ -387,23 +393,15 @@ public class HttpClientProtocol extends AbstractProtocol {
* HTTP method for request (string default: {@value #DEFAULT_HTTP_METHOD})
*/
public static final String META_ATTRIBUTE_METHOD = PROTOCOL_NAME + ":method";
- /**
- * HTTP request body; supports dynamic value insertion, see class javadoc for more details ({@link Value})
- */
- public static final String META_ATTRIBUTE_BODY = PROTOCOL_NAME + ":body";
/**
* Used to indicate the type of data sent in the body, a default will be used if not supplied; default is determined
* as follows:
* <ul>
- * <li>{@link #META_ATTRIBUTE_BODY} value type = {@link ObjectValue} or {@link ArrayValue}: {@link MediaType#APPLICATION_JSON}</li>
- * <li>{@link #META_ATTRIBUTE_BODY} value type = any other value type: {@value #DEFAULT_CONTENT_TYPE}</li>
+ * <li>{@link Protocol#META_ATTRIBUTE_WRITE_VALUE} value type = {@link ObjectValue} or {@link ArrayValue}: {@link MediaType#APPLICATION_JSON}</li>
+ * <li>{@link Protocol#META_ATTRIBUTE_WRITE_VALUE} value type = any other value type: {@value #DEFAULT_CONTENT_TYPE}</li>
* </ul>
*/
public static final String META_ATTRIBUTE_CONTENT_TYPE = PROTOCOL_NAME + ":contentType";
- /**
- * Polling frequency in seconds for {@link Attribute}s whose value should come from the HTTP server
- */
- public static final String META_ATTRIBUTE_POLLING_SECONDS = PROTOCOL_NAME + ":pollingSeconds";
/*--------------- META ITEMS TO BE USED ON PROTOCOL CONFIGURATIONS OR LINKED ATTRIBUTES ---------------*/
/**
@@ -514,7 +512,7 @@ public class HttpClientProtocol extends AbstractProtocol {
null,
false, null, null, null),
new MetaItemDescriptorImpl(
- META_PROTOCOL_PING_SECONDS,
+ META_PROTOCOL_PING_MILLIS,
ValueType.NUMBER,
false,
REGEXP_PATTERN_INTEGER_POSITIVE_NON_ZERO,
@@ -607,15 +605,7 @@ public class HttpClientProtocol extends AbstractProtocol {
1,
null,
false, null, null, null),
- new MetaItemDescriptorImpl(
- META_ATTRIBUTE_BODY,
- null,
- false,
- null,
- null,
- 1,
- null,
- false, null, null, null),
+ META_ATTRIBUTE_WRITE_VALUE,
new MetaItemDescriptorImpl(
META_ATTRIBUTE_CONTENT_TYPE,
ValueType.STRING,
@@ -625,15 +615,7 @@ public class HttpClientProtocol extends AbstractProtocol {
1,
null,
false, null, null, null),
- new MetaItemDescriptorImpl(
- META_ATTRIBUTE_POLLING_SECONDS,
- ValueType.NUMBER,
- false,
- REGEXP_PATTERN_INTEGER_POSITIVE_NON_ZERO,
- MetaItemDescriptor.PatternFailure.INTEGER_POSITIVE_NON_ZERO.name(),
- 1,
- null,
- false, null, null, null),
+ META_POLLING_MILLIS,
new MetaItemDescriptorImpl(
META_QUERY_PARAMETERS,
ValueType.OBJECT,
@@ -673,14 +655,13 @@ public class HttpClientProtocol extends AbstractProtocol {
);
- private static final Logger LOG = Logger.getLogger(HttpClientProtocol.class.getName());
- public static final String PROTOCOL_DISPLAY_NAME = "Http Client";
+ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, HttpClientProtocol.class.getName());
+ public static final String PROTOCOL_DISPLAY_NAME = "HTTP Client";
public static final String PROTOCOL_VERSION = "1.0";
protected static final String HEADER_LINK = "Link";
- public static final String DYNAMIC_VALUE_PLACEHOLDER = "{$value}";
- protected static final String DYNAMIC_VALUE_PLACEHOLDER_REGEXP = "\"?\\{\\$value}\"?";
- private static TimeUnit POLLING_TIME_UNIT = TimeUnit.SECONDS; // Only here to allow override in tests
- public static final int DEFAULT_PING_SECONDS = 60;
+ public static final int DEFAULT_PING_MILLIS = 60000;
+ private static int MIN_POLLING_MILLIS = 1000;
+ private static int MIN_PING_MILLIS = 10000;
public static final String DEFAULT_HTTP_METHOD = HttpMethod.GET;
public static final String DEFAULT_CONTENT_TYPE = MediaType.TEXT_PLAIN;
protected final Map<AttributeRef, Pair<ResteasyWebTarget, List<Integer>>> clientMap = new HashMap<>();
@@ -821,7 +802,7 @@ public class HttpClientProtocol extends AbstractProtocol {
.flatMap(objectValue -> getMultivaluedMap(objectValue, false))
.orElse(null);
- Integer pingPollingSeconds = getPingSeconds(protocolConfiguration);
+ Integer pingPollingMillis = getPingMillis(protocolConfiguration);
String contentType = Values.getMetaItemValueOrThrow(
protocolConfiguration,
@@ -851,7 +832,7 @@ public class HttpClientProtocol extends AbstractProtocol {
null,
protocolRef,
pingRequest,
- pingPollingSeconds));
+ pingPollingMillis));
}
@Override
@@ -892,7 +873,7 @@ public class HttpClientProtocol extends AbstractProtocol {
.orElse(null);
Value body = attribute
- .getMetaItem(META_ATTRIBUTE_BODY)
+ .getMetaItem(META_ATTRIBUTE_WRITE_VALUE)
.flatMap(AbstractValueHolder::getValue)
.orElse(null);
@@ -925,17 +906,16 @@ public class HttpClientProtocol extends AbstractProtocol {
.flatMap(objectValue -> getMultivaluedMap(objectValue, false))
.orElse(null);
- Optional<Integer> pollingSeconds = Values.getMetaItemValueOrThrow(
+ Optional<Integer> pollingMillis = Values.getMetaItemValueOrThrow(
attribute,
- META_ATTRIBUTE_POLLING_SECONDS,
- NumberValue.class,
+ META_POLLING_MILLIS,
false,
true)
.map(polling ->
Values.getIntegerCoerced(polling)
- .map(seconds -> seconds < 1 ? null : seconds)
+ .map(millis -> millis < MIN_POLLING_MILLIS ? null : millis)
.orElseThrow(() ->
- new IllegalArgumentException("Polling seconds meta item must be an integer >= 1")
+ new IllegalArgumentException("Polling millis meta item must be an integer >= " + MIN_POLLING_MILLIS)
));
Boolean pagingEnabled = Values.getMetaItemValueOrThrow(
@@ -959,7 +939,7 @@ public class HttpClientProtocol extends AbstractProtocol {
pagingEnabled,
body,
contentType,
- pollingSeconds.orElse(null));
+ pollingMillis.orElse(null));
}
protected void addHttpClientRequest(AssetAttribute protocolConfiguration,
@@ -1094,7 +1074,7 @@ public class HttpClientProtocol extends AbstractProtocol {
try {
getOAuthGrant(protocolConfiguration);
getUsernameAndPassword(protocolConfiguration);
- getPingSeconds(protocolConfiguration);
+ getPingMillis(protocolConfiguration);
} catch (IllegalArgumentException e) {
result.addAttributeFailure(
new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_MISMATCH, PROTOCOL_NAME)
@@ -1142,20 +1122,20 @@ public class HttpClientProtocol extends AbstractProtocol {
return username.map(stringValue -> new Pair<>(stringValue, password.get()));
}
- public static Integer getPingSeconds(AssetAttribute attribute) throws IllegalArgumentException {
+ public static Integer getPingMillis(AssetAttribute attribute) throws IllegalArgumentException {
return Values.getMetaItemValueOrThrow(
attribute,
- META_PROTOCOL_PING_SECONDS,
+ META_PROTOCOL_PING_MILLIS,
NumberValue.class,
false,
true)
.map(polling ->
Values.getIntegerCoerced(polling)
- .map(seconds -> seconds < 1 ? null : seconds)
+ .map(seconds -> seconds < MIN_PING_MILLIS ? null : seconds)
.orElseThrow(() ->
- new IllegalArgumentException("Ping polling seconds meta item must be an integer >= 1")
+ new IllegalArgumentException("Ping polling seconds meta item must be an integer >= " + MIN_PING_MILLIS)
))
- .orElse(DEFAULT_PING_SECONDS);
+ .orElse(DEFAULT_PING_MILLIS);
}
@@ -1214,9 +1194,9 @@ public class HttpClientProtocol extends AbstractProtocol {
protected ScheduledFuture schedulePollingRequest(AttributeRef attributeRef,
AttributeRef protocolConfigurationRef,
HttpClientRequest clientRequest,
- int pollingSeconds) {
+ int pollingMillis) {
- LOG.fine("Scheduling polling request '" + clientRequest + "' to execute every " + pollingSeconds + " seconds for attribute: " + attributeRef);
+ LOG.fine("Scheduling polling request '" + clientRequest + "' to execute every " + pollingMillis + " ms for attribute: " + attributeRef);
return executorService.scheduleWithFixedDelay(() ->
executePollingRequest(clientRequest, response ->
@@ -1225,7 +1205,7 @@ public class HttpClientProtocol extends AbstractProtocol {
response,
attributeRef,
protocolConfigurationRef)
- ), 0, pollingSeconds, POLLING_TIME_UNIT);
+ ), 0, pollingMillis, TimeUnit.MILLISECONDS);
}
protected void executePollingRequest(HttpClientRequest clientRequest, Consumer<Response> responseConsumer) {
diff --git a/agent/src/main/java/org/openremote/agent/protocol/io/AbstractIoServer.java b/agent/src/main/java/org/openremote/agent/protocol/io/AbstractIoServer.java
deleted file mode 100644
index 05cbf3b71..000000000
--- a/agent/src/main/java/org/openremote/agent/protocol/io/AbstractIoServer.java
+++ /dev/null
@@ -1,312 +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.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/AbstractNettyMessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/io/AbstractNettyIoClient.java
similarity index 82%
rename from agent/src/main/java/org/openremote/agent/protocol/AbstractNettyMessageProcessor.java
rename to agent/src/main/java/org/openremote/agent/protocol/io/AbstractNettyIoClient.java
index 4ae65305a..a5958daf8 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractNettyMessageProcessor.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/io/AbstractNettyIoClient.java
@@ -17,13 +17,14 @@
* 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;
+package org.openremote.agent.protocol.io;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
+import org.openremote.agent.protocol.ProtocolExecutorService;
import org.openremote.model.asset.agent.ConnectionStatus;
import org.openremote.model.syslog.SyslogCategory;
@@ -38,7 +39,7 @@ import java.util.logging.Logger;
import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
/**
- * This is a {@link MessageProcessor} implementation for netty.
+ * This is a {@link IoClient} implementation for netty.
* <p>
* It uses the netty component for managing the connection.
* <p>
@@ -54,18 +55,19 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
* <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> {
+public abstract class AbstractNettyIoClient<T, U extends SocketAddress> implements IoClient<T> {
public class MessageDecoder extends ByteToMessageDecoder {
protected List<T> messages = new ArrayList<>(1);
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
- AbstractNettyMessageProcessor.this.decode(in, messages);
+ AbstractNettyIoClient.this.decode(in, messages);
if (!messages.isEmpty()) {
+ U address = (U)ctx.channel().remoteAddress();
// Don't pass them along the channel pipeline just consume them
- messages.forEach(AbstractNettyMessageProcessor.this::onMessageReceived);
+ messages.forEach(m -> AbstractNettyIoClient.this.onMessageReceived(address, m));
messages.clear();
}
}
@@ -73,7 +75,7 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
- AbstractNettyMessageProcessor.this.onDecodeException(ctx, cause);
+ AbstractNettyIoClient.this.onDecodeException(ctx, cause);
}
}
@@ -85,17 +87,17 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
@Override
protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out) {
- AbstractNettyMessageProcessor.this.encode(msg, out);
+ AbstractNettyIoClient.this.encode(msg, out);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
- AbstractNettyMessageProcessor.this.onEncodeException(ctx, cause);
+ AbstractNettyIoClient.this.onEncodeException(ctx, cause);
}
}
- private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractNettyMessageProcessor.class);
+ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractNettyIoClient.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;
@@ -105,24 +107,23 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
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) {
+ public AbstractNettyIoClient(ProtocolExecutorService executorService) {
this.executorService = executorService;
}
protected abstract Class<? extends Channel> getChannelClass();
- protected abstract SocketAddress getSocketAddress();
-
protected abstract String getSocketAddressString();
protected abstract EventLoopGroup getWorkerGroup();
+ protected abstract ChannelFuture startChannel();
+
protected void configureChannel() {
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000);
}
@@ -130,11 +131,11 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
@Override
public synchronized void connect() {
if (connectionStatus != ConnectionStatus.DISCONNECTED && connectionStatus != ConnectionStatus.WAITING) {
- LOG.finest("Must be disconnected before calling connect");
+ LOG.finest("Must be disconnected before calling connect: " + getSocketAddressString());
return;
}
- LOG.fine("Connecting");
+ LOG.fine("Connecting IO Client: " + getSocketAddressString());
onConnectionStatusChanged(ConnectionStatus.CONNECTING);
if (workerGroup == null) {
@@ -150,20 +151,19 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
bootstrap.handler(new ChannelInitializer() {
@Override
public void initChannel(Channel channel) {
- AbstractNettyMessageProcessor.this.initChannel(channel);
+ AbstractNettyIoClient.this.initChannel(channel);
}
});
- // Start the client and store the channel
- socketAddress = getSocketAddress();
- channelFuture = bootstrap.connect(socketAddress);
+ // Start and store the channel
+ channelFuture = startChannel();
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) {
- synchronized (AbstractNettyMessageProcessor.this) {
+ synchronized (AbstractNettyIoClient.this) {
channelFuture.removeListener(this);
if (connectionStatus == ConnectionStatus.DISCONNECTING) {
@@ -171,11 +171,11 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
}
if (future.isSuccess()) {
- LOG.log(Level.INFO, "Connection initialising");
+ LOG.log(Level.INFO, "Connection initialising: " + getSocketAddressString());
reconnectTask = null;
reconnectDelayMilliseconds = INITIAL_RECONNECT_DELAY_MILLIS;
} else if (future.cause() != null) {
- LOG.log(Level.INFO, "Connection error", future.cause());
+ LOG.log(Level.WARNING, "Connection error: " + getSocketAddressString(), future.cause());
// Failed to connect so schedule reconnection attempt
scheduleReconnect();
}
@@ -194,11 +194,11 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
@Override
public synchronized void disconnect() {
if (connectionStatus == ConnectionStatus.DISCONNECTING || connectionStatus == ConnectionStatus.DISCONNECTED) {
- LOG.finest("Already disconnecting or disconnected");
+ LOG.finest("Already disconnecting or disconnected: " + getSocketAddressString());
return;
}
- LOG.finest("Disconnecting");
+ LOG.finest("Disconnecting IO client: " + getSocketAddressString());
onConnectionStatusChanged(ConnectionStatus.DISCONNECTING);
try {
@@ -218,7 +218,6 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
channel = null;
}
- socketAddress = null;
} catch (InterruptedException ignored) {
} finally {
@@ -233,24 +232,16 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
@Override
public void sendMessage(T message) {
if (connectionStatus != ConnectionStatus.CONNECTED) {
- LOG.fine("Cannot send message: Status = " + connectionStatus);
+ LOG.fine("Cannot send message: Status = " + connectionStatus + ": " + getSocketAddressString());
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");
-// }
+ channel.writeAndFlush(message);
+ LOG.finest("Message sent to server: " + getSocketAddressString());
} catch (Exception e) {
- LOG.log(Level.WARNING, "Message send failed", e);
+ LOG.log(Level.WARNING, "Message send failed: " + getSocketAddressString(), e);
}
}
@@ -275,6 +266,13 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
}
}
+ @Override
+ public void removeAllConnectionStatusConsumers() {
+ synchronized (connectionStatusConsumers) {
+ connectionStatusConsumers.clear();
+ }
+ }
+
@Override
public synchronized void addMessageConsumer(Consumer<T> messageConsumer) {
if (!messageConsumers.contains(messageConsumer)) {
@@ -287,6 +285,11 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
messageConsumers.remove(messageConsumer);
}
+ @Override
+ public synchronized void removeAllMessageConsumers() {
+ messageConsumers.clear();
+ }
+
/**
* Inserts the decoders and encoders into the channel pipeline
*/
@@ -294,7 +297,7 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
- synchronized (AbstractNettyMessageProcessor.this) {
+ synchronized (AbstractNettyIoClient.this) {
LOG.fine("Connected: " + getSocketAddressString());
onConnectionStatusChanged(ConnectionStatus.CONNECTED);
}
@@ -303,7 +306,7 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- synchronized (AbstractNettyMessageProcessor.this) {
+ synchronized (AbstractNettyIoClient.this) {
if (connectionStatus != ConnectionStatus.DISCONNECTING) {
// This is a connection failure so ignore as reconnect logic will handle it
return;
@@ -315,25 +318,34 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
super.channelInactive(ctx);
}
});
+ addDecoders(channel);
+ addEncoders(channel);
+ }
+
+ protected void addDecoders(Channel channel) {
channel.pipeline().addLast(new MessageDecoder());
+ }
+
+ protected void addEncoders(Channel channel) {
channel.pipeline().addLast(new MessageEncoder());
}
- protected void onMessageReceived(T message) {
+ protected void onMessageReceived(U address, T message) {
if (connectionStatus != ConnectionStatus.CONNECTED) {
return;
}
- LOG.finest("Message received notifying consumers");
+
+ LOG.finest("Message received notifying consumers: " + getSocketAddressString());
messageConsumers.forEach(consumer -> consumer.accept(message));
}
protected void onDecodeException(ChannelHandlerContext ctx, Throwable cause) {
- LOG.log(Level.SEVERE, "Exception occurred on in-bound message: ", cause);
+ LOG.log(Level.SEVERE, "Exception occurred on in-bound message: " + getSocketAddressString(), cause);
onConnectionStatusChanged(ConnectionStatus.ERROR);
}
protected void onEncodeException(ChannelHandlerContext ctx, Throwable cause) {
- LOG.log(Level.SEVERE, "Exception occurred on out-bound message: ", cause);
+ LOG.log(Level.SEVERE, "Exception occurred on out-bound message: " + getSocketAddressString(), cause);
onConnectionStatusChanged(ConnectionStatus.ERROR);
}
@@ -359,10 +371,10 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
reconnectDelayMilliseconds = Math.min(MAX_RECONNECT_DELAY_MILLIS, reconnectDelayMilliseconds);
}
- LOG.finest("Scheduling reconnection in '" + reconnectDelayMilliseconds + "' milliseconds");
+ LOG.finest("Scheduling reconnection in '" + reconnectDelayMilliseconds + "' milliseconds: " + getSocketAddressString());
reconnectTask = executorService.schedule(() -> {
- synchronized (AbstractNettyMessageProcessor.this) {
+ synchronized (AbstractNettyIoClient.this) {
reconnectTask = null;
// Attempt to reconnect if not disconnecting
@@ -384,4 +396,9 @@ public abstract class AbstractNettyMessageProcessor<T> implements MessageProcess
protected abstract void decode(ByteBuf buf, List<T> messages);
protected abstract void encode(T message, ByteBuf buf);
+
+ @Override
+ public String toString() {
+ return getSocketAddressString();
+ }
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/io/AbstractNettyIoServer.java b/agent/src/main/java/org/openremote/agent/protocol/io/AbstractNettyIoServer.java
new file mode 100644
index 000000000..7283e9d27
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/io/AbstractNettyIoServer.java
@@ -0,0 +1,469 @@
+/*
+ * 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.AbstractBootstrap;
+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.agent.protocol.ProtocolExecutorService;
+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.Objects;
+import java.util.concurrent.ScheduledFuture;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+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 AbstractNettyIoServer<T, U extends Channel, V extends AbstractBootstrap, W extends SocketAddress> implements IoServer<T, U, W> {
+
+ 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 static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractNettyIoServer.class);
+ protected final ProtocolExecutorService executorService;
+ protected int clientLimit = 0; // 0 means no limit
+ protected V bootstrap;
+ protected ConnectionStatus connectionStatus = ConnectionStatus.DISCONNECTED;
+ protected ChannelFuture channelFuture;
+ protected EventLoopGroup workerGroup;
+ protected U channel;
+ protected final ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
+ protected final List<IoServerMessageConsumer<T, U, W>> messageConsumers = new ArrayList<>();
+ protected final List<Consumer<ConnectionStatus>> connectionStatusConsumers = new ArrayList<>();
+ protected final List<BiConsumer<U, ConnectionStatus>> clientConnectionStatusConsumers = new ArrayList<>();
+ protected ScheduledFuture reconnectTask;
+ protected int reconnectDelayMilliseconds = INITIAL_RECONNECT_DELAY_MILLIS;
+
+ public AbstractNettyIoServer(ProtocolExecutorService executorService) {
+ this.executorService = executorService;
+ }
+
+ @Override
+ public synchronized void start() {
+ if (connectionStatus != ConnectionStatus.DISCONNECTED && connectionStatus != ConnectionStatus.WAITING) {
+ LOG.finest("Must be disconnected before calling start: " + getSocketAddressString());
+ return;
+ }
+
+ LOG.fine("Starting IO Server: " + getSocketAddressString());
+ 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();
+ }
+
+ try {
+ bootstrap = createAndConfigureBootstrap();
+
+ bootstrap.handler(new ChannelInitializer() {
+ @Override
+ public void initChannel(Channel channel) {
+ AbstractNettyIoServer.this.initChannel((U)channel);
+ }
+ });
+
+ // Bind and start to accept incoming connections.
+ channelFuture = bootstrap.bind().sync();
+ channel = (U)channelFuture.channel();
+ //allChannels.add(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) {
+ synchronized (AbstractNettyIoServer.this) {
+ channelFuture.removeListener(this);
+
+ if (connectionStatus == ConnectionStatus.DISCONNECTING) {
+ return;
+ }
+
+ if (future.isSuccess()) {
+ LOG.log(Level.INFO, "Connection initialising: " + getSocketAddressString());
+ reconnectTask = null;
+ reconnectDelayMilliseconds = INITIAL_RECONNECT_DELAY_MILLIS;
+ } else if (future.cause() != null) {
+ LOG.log(Level.WARNING, "Connection error: " + getSocketAddressString(), future.cause());
+ // Failed to connect so schedule reconnection attempt
+ scheduleReconnect();
+ }
+ }
+ }
+ });
+
+ // Add closed callback
+ channel.closeFuture().addListener(future -> {
+ if (connectionStatus != ConnectionStatus.DISCONNECTING) {
+ scheduleReconnect();
+ }
+ });
+
+ } 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 (connectionStatus == ConnectionStatus.DISCONNECTING || connectionStatus == ConnectionStatus.DISCONNECTED) {
+ LOG.finest("Already stopping or stopped: " + getSocketAddressString());
+ return;
+ }
+
+ LOG.finest("Stopping IO Server: " + getSocketAddressString());
+ onConnectionStatusChanged(ConnectionStatus.DISCONNECTING);
+
+ try {
+ if (reconnectTask != null) {
+ reconnectTask.cancel(false);
+ }
+
+ // Close all client connections
+ allChannels.close().sync();
+ allChannels.clear();
+
+ 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 addMessageConsumer(IoServerMessageConsumer<T, U, W> messageConsumer) {
+ LOG.finest("Adding message consumer");
+ synchronized (messageConsumers) {
+ messageConsumers.add(messageConsumer);
+ }
+ }
+
+ @Override
+ public void removeMessageConsumer(IoServerMessageConsumer<T, U, W> messageConsumer) {
+ synchronized (messageConsumers) {
+ messageConsumers.remove(messageConsumer);
+ }
+ }
+
+ @Override
+ public synchronized void removeAllMessageConsumers() {
+ synchronized (messageConsumers) {
+ messageConsumers.clear();
+ }
+ }
+
+ @Override
+ public void addConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {
+ synchronized (clientConnectionStatusConsumers) {
+ connectionStatusConsumers.add(connectionStatusConsumer);
+ }
+ }
+
+ @Override
+ public void removeConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {
+ synchronized (clientConnectionStatusConsumers) {
+ connectionStatusConsumers.remove(connectionStatusConsumer);
+ }
+ }
+
+ @Override
+ public void addConnectionStatusConsumer(BiConsumer<U, ConnectionStatus> connectionStatusConsumer) {
+ synchronized (clientConnectionStatusConsumers) {
+ clientConnectionStatusConsumers.add(connectionStatusConsumer);
+ }
+ }
+
+ @Override
+ public void removeConnectionStatusConsumer(BiConsumer<U, ConnectionStatus> connectionStatusConsumer) {
+ synchronized (clientConnectionStatusConsumers) {
+ clientConnectionStatusConsumers.remove(connectionStatusConsumer);
+ }
+ }
+
+ @Override
+ public void removeAllConnectionStatusConsumers() {
+ synchronized (connectionStatusConsumers) {
+ connectionStatusConsumers.clear();
+ }
+ }
+
+ @Override
+ public ConnectionStatus getConnectionStatus() {
+ return connectionStatus;
+ }
+
+ @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();
+ }
+
+
+ protected void initChannel(U channel) {
+ channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
+ @Override
+ public void channelActive(ChannelHandlerContext ctx) throws Exception {
+ synchronized (AbstractNettyIoServer.this) {
+ LOG.fine("Connected: " + getSocketAddressString());
+ onConnectionStatusChanged(ConnectionStatus.CONNECTED);
+ }
+ super.channelActive(ctx);
+ }
+
+ @Override
+ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+ synchronized (AbstractNettyIoServer.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);
+ }
+ });
+ }
+
+ /**
+ * 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) {
+ handleMessageReceived(channel, msg);
+ }
+ });
+ }
+
+ protected void handleMessageReceived(U channel, T message) {
+ onMessageReceived(message, channel, (W)channel.remoteAddress());
+ }
+
+ 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 synchronized void onConnectionStatusChanged(ConnectionStatus connectionStatus) {
+ this.connectionStatus = connectionStatus;
+
+ synchronized (connectionStatusConsumers) {
+ connectionStatusConsumers.forEach(
+ consumer -> consumer.accept(connectionStatus)
+ );
+ }
+ }
+
+ protected void sendClientConnectionStatus(U channel, ConnectionStatus connectionStatus) {
+ synchronized (clientConnectionStatusConsumers) {
+ clientConnectionStatusConsumers.forEach(statusConsumer
+ -> statusConsumer.accept(channel, connectionStatus));
+ }
+ }
+
+ protected void onMessageReceived(T message, U channel, W sender) {
+ synchronized (messageConsumers) {
+ messageConsumers.forEach(messageConsumer -> messageConsumer.accept(message, channel, sender));
+ }
+ }
+
+ 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();
+ }
+
+ @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);
+ }
+ }
+
+ /**
+ * Send a message to a recipient by address; for connection based protocols then the recipient must already
+ * be connected; this is mostly useful for connectionless protocols (i.e. UDP where only a single channel exists)
+ */
+ public void sendMessage(T message, W recipient) {
+ U client = (U) allChannels.stream().filter(c -> Objects.equals(c.remoteAddress(), recipient)).findFirst().orElse(null);
+
+ if (client == null) {
+ LOG.warning("Couldn't find existing connection for recipient '" + recipient.toString() + "': " + getSocketAddressString());
+ return;
+ }
+
+ sendMessage(message, client);
+ }
+
+
+ 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: " + getSocketAddressString());
+
+ reconnectTask = executorService.schedule(() -> {
+ synchronized (AbstractNettyIoServer.this) {
+ reconnectTask = null;
+
+ // Attempt to reconnect if not disconnecting
+ if (connectionStatus != ConnectionStatus.DISCONNECTING && connectionStatus != ConnectionStatus.DISCONNECTED) {
+ start();
+ }
+ }
+ }, reconnectDelayMilliseconds);
+ }
+
+
+ /**
+ * Get a string identifier that uniquely identifies the current instance of this server. e.g. tcp://IP:PORT
+ */
+ protected abstract String getSocketAddressString();
+
+ /**
+ * Create and configure the bootstrap to use for this instance
+ */
+ protected abstract V createAndConfigureBootstrap();
+
+ /**
+ * 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);
+
+ protected void addDecoder(U channel, ChannelInboundHandler decoder) {
+ channel.pipeline().addLast(decoder);
+ }
+
+ protected void addEncoder(U channel, ChannelOutboundHandler encoder) {
+ channel.pipeline().addLast(encoder);
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/MessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/io/IoClient.java
similarity index 83%
rename from agent/src/main/java/org/openremote/agent/protocol/MessageProcessor.java
rename to agent/src/main/java/org/openremote/agent/protocol/io/IoClient.java
index 2ef04d605..cf7a319ff 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/MessageProcessor.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/io/IoClient.java
@@ -17,21 +17,21 @@
* 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;
+package org.openremote.agent.protocol.io;
import org.openremote.model.asset.agent.ConnectionStatus;
import java.util.function.Consumer;
/**
- * This is an abstraction for encoding/decoding messages for communication 'over the wire' in a generic way.
+ * Represents an IO client that communicates with a server.
* <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;
+ * 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> {
+public interface IoClient<T> {
/**
* Send a message over the wire
@@ -48,6 +48,11 @@ public interface MessageProcessor<T> {
*/
void removeMessageConsumer(Consumer<T> messageConsumer);
+ /**
+ * Remove every consumer of received messages
+ */
+ void removeAllMessageConsumers();
+
/**
* Add a consumer of connection status
*/
@@ -58,6 +63,11 @@ public interface MessageProcessor<T> {
*/
void removeConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer);
+ /**
+ * Remove every consumer of connection status
+ */
+ void removeAllConnectionStatusConsumers();
+
/**
* Get current connection status
*/
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.java
index 5f30ae718..9eb3146d7 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/io/IoServer.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/io/IoServer.java
@@ -21,6 +21,7 @@ package org.openremote.agent.protocol.io;
import org.openremote.model.asset.agent.ConnectionStatus;
+import java.net.SocketAddress;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
@@ -28,12 +29,19 @@ 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 &lt;T&gt;
+ * for encoding/decoding messages of type &lt;T&gt; received from source &lt;U&gt; with an address &lt;V&gt;.
*
* @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
+ * @param <V> Defines the client address that can be used to uniquely identify the client
*/
-public interface IoServer<T, U> {
+public interface IoServer<T, U, V extends SocketAddress> {
+
+ @FunctionalInterface
+ interface IoServerMessageConsumer<T, U, V> {
+
+ void accept(T t, U u, V v);
+ }
/**
* Send a message to a client
@@ -48,12 +56,27 @@ public interface IoServer<T, U> {
/**
* Add a consumer of received messages
*/
- void addMessageConsumer(BiConsumer<U, T> messageConsumer);
+ void addMessageConsumer(IoServerMessageConsumer<T, U, V> messageConsumer);
/**
* Remove a consumer of received messages
*/
- void removeMessageConsumer(BiConsumer<U, T> messageConsumer);
+ void removeMessageConsumer(IoServerMessageConsumer<T, U, V> messageConsumer);
+
+ /**
+ * Remove every consumer of received messages
+ */
+ void removeAllMessageConsumers();
+
+ /**
+ * Add a consumer of server connection status changes
+ */
+ void addConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer);
+
+ /**
+ * Remove a consumer of server connection status changes
+ */
+ void removeConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer);
/**
* Add a consumer of client connection status changes
@@ -65,6 +88,16 @@ public interface IoServer<T, U> {
*/
void removeConnectionStatusConsumer(BiConsumer<U, ConnectionStatus> connectionStatusConsumer);
+ /**
+ * Remove every consumer of connection status
+ */
+ void removeAllConnectionStatusConsumers();
+
+ /**
+ * Get current connection status of the server
+ */
+ ConnectionStatus getConnectionStatus();
+
/**
* Get current connection status of a client (either {@link ConnectionStatus#CONNECTED} or
* {@link ConnectionStatus#DISCONNECTED})
diff --git a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java
index 6171b183c..3cff9b6f7 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java
@@ -20,8 +20,8 @@
package org.openremote.agent.protocol.macro;
import org.openremote.agent.protocol.AbstractProtocol;
-import org.openremote.model.asset.agent.ConnectionStatus;
import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.agent.ConnectionStatus;
import org.openremote.model.attribute.*;
import org.openremote.model.util.Pair;
import org.openremote.model.value.Value;
@@ -126,7 +126,7 @@ public class MacroProtocol extends AbstractProtocol {
}
// Get next execution delay
- Integer delayMillis = actions.get(iteration).getDelayMilliseconds();
+ int delayMillis = actions.get(iteration).getDelayMilliseconds();
// Schedule the next iteration
scheduledFuture = executorService.schedule(this::run, delayMillis > 0 ? delayMillis : 0);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractSerialMessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/serial/AbstractSerialClient.java
similarity index 64%
rename from agent/src/main/java/org/openremote/agent/protocol/AbstractSerialMessageProcessor.java
rename to agent/src/main/java/org/openremote/agent/protocol/serial/AbstractSerialClient.java
index a9d8a53b8..5f0b25aec 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractSerialMessageProcessor.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/serial/AbstractSerialClient.java
@@ -17,29 +17,30 @@
* 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;
+package org.openremote.agent.protocol.serial;
import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
import io.netty.channel.oio.OioEventLoopGroup;
+import org.openremote.agent.protocol.ProtocolExecutorService;
+import org.openremote.agent.protocol.io.AbstractNettyIoClient;
+import org.openremote.agent.protocol.io.IoClient;
import org.openremote.model.util.TextUtil;
-import java.net.SocketAddress;
-import java.util.Objects;
-
/**
- * This is a {@link MessageProcessor} implementation for serial ports.
+ * This is a {@link IoClient} implementation for serial ports.
*/
-public abstract class AbstractSerialMessageProcessor<T> extends AbstractNettyMessageProcessor<T> {
+public abstract class AbstractSerialClient<T> extends AbstractNettyIoClient<T, NrJavaSerialAddress> {
protected String port;
protected int baudRate;
+ public static int DEFAULT_BAUD_RATE = 38400;
- public AbstractSerialMessageProcessor(String port, Integer baudRate, ProtocolExecutorService executorService) {
+ public AbstractSerialClient(String port, Integer baudRate, ProtocolExecutorService executorService) {
super(executorService);
TextUtil.requireNonNullAndNonEmpty(port);
- Objects.requireNonNull(baudRate);
this.port = port;
- this.baudRate = baudRate;
+ this.baudRate = baudRate == null ? DEFAULT_BAUD_RATE : baudRate;
}
@Override
@@ -48,13 +49,13 @@ public abstract class AbstractSerialMessageProcessor<T> extends AbstractNettyMes
}
@Override
- protected SocketAddress getSocketAddress() {
- return new NrJavaSerialAddress(port, 38400);
+ protected ChannelFuture startChannel() {
+ return bootstrap.connect(new NrJavaSerialAddress(port, baudRate));
}
@Override
protected String getSocketAddressString() {
- return port;
+ return "serial://" + port;
}
@SuppressWarnings("deprecation")
diff --git a/agent/src/main/java/org/openremote/agent/protocol/NrJavaSerialAddress.java b/agent/src/main/java/org/openremote/agent/protocol/serial/NrJavaSerialAddress.java
similarity index 96%
rename from agent/src/main/java/org/openremote/agent/protocol/NrJavaSerialAddress.java
rename to agent/src/main/java/org/openremote/agent/protocol/serial/NrJavaSerialAddress.java
index 8622e982e..00700b670 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/NrJavaSerialAddress.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/serial/NrJavaSerialAddress.java
@@ -17,7 +17,7 @@
* 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;
+package org.openremote.agent.protocol.serial;
@SuppressWarnings("deprecation")
public class NrJavaSerialAddress extends io.netty.channel.rxtx.RxtxDeviceAddress {
diff --git a/agent/src/main/java/org/openremote/agent/protocol/NrJavaSerialChannel.java b/agent/src/main/java/org/openremote/agent/protocol/serial/NrJavaSerialChannel.java
similarity index 98%
rename from agent/src/main/java/org/openremote/agent/protocol/NrJavaSerialChannel.java
rename to agent/src/main/java/org/openremote/agent/protocol/serial/NrJavaSerialChannel.java
index db599c276..ac3bab634 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/NrJavaSerialChannel.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/serial/NrJavaSerialChannel.java
@@ -17,7 +17,7 @@
* 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;
+package org.openremote.agent.protocol.serial;
import gnu.io.NRSerialPort;
import gnu.io.SerialPort;
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractSocketMessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpClient.java
similarity index 74%
rename from agent/src/main/java/org/openremote/agent/protocol/AbstractSocketMessageProcessor.java
rename to agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpClient.java
index 75430d64e..ce0a27321 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractSocketMessageProcessor.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpClient.java
@@ -17,32 +17,35 @@
* 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;
+package org.openremote.agent.protocol.tcp;
import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
+import org.openremote.agent.protocol.ProtocolExecutorService;
+import org.openremote.agent.protocol.io.AbstractNettyIoClient;
+import org.openremote.agent.protocol.io.IoClient;
import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.TextUtil;
import java.net.InetSocketAddress;
-import java.net.SocketAddress;
import java.util.logging.Logger;
import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
/**
- * This is a {@link MessageProcessor} implementation for sockets.
+ * This is a {@link IoClient} implementation for TCP.
*/
-public abstract class AbstractSocketMessageProcessor<T> extends AbstractNettyMessageProcessor<T> {
+public abstract class AbstractTcpClient<T> extends AbstractNettyIoClient<T, InetSocketAddress> {
- private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractSocketMessageProcessor.class);
+ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractTcpClient.class);
protected String host;
protected int port;
- public AbstractSocketMessageProcessor(String host, int port, ProtocolExecutorService executorService) {
+ public AbstractTcpClient(String host, int port, ProtocolExecutorService executorService) {
super(executorService);
TextUtil.requireNonNullAndNonEmpty(host);
this.host = host;
@@ -54,14 +57,9 @@ public abstract class AbstractSocketMessageProcessor<T> extends AbstractNettyMes
return NioSocketChannel.class;
}
- @Override
- protected SocketAddress getSocketAddress() {
- return new InetSocketAddress(host, port);
- }
-
@Override
protected String getSocketAddressString() {
- return host + ":" + port;
+ return "tcp://" + host + ":" + port;
}
@Override
@@ -69,6 +67,11 @@ public abstract class AbstractSocketMessageProcessor<T> extends AbstractNettyMes
return new NioEventLoopGroup(1);
}
+ @Override
+ protected ChannelFuture startChannel() {
+ return bootstrap.connect(new InetSocketAddress(host, port));
+ }
+
@Override
protected void configureChannel() {
super.configureChannel();
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tcp/TcpServer.java b/agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpServer.java
similarity index 58%
rename from agent/src/main/java/org/openremote/agent/protocol/tcp/TcpServer.java
rename to agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpServer.java
index 3b94183fb..0b94070c4 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/tcp/TcpServer.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpServer.java
@@ -19,12 +19,13 @@
*/
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.bootstrap.ServerBootstrap;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
-import org.openremote.agent.protocol.io.AbstractIoServer;
+import org.openremote.agent.protocol.ProtocolExecutorService;
+import org.openremote.agent.protocol.io.AbstractNettyIoServer;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
@@ -34,32 +35,37 @@ import java.net.SocketAddress;
* to configure the pipeline with the necessary encoders and decoders to ensure messages of type &lt;T&gt; are
* generated/consumed at/from the end/start of the pipeline.
*/
-public abstract class TcpServer<T> extends AbstractIoServer<T, SocketChannel> {
+public abstract class AbstractTcpServer<T> extends AbstractNettyIoServer<T, SocketChannel, ServerBootstrap, InetSocketAddress> {
protected SocketAddress localAddress;
- public TcpServer(InetSocketAddress localAddress) {
+ public AbstractTcpServer(ProtocolExecutorService executorService, InetSocketAddress localAddress) {
+ super(executorService);
this.localAddress = localAddress;
}
@Override
- protected String getInstanceIdentifier() {
+ protected String getSocketAddressString() {
return localAddress == null ? null : "tcp://" + localAddress;
}
@Override
- protected Class<? extends ServerChannel> getServerChannelClass() {
- return NioServerSocketChannel.class;
- }
+ protected ServerBootstrap createAndConfigureBootstrap() {
+ ServerBootstrap bootstrap = new ServerBootstrap();
+ bootstrap.channel(NioServerSocketChannel.class);
+ bootstrap.group(workerGroup);
+ bootstrap.localAddress(localAddress);
+ bootstrap.option(ChannelOption.SO_BACKLOG, clientLimit);
- @Override
- protected EventLoopGroup getWorkerGroup() {
- return new NioEventLoopGroup();
- }
+ bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
+ bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
+ @Override
+ protected void initChannel(SocketChannel channel) {
+ AbstractTcpServer.this.initClientChannel(channel);
+ }
+ });
- @Override
- protected SocketAddress getLocalAddress() {
- return localAddress;
+ return bootstrap;
}
@Override
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.java
index ffc33e31d..20fe251aa 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpServerProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/tcp/AbstractTcpServerProtocol.java
@@ -33,6 +33,7 @@ import org.openremote.model.value.Values;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
+import java.util.function.Consumer;
import java.util.logging.Logger;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
@@ -45,18 +46,18 @@ import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
* <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_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 abstract class AbstractTcpServerProtocol<T extends AbstractTcpServer<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";
+ public static final String META_PROTOCOL_BIND_PORT = PROTOCOL_NAME + ":bindPort";
/**
* Sets the network interface that this server will bind to; if not defined then the server
* will bind to all network interfaces.
@@ -70,15 +71,10 @@ public abstract class AbstractTcpServerProtocol<T extends TcpServer<U>, U> exten
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)
+ int port = protocolConfiguration.getMetaItem(META_PROTOCOL_BIND_PORT)
.flatMap(AbstractValueHolder::getValueAsInteger)
.orElseThrow(() ->
- new IllegalArgumentException("Missing or invalid require meta item: " + META_PROTOCOL_PORT));
+ new IllegalArgumentException("Missing or invalid require meta item: " + META_PROTOCOL_BIND_PORT));
Optional<StringValue> bindAddress = Values.getMetaItemValueOrThrow(
protocolConfiguration,
@@ -90,15 +86,15 @@ public abstract class AbstractTcpServerProtocol<T extends TcpServer<U>, U> exten
LOG.info("Creating TCP server instance");
T tcpServer = createTcpServer(port, bindAddress.map(StringValue::getString).orElse(null), protocolConfiguration);
+ Consumer<ConnectionStatus> connectionStatusConsumer = connectionStatus ->
+ onServerConnectionStatusChanged(protocolRef, connectionStatus);
+ tcpServer.addConnectionStatusConsumer(connectionStatusConsumer);
tcpServerMap.put(protocolRef, tcpServer);
startTcpServer(protocolRef, tcpServer);
+ }
- if (!tcpServer.isStarted()) {
- LOG.warning("Failed to start TCP server instance");
- updateStatus(protocolRef, ConnectionStatus.ERROR);
- } else {
- updateStatus(protocolRef, ConnectionStatus.CONNECTED);
- }
+ protected void onServerConnectionStatusChanged(AttributeRef protocolRef, ConnectionStatus connectionStatus) {
+ updateStatus(protocolRef, connectionStatus);
}
@Override
@@ -106,12 +102,12 @@ public abstract class AbstractTcpServerProtocol<T extends TcpServer<U>, U> exten
final AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();
T tcpServer = tcpServerMap.remove(protocolRef);
-
if (tcpServer == null) {
return;
}
LOG.info("Removing TCP server instance");
+ tcpServer.removeAllConnectionStatusConsumers();
stopTcpServer(protocolRef, tcpServer);
updateStatus(protocolRef, ConnectionStatus.DISCONNECTED);
}
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.java
index 4045284ec..d81e2fc78 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/tcp/TcpStringServer.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/tcp/TcpStringServer.java
@@ -24,22 +24,23 @@ 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 org.openremote.agent.protocol.ProtocolExecutorService;
import java.net.InetSocketAddress;
/**
- * This is an {@link TcpServer} implementation that handles {@link String} messages.
+ * This is an {@link AbstractTcpServer} implementation that handles {@link String} messages.
* <p>
* Uses {@link DelimiterBasedFrameDecoder} and {@link StringDecoder}.
*/
-public class TcpStringServer extends TcpServer<String> {
+public class TcpStringServer extends AbstractTcpServer<String> {
protected String delimiter;
protected int maxFrameLength;
protected boolean stripDelimiter;
- public TcpStringServer(InetSocketAddress localAddress, String delimiter, int maxFrameLength, boolean stripDelimiter) {
- super(localAddress);
+ public TcpStringServer(ProtocolExecutorService executorService, InetSocketAddress localAddress, String delimiter, int maxFrameLength, boolean stripDelimiter) {
+ super(executorService, localAddress);
this.delimiter = delimiter;
this.maxFrameLength = maxFrameLength;
this.stripDelimiter = stripDelimiter;
@@ -48,14 +49,12 @@ public class TcpStringServer extends TcpServer<String> {
@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());
+ addDecoder(channel, new DelimiterBasedFrameDecoder(maxFrameLength, stripDelimiter, Unpooled.wrappedBuffer(delimiter.getBytes())));
+ addDecoder(channel, new StringDecoder());
}
@Override
protected void addEncoders(SocketChannel channel) {
- channel.pipeline().addLast(new StringEncoder());
+ addEncoder(channel, new StringEncoder());
}
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/udp/AbstractUdpClient.java b/agent/src/main/java/org/openremote/agent/protocol/udp/AbstractUdpClient.java
new file mode 100644
index 000000000..a7fbdc492
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/udp/AbstractUdpClient.java
@@ -0,0 +1,131 @@
+/*
+ * 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.udp;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.DatagramPacket;
+import io.netty.channel.socket.nio.NioDatagramChannel;
+import io.netty.handler.codec.MessageToMessageDecoder;
+import io.netty.handler.codec.MessageToMessageEncoder;
+import org.openremote.agent.protocol.ProtocolExecutorService;
+import org.openremote.agent.protocol.io.AbstractNettyIoClient;
+import org.openremote.agent.protocol.io.IoClient;
+import org.openremote.model.syslog.SyslogCategory;
+import org.openremote.model.util.TextUtil;
+
+import java.net.InetSocketAddress;
+import java.util.List;
+import java.util.logging.Logger;
+
+import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
+
+/**
+ * This is a {@link IoClient} implementation for UDP.
+ */
+public abstract class AbstractUdpClient<T> extends AbstractNettyIoClient<T, InetSocketAddress> {
+
+ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractUdpClient.class);
+ protected String host;
+ protected int port;
+ protected int bindPort;
+
+ public AbstractUdpClient(String host, int port, ProtocolExecutorService executorService) {
+ this(host, port, null, executorService);
+ }
+
+ public AbstractUdpClient(String host, int port, Integer bindPort, ProtocolExecutorService executorService) {
+ super(executorService);
+ TextUtil.requireNonNullAndNonEmpty(host);
+
+ if (port < 1 || port > 65536) {
+ throw new IllegalArgumentException("Port must be between 1 and 65536");
+ }
+
+ if (bindPort == null) {
+ bindPort = 0;
+ } else if (bindPort < 1 || bindPort > 65536) {
+ throw new IllegalArgumentException("Bind port must be between 1 and 65536");
+ }
+
+ this.host = host;
+ this.port = port;
+ this.bindPort = bindPort;
+ }
+
+ @Override
+ protected void addEncoders(Channel channel) {
+ channel.pipeline().addLast(new MessageToMessageEncoder<ByteBuf>() {
+ @Override
+ protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
+ out.add(new DatagramPacket(msg.retain(), new InetSocketAddress(host, port)));
+ }
+ });
+
+ super.addEncoders(channel);
+ }
+
+ @Override
+ protected void addDecoders(Channel channel) {
+ super.addDecoders(channel);
+
+ channel.pipeline().addFirst(new MessageToMessageDecoder<DatagramPacket>() {
+ @Override
+ protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
+ out.add(msg.content().retain());
+ }
+ });
+ }
+
+ @Override
+ protected ChannelFuture startChannel() {
+ return bootstrap.bind(bindPort);
+ }
+
+ @Override
+ protected Class<? extends Channel> getChannelClass() {
+ return NioDatagramChannel.class;
+ }
+
+ @Override
+ protected String getSocketAddressString() {
+ return "udp://" + host + ":" + port + " (bindPort: " + bindPort + ")";
+ }
+
+ @Override
+ protected EventLoopGroup getWorkerGroup() {
+ return new NioEventLoopGroup(1);
+ }
+
+ @Override
+ protected void configureChannel() {
+ super.configureChannel();
+ //bootstrap.option(ChannelOption.SO_BROADCAST, true);
+ }
+
+ @Override
+ protected synchronized void scheduleReconnect() {
+ // No connection to reconnect
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/udp/AbstractUdpServer.java b/agent/src/main/java/org/openremote/agent/protocol/udp/AbstractUdpServer.java
new file mode 100644
index 000000000..e25831fac
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/udp/AbstractUdpServer.java
@@ -0,0 +1,156 @@
+/*
+ * Copyright 2019, 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.udp;
+
+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.DatagramChannel;
+import io.netty.channel.socket.DatagramPacket;
+import io.netty.channel.socket.nio.NioDatagramChannel;
+import io.netty.handler.codec.DatagramPacketEncoder;
+import io.netty.handler.codec.MessageToMessageDecoder;
+import io.netty.handler.codec.MessageToMessageEncoder;
+import org.openremote.agent.protocol.ProtocolExecutorService;
+import org.openremote.agent.protocol.io.AbstractNettyIoServer;
+
+import java.net.InetSocketAddress;
+import java.util.List;
+import java.util.logging.Level;
+
+/**
+ * UDP in Netty is crap; everything goes through the single server channel as it is connectionless but there is no way
+ * of tracking packet origin across decoders. From reading each channel is single threaded so making an assumption that
+ * we can store packet origin for processing in {@link #onMessageReceived}.
+ * For outbound messages we wrap each decoder in a {@link DatagramPacketEncoder} which unfortunately only supports
+ * {@link MessageToMessageEncoder}s.
+ */
+public abstract class AbstractUdpServer<T> extends AbstractNettyIoServer<T, DatagramChannel, Bootstrap, InetSocketAddress> {
+
+ protected InetSocketAddress localAddress;
+ protected InetSocketAddress lastMessageSender;
+
+ public AbstractUdpServer(ProtocolExecutorService executorService, InetSocketAddress localAddress) {
+ super(executorService);
+ this.localAddress = localAddress;
+ }
+
+ @Override
+ protected String getSocketAddressString() {
+ return localAddress == null ? null : "udp://" + localAddress;
+ }
+
+ @Override
+ protected String getClientDescriptor(DatagramChannel client) {
+ return null;
+ }
+
+ @Override
+ protected Bootstrap createAndConfigureBootstrap() {
+ Bootstrap b = new Bootstrap();
+ b.group(new NioEventLoopGroup())
+ .channel(NioDatagramChannel.class)
+ .localAddress(localAddress)
+ .option(ChannelOption.SO_BROADCAST, true);
+ return b;
+ }
+
+ @Override
+ protected void initChannel(DatagramChannel channel) {
+ super.initChannel(channel);
+
+ // Convert datagram packet to default address envelope
+ channel.pipeline().addLast(new MessageToMessageDecoder<DatagramPacket>() {
+ @Override
+ protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
+ lastMessageSender = msg.sender();
+ out.add(msg.content().retain());
+ }
+ });
+
+ addDecoders(channel);
+
+ // Add handler to route the final messages
+ channel.pipeline().addLast(new SimpleChannelInboundHandler<T>() {
+ @Override
+ protected void channelRead0(ChannelHandlerContext ctx, T msg) {
+ handleMessageReceived(channel, msg);
+ }
+ });
+
+ // just ensure there is a datagram packet at the end of the outward pipeline
+ channel.pipeline().addLast(new MessageToMessageEncoder<AddressedEnvelope<ByteBuf, InetSocketAddress>>() {
+
+ @Override
+ protected void encode(ChannelHandlerContext ctx, AddressedEnvelope<ByteBuf, InetSocketAddress> msg, List<Object> out) throws Exception {
+ if (msg instanceof DatagramPacket) {
+ out.add(msg.retain());
+ } else {
+ out.add(new DatagramPacket(msg.content(), msg.recipient(), msg.sender()));
+ }
+ }
+ });
+
+ addEncoders(channel);
+ }
+
+ @Override
+ public void sendMessage(T message) {
+ sendMessage(message, new InetSocketAddress("255.255.255.255", localAddress.getPort()));
+ }
+
+ @Override
+ public void sendMessage(T message, DatagramChannel client) {
+ throw new IllegalStateException("Sending to a channel not supported for UDP");
+ }
+
+ @Override
+ public void sendMessage(T message, InetSocketAddress destination) {
+ try {
+ channelFuture.channel().writeAndFlush(new DefaultAddressedEnvelope<>(message, destination, localAddress));
+ LOG.finest("Message sent to client: " + destination.toString());
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Message send failed", e);
+ }
+ }
+
+ @Override
+ protected void addEncoder(DatagramChannel channel, ChannelOutboundHandler encoder) {
+ if (encoder instanceof DatagramPacketEncoder) {
+ super.addEncoder(channel, encoder);
+ return;
+ }
+
+ if (!(encoder instanceof MessageToMessageEncoder)) {
+ throw new IllegalArgumentException("Only MessageToMessage encoders can be used with UDP");
+ }
+
+ MessageToMessageEncoder mEncoder = (MessageToMessageEncoder)encoder;
+ super.addEncoder(channel, new DatagramPacketEncoder(mEncoder));
+ }
+
+ @Override
+ protected void handleMessageReceived(DatagramChannel channel, T message) {
+ InetSocketAddress sender = lastMessageSender;
+ lastMessageSender = null;
+ onMessageReceived(message, channel, sender);
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/udp/UdpClientProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/udp/UdpClientProtocol.java
new file mode 100644
index 000000000..d15dec508
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/udp/UdpClientProtocol.java
@@ -0,0 +1,442 @@
+/*
+ * 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.udp;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.util.CharsetUtil;
+import org.openremote.agent.protocol.AbstractProtocol;
+import org.openremote.agent.protocol.Protocol;
+import org.openremote.agent.protocol.io.IoClient;
+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.*;
+import org.openremote.model.syslog.SyslogCategory;
+import org.openremote.model.util.TextUtil;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.Values;
+
+import java.nio.charset.Charset;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.logging.Logger;
+
+import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
+import static org.openremote.model.attribute.MetaItemDescriptor.Access.ACCESS_PRIVATE;
+import static org.openremote.model.attribute.MetaItemDescriptorImpl.*;
+import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
+
+/**
+ * This is a UDP client protocol for communicating with UDP servers; it uses the {@link AbstractUdpClient} to handle the
+ * communication, it is important that all data (sent and received) fits in a single datagram packet.
+ * <p>
+ * This is a generic protocol that supports
+ * {@link org.openremote.agent.protocol.Protocol#META_PROTOCOL_CONVERT_HEX} or
+ * {@link org.openremote.agent.protocol.Protocol#META_PROTOCOL_CONVERT_BINARY} to facilitate working with UDP servers
+ * that handle binary data.
+ * <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_HOST} <b>(required)</b></li>
+ * <li>{@link #META_PROTOCOL_PORT} <b>(required)</b></li>
+ * <li>{@link #META_PROTOCOL_BIND_PORT}</li>
+ * <li>{@link #META_PROTOCOL_CHARSET} (defaults to UTF8 if not specified)</li>
+ * </ul>
+ * <p>
+ * <h1>Linked Attributes</h1>
+ * {@link Attribute}s that are linked to this protocol using an {@link MetaItemType#AGENT_LINK} {@link MetaItem} support
+ * the following meta items:
+ * <ul>
+ * <li>{@link #META_ATTRIBUTE_WRITE_VALUE} (if specified also supports dynamic value injection as described in {@link Protocol})</li>
+ * <li>{@link #META_ATTRIBUTE_FILTERS}</li>
+ * <li>{@link #META_POLLING_MILLIS}</li>
+ * </ul>
+ *
+ */
+public class UdpClientProtocol extends AbstractProtocol {
+
+ private static class AttributeInfo {
+ Consumer<Value> sendConsumer;
+ ScheduledFuture pollingTask;
+
+
+ }
+
+
+ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, UdpClientProtocol.class.getName());
+ public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":udpClient";
+ public static final String PROTOCOL_DISPLAY_NAME = "UDP Client";
+ public static final String PROTOCOL_VERSION = "1.0";
+ private static int DEFAULT_RESPONSE_TIMEOUT_MILLIS = 3000;
+ private static int DEFAULT_SEND_RETRIES = 1;
+ private static boolean DEFAULT_SERVER_ALWAYS_RESPONDS = false;
+ protected final Map<AttributeRef, IoClient<String>> clientMap = new HashMap<>();
+ protected final Map<AttributeRef, Consumer<Value>> attributeWriteMap = new HashMap<>();
+ protected final Map<AttributeRef, ScheduledFuture> attributePollingMap = new HashMap<>();
+
+ /**
+ * The UDP server host name/IP address
+ */
+ public static final MetaItemDescriptor META_PROTOCOL_HOST = metaItemString(
+ PROTOCOL_NAME + ":host",
+ ACCESS_PRIVATE,
+ true,
+ TextUtil.REGEXP_PATTERN_STRING_NON_EMPTY_NO_WHITESPACE,
+ MetaItemDescriptor.PatternFailure.STRING_EMPTY_OR_CONTAINS_WHITESPACE);
+
+ /**
+ * The UDP server port
+ */
+ public static final MetaItemDescriptor META_PROTOCOL_PORT = metaItemInteger(
+ PROTOCOL_NAME + ":port",
+ ACCESS_PRIVATE,
+ true,
+ 1,
+ 65536);
+
+ /**
+ * Optionally sets the port that this UDP client will bind to (if not set then a random ephemeral port will be used)
+ */
+ public static final MetaItemDescriptor META_PROTOCOL_BIND_PORT = metaItemInteger(
+ PROTOCOL_NAME + ":bindPort",
+ ACCESS_PRIVATE,
+ true,
+ 1,
+ 65536);
+
+ /**
+ * Indicates whether the server replies to each packet not just polling requests (need this to successfully match
+ * request and response packets)
+ */
+ MetaItemDescriptor META_SERVER_ALWAYS_RESPONDS = metaItemFixedBoolean(PROTOCOL_NAMESPACE + ":serverAlwaysResponds", ACCESS_PRIVATE, false);
+
+ /**
+ * Indicates how long to wait for a response from the server before re-attempting {@link #META_SEND_RETRIES} times
+ */
+ public static final MetaItemDescriptor META_RESPONSE_TIMEOUT_MILLIS = metaItemInteger(
+ PROTOCOL_NAME + ":responseTimeoutMillis",
+ ACCESS_PRIVATE,
+ true,
+ 1,
+ 10000);
+
+ /**
+ * How many times to retry sending a failed command
+ */
+ public static final MetaItemDescriptor META_SEND_RETRIES = metaItemInteger(
+ PROTOCOL_NAME + ":sendRetries",
+ ACCESS_PRIVATE,
+ true,
+ 1,
+ 10);
+
+ @Override
+ public String getProtocolName() {
+ return PROTOCOL_NAME;
+ }
+
+ @Override
+ public String getProtocolDisplayName() {
+ return PROTOCOL_DISPLAY_NAME;
+ }
+
+ @Override
+ public String getVersion() {
+ return PROTOCOL_VERSION;
+ }
+
+ @Override
+ protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
+ final AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();
+
+ String host = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_HOST,
+ true,
+ true
+ ).flatMap(Values::getString).orElse(null);
+
+ int port = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_PORT,
+ true,
+ true
+ ).flatMap(Values::getIntegerCoerced).orElse(0);
+
+ Integer bindPort = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_BIND_PORT,
+ false,
+ false
+ ).flatMap(Values::getIntegerCoerced).orElse(null);
+
+ boolean hexMode = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_CONVERT_HEX,
+ false,
+ false
+ ).flatMap(Values::getBoolean).orElse(false);
+
+ boolean binaryMode = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_CONVERT_BINARY,
+ false,
+ false
+ ).flatMap(Values::getBoolean).orElse(false);
+
+ Charset charset = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_CHARSET,
+ false,
+ true
+ ).flatMap(Values::getString).map(Charset::forName).orElse(CharsetUtil.UTF_8);
+
+ Consumer<ConnectionStatus> connectionStatusConsumer = connectionStatus ->
+ onConnectionStatusChanged(protocolRef, connectionStatus);
+
+ Consumer<String> messageConsumer = message -> onClientMessageReceived(protocolRef, message);
+
+ IoClient client = addClient(host, port, bindPort, charset, binaryMode, hexMode, messageConsumer, connectionStatusConsumer);
+ clientMap.put(protocolRef, client);
+ connectClient(protocolRef, client);
+ }
+
+ @Override
+ protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
+ final AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();
+
+ IoClient<String> client = clientMap.remove(protocolRef);
+ removeClient(client);
+ disconnectClient(protocolRef, client);
+ updateStatus(protocolRef, ConnectionStatus.DISCONNECTED);
+ }
+
+ @Override
+ protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+
+ IoClient<String> client = clientMap.get(protocolConfiguration.getReferenceOrThrow());
+
+ if (client == null) {
+ return;
+ }
+
+ final String writeValue = Values.getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_WRITE_VALUE, true, true)
+ .map(Object::toString).orElse(null);
+
+ final Integer pollingMillis = Values.getMetaItemValueOrThrow(attribute, META_POLLING_MILLIS, false, true)
+ .flatMap(Values::getIntegerCoerced)
+ .orElse(null);
+
+ final Integer responseTimeoutMillis = Values.getMetaItemValueOrThrow(attribute, META_RESPONSE_TIMEOUT_MILLIS, false, true)
+ .flatMap(Values::getIntegerCoerced)
+ .orElseGet(() ->
+ Values.getMetaItemValueOrThrow(protocolConfiguration, META_RESPONSE_TIMEOUT_MILLIS, false, true)
+ .flatMap(Values::getIntegerCoerced)
+ .orElse(null)
+ );
+
+ final Integer sendRetries = Values.getMetaItemValueOrThrow(attribute, META_SEND_RETRIES, false, true)
+ .flatMap(Values::getIntegerCoerced)
+ .orElseGet(() ->
+ Values.getMetaItemValueOrThrow(protocolConfiguration, META_SEND_RETRIES, false, true)
+ .flatMap(Values::getIntegerCoerced)
+ .orElse(null)
+ );
+
+ if (!attribute.isReadOnly()) {
+ Consumer<Value> valueWriter = createWriteConsumer(client, attribute.getReferenceOrThrow(), writeValue, null);
+ attributeWriteMap.put(attribute.getReferenceOrThrow(), valueWriter);
+ }
+
+ if (pollingMillis < 1000) {
+ LOG.warning("Polling ms must be >= 1000");
+ return;
+ }
+
+ if (pollingMillis != null && TextUtil.isNullOrEmpty(writeValue)) {
+ LOG.warning("Polling requires the META_ATTRIBUTE_WRITE_VALUE meta item to be set");
+ return;
+ }
+
+ if (pollingMillis != null) {
+ Consumer<String> responseConsumer = str ->
+ updateLinkedAttribute(
+ new AttributeState(
+ attribute.getReferenceOrThrow(),
+ str != null ? Values.create(str) : null));
+
+ Consumer<Value> pollingWriter = createWriteConsumer(client, attribute.getReferenceOrThrow(), writeValue, responseConsumer);
+ Runnable pollingTask = () -> pollingWriter.accept(null);
+ ScheduledFuture pollingFuture = schedulePollingRequest(client, attribute.getReferenceOrThrow(), pollingTask, pollingMillis);
+ attributePollingMap.put(attribute.getReferenceOrThrow(), pollingFuture);
+ }
+ }
+
+ protected Consumer<Value> createWriteConsumer(IoClient<String> client, AttributeRef attributeRef, String writeValue, Consumer<String> responseConsumer) {
+ return value -> {
+
+ String str = value != null ? value.toString() : "";
+
+ if (!TextUtil.isNullOrEmpty(writeValue) && writeValue.contains(DYNAMIC_VALUE_PLACEHOLDER)) {
+ str = writeValue.replaceAll(DYNAMIC_VALUE_PLACEHOLDER_REGEXP, str);
+ }
+
+ onClientWriteRequest(client, attributeRef, str, responseConsumer);
+ };
+ }
+
+ @Override
+ protected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+ attributeWriteMap.remove(attribute.getReferenceOrThrow());
+ ScheduledFuture pollingTask = attributePollingMap.remove(attribute.getReferenceOrThrow());
+
+ if (pollingTask != null) {
+ pollingTask.cancel(false);
+ }
+ }
+
+ @Override
+ protected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration) {
+ Consumer<Value> writer = attributeWriteMap.get(event.getAttributeRef());
+
+ if (writer == null) {
+ LOG.info("Request to write unlinked attribute so ignoring: " + event);
+ return;
+ }
+
+ writer.accept(event.getValue().orElse(null));
+ }
+
+ protected void onConnectionStatusChanged(AttributeRef protocolRef, ConnectionStatus connectionStatus) {
+ updateStatus(protocolRef, connectionStatus);
+ }
+
+ protected void onClientWriteRequest(IoClient<String> client, AttributeRef attributeRef, String value, Consumer<String> responseConsumer) {
+
+ }
+
+ protected void onClientMessageReceived(AttributeRef protocolRef, String message) {
+
+ }
+
+ protected ScheduledFuture schedulePollingRequest(IoClient<String> client,
+ AttributeRef attributeRef,
+ Runnable pollingTask,
+ int pollingMillis) {
+
+ LOG.fine("Scheduling polling request on client '" + client + "' to execute every " + pollingMillis + " seconds for attribute: " + attributeRef);
+
+ return executorService.scheduleWithFixedDelay(pollingTask, 0, pollingMillis, TimeUnit.MILLISECONDS);
+ }
+
+ protected IoClient<String> addClient(String host, int port, Integer bindPort, Charset charset, boolean binaryMode, boolean hexMode, Consumer<String> messageConsumer, Consumer<ConnectionStatus> statusConsumer) {
+
+ LOG.info("Adding UDP client");
+
+ BiConsumer<ByteBuf, List<String>> decoder;
+ BiConsumer<String, ByteBuf> encoder;
+
+ if (hexMode) {
+ decoder = (buf, messages) -> {
+ byte[] bytes = new byte[buf.readableBytes()];
+ buf.readBytes(bytes);
+ String msg = Protocol.bytesToHexString(bytes);
+ buf.release();
+ messages.add(msg);
+ };
+ encoder = (message, buf) -> {
+ byte[] bytes = Protocol.bytesFromHexString(message);
+ buf.writeBytes(bytes);
+ };
+ } else if (binaryMode) {
+ decoder = (buf, messages) -> {
+ byte[] bytes = new byte[buf.readableBytes()];
+ buf.readBytes(bytes);
+ String msg = Protocol.bytesToBinaryString(bytes);
+ buf.release();
+ messages.add(msg);
+ };
+ encoder = (message, buf) -> {
+ byte[] bytes = Protocol.bytesFromBinaryString(message);
+ buf.writeBytes(bytes);
+ };
+ } else {
+ final Charset finalCharset = charset != null ? charset : CharsetUtil.UTF_8;
+ decoder = (buf, messages) -> {
+ String msg = buf.toString(finalCharset);
+ buf.release();
+ messages.add(msg);
+ };
+ encoder = (message, buf) -> buf.writeBytes(message.getBytes(finalCharset));
+ }
+
+ BiConsumer<ByteBuf, List<String>> finalDecoder = decoder;
+ BiConsumer<String, ByteBuf> finalEncoder = encoder;
+
+ final IoClient<String> client = new AbstractUdpClient<String>(host, port, bindPort, executorService) {
+
+ @Override
+ protected void decode(ByteBuf buf, List<String> messages) {
+ finalDecoder.accept(buf, messages);
+ }
+
+ @Override
+ protected void encode(String message, ByteBuf buf) {
+ finalEncoder.accept(message, buf);
+ }
+ };
+
+ client.addMessageConsumer(messageConsumer);
+ client.addConnectionStatusConsumer(statusConsumer);
+ return client;
+ }
+
+ protected void removeClient(IoClient client) {
+ if (client == null) {
+ return;
+ }
+
+ LOG.info("Removing UDP client");
+ client.removeAllMessageConsumers();
+ client.removeAllConnectionStatusConsumers();
+ }
+
+ protected void connectClient(AttributeRef protocolRef, IoClient client) {
+ if (client == null) {
+ return;
+ }
+ LOG.info("Connecting UDP client");
+ client.connect();
+ }
+
+ protected void disconnectClient(AttributeRef protocolRef, IoClient client) {
+ if (client == null) {
+ return;
+ }
+ LOG.info("Disconnecting UDP client");
+ client.disconnect();
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/udp/UdpStringServer.java b/agent/src/main/java/org/openremote/agent/protocol/udp/UdpStringServer.java
new file mode 100644
index 000000000..2592bd511
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/udp/UdpStringServer.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright 2019, 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.udp;
+
+import io.netty.buffer.Unpooled;
+import io.netty.channel.socket.DatagramChannel;
+import io.netty.handler.codec.DelimiterBasedFrameDecoder;
+import io.netty.handler.codec.string.StringDecoder;
+import io.netty.handler.codec.string.StringEncoder;
+import org.openremote.agent.protocol.ProtocolExecutorService;
+
+import java.net.InetSocketAddress;
+
+/**
+ * This is an {@link AbstractUdpServer} implementation that handles {@link String} messages.
+ * <p>
+ * Uses {@link DelimiterBasedFrameDecoder} and {@link StringDecoder}.
+ */
+public class UdpStringServer extends AbstractUdpServer<String> {
+
+ protected String delimiter;
+ protected int maxFrameLength;
+ protected boolean stripDelimiter;
+
+ public UdpStringServer(ProtocolExecutorService executorService, InetSocketAddress localAddress, String delimiter, int maxFrameLength, boolean stripDelimiter) {
+ super(executorService, localAddress);
+ this.delimiter = delimiter;
+ this.maxFrameLength = maxFrameLength;
+ this.stripDelimiter = stripDelimiter;
+ }
+
+ @Override
+ protected void addDecoders(DatagramChannel channel) {
+ // Add delimiter and string decoders to do the work
+ addDecoder(channel, new DelimiterBasedFrameDecoder(maxFrameLength, stripDelimiter, Unpooled.wrappedBuffer(delimiter.getBytes())));
+ addDecoder(channel, new StringDecoder());
+ }
+
+ @Override
+ protected void addEncoders(DatagramChannel channel) {
+ addEncoder(channel, new StringEncoder());
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/AbstractVelbusProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/AbstractVelbusProtocol.java
index 35e82b51b..cd8884ace 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/AbstractVelbusProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/AbstractVelbusProtocol.java
@@ -20,6 +20,7 @@
package org.openremote.agent.protocol.velbus;
import org.openremote.agent.protocol.*;
+import org.openremote.agent.protocol.io.IoClient;
import org.openremote.agent.protocol.velbus.device.DevicePropertyValue;
import org.openremote.agent.protocol.velbus.device.FeatureProcessor;
import org.openremote.agent.protocol.velbus.device.VelbusDeviceType;
@@ -135,7 +136,7 @@ public abstract class AbstractVelbusProtocol extends AbstractProtocol implements
velbusNetwork = networkMap.get(networkIdentifier);
} else {
try {
- MessageProcessor<VelbusPacket> messageProcessor = createMessageProcessor(protocolConfiguration);
+ IoClient<VelbusPacket> messageProcessor = createClient(protocolConfiguration);
int timeInjectionSeconds = getTimeInjectionIntervalSeconds(protocolConfiguration);
LOG.fine("Creating new VELBUS network instance for protocolConfiguration: " + protocolRef);
velbusNetwork = new VelbusNetwork(messageProcessor, executorService, timeInjectionSeconds);
@@ -148,7 +149,7 @@ public abstract class AbstractVelbusProtocol extends AbstractProtocol implements
}
if (velbusNetwork != null) {
- if (protocolConfiguration.isEnabled() && velbusNetwork.getConnectionStatus() == ConnectionStatus.DISCONNECTED) {
+ if (velbusNetwork.getConnectionStatus() == ConnectionStatus.DISCONNECTED) {
velbusNetwork.connect();
}
Consumer<ConnectionStatus> statusConsumer = status -> updateStatus(protocolRef, status);
@@ -349,9 +350,9 @@ public abstract class AbstractVelbusProtocol extends AbstractProtocol implements
}
/**
- * Should return an instance of {@link MessageProcessor} for the supplied protocolConfiguration
+ * Should return an instance of {@link IoClient} for the supplied protocolConfiguration
*/
- protected abstract MessageProcessor<VelbusPacket> createMessageProcessor(AssetAttribute protocolConfiguration) throws RuntimeException;
+ protected abstract IoClient<VelbusPacket> createClient(AssetAttribute protocolConfiguration) throws RuntimeException;
/**
diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusConfiguration.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusConfiguration.java
index 7a3c7175b..7f916b2bb 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusConfiguration.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusConfiguration.java
@@ -65,7 +65,7 @@ public final class VelbusConfiguration {
result.addAttributeFailure(
new ValidationFailure(
ValueHolder.ValueFailureReason.VALUE_MISMATCH,
- VelbusSocketProtocol.PROTOCOL_NAME));
+ VelbusTcpProtocol.PROTOCOL_NAME));
}
}
@@ -75,7 +75,7 @@ public final class VelbusConfiguration {
if (attribute.getMeta() != null && !attribute.getMeta().isEmpty()) {
for (int i = 0; i < attribute.getMeta().size(); i++) {
MetaItem metaItem = attribute.getMeta().get(i);
- if (isMetaNameEqualTo(metaItem, VelbusSocketProtocol.META_VELBUS_SOCKET_HOST)) {
+ if (isMetaNameEqualTo(metaItem, VelbusTcpProtocol.META_VELBUS_SOCKET_HOST)) {
hostFound = true;
if (isNullOrEmpty(metaItem.getValueAsString().orElse(null))) {
failure = true;
@@ -85,7 +85,7 @@ public final class VelbusConfiguration {
result.addMetaFailure(i,
new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_VALUE_IS_REQUIRED, ValueType.STRING.name()));
}
- } else if (isMetaNameEqualTo(metaItem, VelbusSocketProtocol.META_VELBUS_SOCKET_PORT)) {
+ } else if (isMetaNameEqualTo(metaItem, VelbusTcpProtocol.META_VELBUS_SOCKET_PORT)) {
portFound = true;
int port = metaItem.getValueAsInteger().orElse(0);
if (port <= 0 || port > 65536) {
@@ -106,7 +106,7 @@ public final class VelbusConfiguration {
result.addMetaFailure(
new ValidationFailure(
MetaItem.MetaItemFailureReason.META_ITEM_MISSING,
- VelbusSocketProtocol.META_VELBUS_SOCKET_HOST));
+ VelbusTcpProtocol.META_VELBUS_SOCKET_HOST));
}
}
if (!portFound) {
@@ -115,7 +115,7 @@ public final class VelbusConfiguration {
result.addMetaFailure(
new ValidationFailure(
MetaItem.MetaItemFailureReason.META_ITEM_MISSING,
- VelbusSocketProtocol.META_VELBUS_SOCKET_PORT));
+ VelbusTcpProtocol.META_VELBUS_SOCKET_PORT));
}
}
@@ -170,7 +170,7 @@ public final class VelbusConfiguration {
failure = true;
if (result != null) {
result.addMetaFailure(
- new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_MISSING, VelbusSocketProtocol.META_VELBUS_SOCKET_PORT)
+ new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_MISSING, VelbusTcpProtocol.META_VELBUS_SOCKET_PORT)
);
}
}
@@ -187,7 +187,7 @@ public final class VelbusConfiguration {
}
public static boolean isSocketConfiguration(AssetAttribute attribute) {
- return attribute != null && attribute.getValueAsString().map(value -> value.equals(VelbusSocketProtocol.PROTOCOL_NAME)).orElse(false);
+ return attribute != null && attribute.getValueAsString().map(value -> value.equals(VelbusTcpProtocol.PROTOCOL_NAME)).orElse(false);
}
public static boolean isSerialConfiguration(AssetAttribute attribute) {
diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusNetwork.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusNetwork.java
index 1ad5c6349..341ce34be 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusNetwork.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusNetwork.java
@@ -19,22 +19,25 @@
*/
package org.openremote.agent.protocol.velbus;
-import org.openremote.agent.protocol.*;
-import org.openremote.agent.protocol.velbus.device.*;
+import org.openremote.agent.protocol.ProtocolExecutorService;
+import org.openremote.agent.protocol.io.IoClient;
+import org.openremote.agent.protocol.velbus.device.DevicePropertyValue;
+import org.openremote.agent.protocol.velbus.device.VelbusDevice;
import org.openremote.model.asset.agent.ConnectionStatus;
-import org.openremote.model.value.*;
+import org.openremote.model.value.Value;
import java.util.*;
-import java.util.concurrent.*;
-import java.util.function.*;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledFuture;
+import java.util.function.Consumer;
-import static org.openremote.agent.protocol.velbus.AbstractVelbusProtocol.*;
+import static org.openremote.agent.protocol.velbus.AbstractVelbusProtocol.LOG;
public class VelbusNetwork {
protected static int DELAY_BETWEEN_PACKET_WRITES_MILLISECONDS = 100; // Need to throttle bus writes
protected final Integer timeInjectionIntervalSeconds;
- protected MessageProcessor<VelbusPacket> messageProcessor;
+ protected IoClient<VelbusPacket> client;
protected final Queue<VelbusPacket> messageQueue = new ArrayDeque<>();
protected List<ScheduledFuture> scheduledTasks = new ArrayList<>();
protected ScheduledFuture timeInjector;
@@ -44,12 +47,12 @@ public class VelbusNetwork {
protected ProtocolExecutorService executorService;
protected final List<Consumer<ConnectionStatus>> connectionStatusConsumers = new ArrayList<>();
- public VelbusNetwork(MessageProcessor<VelbusPacket> messageProcessor, ProtocolExecutorService executorService, Integer timeInjectionIntervalSeconds) {
- this.messageProcessor = messageProcessor;
+ public VelbusNetwork(IoClient<VelbusPacket> client, ProtocolExecutorService executorService, Integer timeInjectionIntervalSeconds) {
+ this.client = client;
this.executorService = executorService;
this.timeInjectionIntervalSeconds = timeInjectionIntervalSeconds;
- messageProcessor.addConnectionStatusConsumer(this::onConnectionStatusChanged);
- messageProcessor.addMessageConsumer(this::onPacketReceived);
+ client.addConnectionStatusConsumer(this::onConnectionStatusChanged);
+ client.addMessageConsumer(this::onPacketReceived);
onConnectionStatusChanged(getConnectionStatus());
if (timeInjectionIntervalSeconds != null) {
timeInjector = getExecutorService().scheduleWithFixedDelay(this::doTimeInjection, timeInjectionIntervalSeconds * 1000, timeInjectionIntervalSeconds * 1000);
@@ -83,19 +86,19 @@ public class VelbusNetwork {
}
public void connect() {
- if (messageProcessor == null) {
+ if (client == null) {
return;
}
- messageProcessor.connect();
+ client.connect();
}
public void disconnect() {
scheduledTasks.forEach(task -> task.cancel(true));
scheduledTasks.clear();
- if (messageProcessor != null) {
- messageProcessor.disconnect();
+ if (client != null) {
+ client.disconnect();
}
}
@@ -111,15 +114,15 @@ public class VelbusNetwork {
disconnect();
- if (messageProcessor != null) {
- messageProcessor.removeConnectionStatusConsumer(this::onConnectionStatusChanged);
- messageProcessor.removeMessageConsumer(this::onPacketReceived);
- messageProcessor = null;
+ if (client != null) {
+ client.removeConnectionStatusConsumer(this::onConnectionStatusChanged);
+ client.removeMessageConsumer(this::onPacketReceived);
+ client = null;
}
}
public ConnectionStatus getConnectionStatus() {
- return messageProcessor.getConnectionStatus();
+ return client.getConnectionStatus();
}
protected void onConnectionStatusChanged(ConnectionStatus status) {
@@ -271,7 +274,7 @@ public class VelbusNetwork {
if (packet != null) {
VelbusPacket.OutboundCommand command = VelbusPacket.OutboundCommand.fromCode(packet.getCommand());
LOG.finest("Sending packet " + command + " : " + packet);
- messageProcessor.sendMessage(packet);
+ client.sendMessage(packet);
} else {
queueProcessingTask.cancel(false);
queueProcessingTask = null;
diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialMessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialClient.java
similarity index 82%
rename from agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialMessageProcessor.java
rename to agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialClient.java
index 74ac5539a..87df29cfa 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialMessageProcessor.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialClient.java
@@ -20,14 +20,14 @@
package org.openremote.agent.protocol.velbus;
import io.netty.buffer.ByteBuf;
-import org.openremote.agent.protocol.AbstractSerialMessageProcessor;
+import org.openremote.agent.protocol.serial.AbstractSerialClient;
import org.openremote.agent.protocol.ProtocolExecutorService;
import java.util.List;
-public class VelbusSerialMessageProcessor extends AbstractSerialMessageProcessor<VelbusPacket> {
+public class VelbusSerialClient extends AbstractSerialClient<VelbusPacket> {
- public VelbusSerialMessageProcessor(String port, Integer baudRate, ProtocolExecutorService executorService) {
+ public VelbusSerialClient(String port, Integer baudRate, ProtocolExecutorService executorService) {
super(port, baudRate, executorService);
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialProtocol.java
index bedd6cfc3..199523117 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialProtocol.java
@@ -19,7 +19,8 @@
*/
package org.openremote.agent.protocol.velbus;
-import org.openremote.agent.protocol.MessageProcessor;
+import org.openremote.agent.protocol.io.IoClient;
+import org.openremote.agent.protocol.serial.NrJavaSerialAddress;
import org.openremote.agent.protocol.ProtocolConfigurationDiscovery;
import org.openremote.model.AbstractValueHolder;
import org.openremote.model.asset.AssetAttribute;
@@ -100,7 +101,7 @@ public class VelbusSerialProtocol extends AbstractVelbusProtocol implements Prot
}
@Override
- protected MessageProcessor<VelbusPacket> createMessageProcessor(AssetAttribute protocolConfiguration) throws RuntimeException {
+ protected IoClient<VelbusPacket> createClient(AssetAttribute protocolConfiguration) throws RuntimeException {
// Extract port and baud rate
String port = protocolConfiguration.getMetaItem(META_VELBUS_SERIAL_PORT).flatMap(AbstractValueHolder::getValueAsString).orElse(null);
@@ -108,7 +109,7 @@ public class VelbusSerialProtocol extends AbstractVelbusProtocol implements Prot
TextUtil.requireNonNullAndNonEmpty(port, "Port cannot be null or empty");
- return new VelbusSerialMessageProcessor(port, baudRate, executorService);
+ return new VelbusSerialClient(port, baudRate, executorService);
}
@Override
diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSocketMessageProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusTcpClient.java
similarity index 82%
rename from agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSocketMessageProcessor.java
rename to agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusTcpClient.java
index a6b775a64..a0c896c58 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSocketMessageProcessor.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusTcpClient.java
@@ -20,14 +20,14 @@
package org.openremote.agent.protocol.velbus;
import io.netty.buffer.ByteBuf;
-import org.openremote.agent.protocol.AbstractSocketMessageProcessor;
+import org.openremote.agent.protocol.tcp.AbstractTcpClient;
import org.openremote.agent.protocol.ProtocolExecutorService;
import java.util.List;
-public class VelbusSocketMessageProcessor extends AbstractSocketMessageProcessor<VelbusPacket> {
+public class VelbusTcpClient extends AbstractTcpClient<VelbusPacket> {
- public VelbusSocketMessageProcessor(String host, int port, ProtocolExecutorService executorService) {
+ public VelbusTcpClient(String host, int port, ProtocolExecutorService executorService) {
super(host, port, executorService);
}
@Override
diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSocketProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusTcpProtocol.java
similarity index 93%
rename from agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSocketProtocol.java
rename to agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusTcpProtocol.java
index 3fe41e8f0..7e1147c58 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSocketProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusTcpProtocol.java
@@ -19,7 +19,7 @@
*/
package org.openremote.agent.protocol.velbus;
-import org.openremote.agent.protocol.MessageProcessor;
+import org.openremote.agent.protocol.io.IoClient;
import org.openremote.model.AbstractValueHolder;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.attribute.AttributeValidationResult;
@@ -35,7 +35,7 @@ import java.util.Objects;
import static org.openremote.model.util.TextUtil.REGEXP_PATTERN_INTEGER_POSITIVE_NON_ZERO;
-public class VelbusSocketProtocol extends AbstractVelbusProtocol {
+public class VelbusTcpProtocol extends AbstractVelbusProtocol {
public static final String PROTOCOL_NAME = PROTOCOL_BASE_NAME + "Socket";
public static final String PROTOCOL_DISPLAY_NAME = "VELBUS Socket";
@@ -100,7 +100,7 @@ public class VelbusSocketProtocol extends AbstractVelbusProtocol {
}
@Override
- protected MessageProcessor<VelbusPacket> createMessageProcessor(AssetAttribute protocolConfiguration) throws RuntimeException {
+ protected IoClient<VelbusPacket> createClient(AssetAttribute protocolConfiguration) throws RuntimeException {
// Extract IP and Host
String host = protocolConfiguration.getMetaItem(META_VELBUS_SOCKET_HOST).flatMap(AbstractValueHolder::getValueAsString).orElse(null);
@@ -109,7 +109,7 @@ public class VelbusSocketProtocol extends AbstractVelbusProtocol {
TextUtil.requireNonNullAndNonEmpty(host, "Host cannot be null or empty");
Objects.requireNonNull(port, "Port cannot be null");
- return new VelbusSocketMessageProcessor(host, port, executorService);
+ return new VelbusTcpClient(host, port, executorService);
}
@Override
diff --git a/agent/src/main/resources/META-INF/services/org.openremote.container.ContainerService b/agent/src/main/resources/META-INF/services/org.openremote.container.ContainerService
index 99f2a05f6..f89460af8 100644
--- a/agent/src/main/resources/META-INF/services/org.openremote.container.ContainerService
+++ b/agent/src/main/resources/META-INF/services/org.openremote.container.ContainerService
@@ -2,7 +2,7 @@ org.openremote.agent.protocol.simulator.SimulatorProtocol
org.openremote.agent.protocol.macro.MacroProtocol
org.openremote.agent.protocol.timer.TimerProtocol
org.openremote.agent.protocol.knx.KNXProtocol
-org.openremote.agent.protocol.velbus.VelbusSocketProtocol
+org.openremote.agent.protocol.velbus.VelbusTcpProtocol
org.openremote.agent.protocol.velbus.VelbusSerialProtocol
org.openremote.agent.protocol.http.HttpClientProtocol
org.openremote.agent.protocol.controller.ControllerProtocol
\ No newline at end of file
diff --git a/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java
index 8f0a15a0e..ab5e382bd 100644
--- a/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java
+++ b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java
@@ -26,8 +26,7 @@ import jsinterop.annotations.JsConstructor;
import jsinterop.annotations.JsIgnore;
import jsinterop.annotations.JsType;
import org.openremote.model.ValidationFailure;
-import org.openremote.model.value.Value;
-import org.openremote.model.value.ValueType;
+import org.openremote.model.value.*;
import java.util.Arrays;
import java.util.Optional;
@@ -192,4 +191,124 @@ public class MetaItemDescriptorImpl implements MetaItemDescriptor {
", patternFailureMessage='" + patternFailureMessage + '\'' +
'}';
}
+
+ public static MetaItemDescriptor metaItemFixedBoolean(String urn, Access access, boolean required) {
+ return new MetaItemDescriptorImpl(
+ urn,
+ ValueType.BOOLEAN,
+ access,
+ required,
+ null,
+ null,
+ 1,
+ Values.create(true),
+ true,
+ null,
+ null,
+ null);
+ }
+
+ public static MetaItemDescriptor metaItemString(String urn, Access access, boolean required, String...allowedValues) {
+ Value[] values = allowedValues != null && allowedValues.length > 0 ? Arrays.stream(allowedValues).map(Values::create).toArray(Value[]::new) : null;
+
+ return new MetaItemDescriptorImpl(
+ urn,
+ ValueType.STRING,
+ access,
+ required,
+ null,
+ null,
+ 1,
+ values != null ? values[0] : null,
+ false,
+ null,
+ null,
+ allowedValues != null ? Arrays.stream(allowedValues).map(Values::create).toArray(Value[]::new) : null);
+ }
+
+ public static MetaItemDescriptor metaItemString(String urn, Access access, boolean required, String patternRegex, PatternFailure failureMessage) {
+ return metaItemString(urn, access, required, patternRegex, failureMessage.name());
+ }
+
+ public static MetaItemDescriptor metaItemString(String urn, Access access, boolean required, String patternRegex, String patternFailureMessage) {
+ return new MetaItemDescriptorImpl(
+ urn,
+ ValueType.STRING,
+ access,
+ required,
+ patternRegex,
+ patternFailureMessage,
+ 1,
+ null,
+ false,
+ null,
+ null,
+ null);
+ }
+
+ public static MetaItemDescriptor metaItemInteger(String urn, Access access, boolean required, Integer minValue, Integer maxValue) {
+ return new MetaItemDescriptorImpl(
+ urn,
+ ValueType.NUMBER,
+ access,
+ required,
+ null,
+ null,
+ 1,
+ minValue != null ? Values.create(minValue) : null,
+ false,
+ minValue != null ? Values.create(minValue) : null,
+ maxValue != null ? Values.create(maxValue) : null,
+ null);
+ }
+
+ public static MetaItemDescriptor metaItemInteger(String urn, Access access, boolean required, Integer...allowedValues) {
+ Value[] values = allowedValues != null && allowedValues.length > 0 ? Arrays.stream(allowedValues).map(Values::create).toArray(Value[]::new) : null;
+
+ return new MetaItemDescriptorImpl(
+ urn,
+ ValueType.NUMBER,
+ access,
+ required,
+ null,
+ null,
+ 1,
+ values != null ? values[0] : null,
+ false,
+ null,
+ null,
+ values);
+ }
+
+ public static MetaItemDescriptor metaItemObject(String urn, Access access, boolean required, ObjectValue initialValue) {
+ return new MetaItemDescriptorImpl(
+ urn,
+ ValueType.OBJECT,
+ access,
+ required,
+ null,
+ null,
+ 1,
+ initialValue,
+ false,
+ null,
+ null,
+ null);
+ }
+
+ public static MetaItemDescriptor metaItemArray(String urn, Access access, boolean required, ArrayValue initialValue) {
+ return new MetaItemDescriptorImpl(
+ urn,
+ ValueType.ARRAY,
+ access,
+ required,
+ null,
+ null,
+ 1,
+ initialValue,
+ false,
+ null,
+ null,
+ null);
+ }
}
diff --git a/model/src/main/java/org/openremote/model/value/ValueType.java b/model/src/main/java/org/openremote/model/value/ValueType.java
index 37c93868f..ff814ab89 100644
--- a/model/src/main/java/org/openremote/model/value/ValueType.java
+++ b/model/src/main/java/org/openremote/model/value/ValueType.java
@@ -26,6 +26,7 @@ import java.util.Locale;
@JsType(namespace = "Model", name = "ValueType")
public enum ValueType {
+ ANY(Value.class),
OBJECT(ObjectValue.class),
ARRAY(ArrayValue.class),
STRING(StringValue.class),
diff --git a/model/src/main/java/org/openremote/model/value/Values.java b/model/src/main/java/org/openremote/model/value/Values.java
index c230b7e52..3cdbdb0ce 100644
--- a/model/src/main/java/org/openremote/model/value/Values.java
+++ b/model/src/main/java/org/openremote/model/value/Values.java
@@ -19,6 +19,7 @@ import jsinterop.annotations.JsMethod;
import jsinterop.base.Any;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.attribute.MetaItem;
+import org.openremote.model.attribute.MetaItemDescriptor;
import org.openremote.model.util.TextUtil;
import org.openremote.model.value.impl.ValueFactoryImpl;
@@ -172,6 +173,20 @@ public class Values {
return Optional.of(stream.collect(Collectors.toList()));
}
+ @SuppressWarnings("unchecked")
+ public static <T extends Value> Optional<T> getMetaItemValueOrThrow(AssetAttribute attribute,
+ MetaItemDescriptor metaItemDescriptor,
+ boolean throwIfMetaMissing,
+ boolean throwIfValueMissing)
+ throws IllegalArgumentException {
+ return getMetaItemValueOrThrow(
+ attribute,
+ metaItemDescriptor.getUrn(),
+ metaItemDescriptor.getValueType().getModelType(),
+ throwIfMetaMissing,
+ throwIfValueMissing);
+ }
+
@SuppressWarnings("unchecked")
public static <T extends Value> Optional<T> getMetaItemValueOrThrow(AssetAttribute attribute,
String name,
diff --git a/test/src/main/groovy/org/openremote/test/MockMessageProcessor.java b/test/src/main/groovy/org/openremote/test/MockVelbusClient.java
similarity index 89%
rename from test/src/main/groovy/org/openremote/test/MockMessageProcessor.java
rename to test/src/main/groovy/org/openremote/test/MockVelbusClient.java
index 8d9fab5aa..4c7b81d68 100644
--- a/test/src/main/groovy/org/openremote/test/MockMessageProcessor.java
+++ b/test/src/main/groovy/org/openremote/test/MockVelbusClient.java
@@ -19,16 +19,16 @@
*/
package org.openremote.test;
-import org.openremote.model.asset.agent.ConnectionStatus;
-import org.openremote.agent.protocol.MessageProcessor;
+import org.openremote.agent.protocol.io.IoClient;
import org.openremote.agent.protocol.velbus.VelbusPacket;
+import org.openremote.model.asset.agent.ConnectionStatus;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
-public class MockMessageProcessor implements MessageProcessor<VelbusPacket> {
+public class MockVelbusClient implements IoClient<VelbusPacket> {
protected final List<Consumer<VelbusPacket>> messageConsumers = new ArrayList<>();
protected final List<Consumer<ConnectionStatus>> statusConsumers = new ArrayList<>();
protected List<VelbusPacket> sentMessages = new ArrayList<>();
@@ -57,9 +57,9 @@ public class MockMessageProcessor implements MessageProcessor<VelbusPacket> {
if (mappings != null) {
synchronized (messageConsumers) {
mappings.forEach(returnPacket -> {
- messageConsumers.forEach(consumer -> {
- consumer.accept(VelbusPacket.fromString(returnPacket));
- });
+ messageConsumers.forEach(consumer ->
+ consumer.accept(VelbusPacket.fromString(returnPacket))
+ );
});
}
}
@@ -84,6 +84,11 @@ public class MockMessageProcessor implements MessageProcessor<VelbusPacket> {
messageConsumers.remove(messageConsumer);
}
+ @Override
+ public void removeAllMessageConsumers() {
+ messageConsumers.clear();
+ }
+
@Override
public void addConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {
statusConsumers.add(connectionStatusConsumer);
@@ -94,6 +99,11 @@ public class MockMessageProcessor implements MessageProcessor<VelbusPacket> {
statusConsumers.remove(connectionStatusConsumer);
}
+ @Override
+ public void removeAllConnectionStatusConsumers() {
+ statusConsumers.clear();
+ }
+
@Override
public ConnectionStatus getConnectionStatus() {
return connectionStatus;
diff --git a/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
index 6b3e2e377..ccc853f25 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
@@ -310,7 +310,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,
new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()
),
new MetaItem(
- Protocol.META_PROTOCOL_FILTERS,
+ Protocol.META_ATTRIBUTE_FILTERS,
Values.createArray().add(new RegexFilter("\\w(\\d+)", 1, 2).toValue().get())
)
),
@@ -322,7 +322,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,
new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()
),
new MetaItem(
- Protocol.META_PROTOCOL_FILTERS,
+ Protocol.META_ATTRIBUTE_FILTERS,
Values.createArray().add(new SubStringFilter(10, 12).toValue().get())
)
),
@@ -334,7 +334,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,
new AttributeRef(mockAgent.getId(), "mockConfig1").toArrayValue()
),
new MetaItem(
- Protocol.META_PROTOCOL_FILTERS,
+ Protocol.META_ATTRIBUTE_FILTERS,
Values.createArray()
.add(new SubStringFilter(23).toValue().get())
.add(new RegexFilter("[a-z|\\s]+(\\d+)%\"}", 1, 0).toValue().get())
@@ -370,7 +370,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,
assert protocolMethodCalls[14] == "LINK_ATTRIBUTE"
assert protocolMethodCalls[15] == "LINK_ATTRIBUTE"
- expect: "the linked attributes values should have been updated by the protocol"
+ and: "the linked attributes values should have been updated by the protocol"
conditions.eventually {
def mockAsset = assetStorageService.find(mockThing.getId(), true)
// Check all valid linked attributes have the new values
@@ -514,6 +514,22 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,
assert !mockThing.getAttribute("filterRegexSubstring").get().getValueAsNumber().isPresent()
}
+ when: "the disabled protocol configuration is enabled"
+ protocolMethodCalls.clear()
+ mockAgent.getAttribute("mockConfig4").ifPresent({it.meta.removeIf({it.name.get() == MetaItemType.DISABLED.urn})})
+ mockAgent = assetStorageService.merge(mockAgent)
+
+ then: "the newly enabled protocol configuration should be unlinked and re-linked"
+ conditions.eventually {
+ assert protocolMethodCalls.size() == 6
+ assert protocolMethodCalls[0] == "UNLINK_ATTRIBUTE"
+ assert protocolMethodCalls[1] == "UNLINK_ATTRIBUTE"
+ assert protocolMethodCalls[2] == "UNLINK_PROTOCOL"
+ assert protocolMethodCalls[3] == "LINK_PROTOCOL"
+ assert protocolMethodCalls[4] == "LINK_ATTRIBUTE"
+ assert protocolMethodCalls[5] == "LINK_ATTRIBUTE"
+ }
+
cleanup: "the server should be stopped"
stopContainer(container)
}
diff --git a/test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/TcpClientTest.groovy
similarity index 60%
rename from test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovy
rename to test/src/test/groovy/org/openremote/test/protocol/TcpClientTest.groovy
index 1dd4446fc..f2d2460ee 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/TcpClientTest.groovy
@@ -21,7 +21,7 @@ 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.tcp.AbstractTcpClient
import org.openremote.agent.protocol.tcp.TcpStringServer
import org.openremote.model.asset.agent.ConnectionStatus
import org.openremote.manager.concurrent.ManagerExecutorService
@@ -31,32 +31,31 @@ 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
+ * This tests the {@link AbstractTcpClient} by creating a simple echo server that the client communicates with
*/
-class SocketMessageProcessorTest extends Specification implements ManagerContainerTrait {
+class TcpClientTest extends Specification implements ManagerContainerTrait {
- def "Check socket message processor"() {
+ def "Check socket client"() {
given: "expected conditions"
def conditions = new PollingConditions(timeout: 10, delay: 1)
- and: "a simple socket echo server"
- def socketServerPort = findEphemeralPort()
- 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()
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>(
+ and: "a simple TCP echo server"
+ def echoServerPort = findEphemeralPort()
+ def echoServer = new TcpStringServer(protocolExecutorService, new InetSocketAddress(echoServerPort), ";", Integer.MAX_VALUE, true)
+ echoServer.addMessageConsumer({
+ message, channel, sender -> echoServer.sendMessage(message)
+ })
+
+ and: "a simple TCP client"
+ def client = new AbstractTcpClient<String>(
"localhost",
- socketServerPort,
+ echoServerPort,
protocolExecutorService) {
@Override
@@ -73,36 +72,36 @@ class SocketMessageProcessorTest extends Specification implements ManagerContain
}
}
- and: "we add callback consumers to the message processor"
- def connectionStatus = messageProcessor.getConnectionStatus()
+ and: "we add callback consumers to the client"
+ def connectionStatus = client.getConnectionStatus()
String lastMessage
- messageProcessor.addMessageConsumer({
+ client.addMessageConsumer({
message -> lastMessage = message
})
- messageProcessor.addConnectionStatusConsumer({
+ client.addConnectionStatusConsumer({
status -> connectionStatus = status
})
when: "the server is started"
- socketServer.start()
+ echoServer.start()
then: "the server should be running"
conditions.eventually {
- assert socketServer.channelFuture.isDone()
- assert socketServer.channelFuture.isSuccess()
+ assert echoServer.channelFuture.isDone()
+ assert echoServer.channelFuture.isSuccess()
}
- when: "we call connect on the message processor"
- messageProcessor.connect()
+ when: "we call connect on the client"
+ client.connect()
- then: "the message processor status should become CONNECTED"
+ then: "the client status should become CONNECTED"
conditions.eventually {
- assert messageProcessor.connectionStatus == ConnectionStatus.CONNECTED
+ assert client.connectionStatus == ConnectionStatus.CONNECTED
assert connectionStatus == ConnectionStatus.CONNECTED
}
when: "the server sends a message"
- socketServer.sendMessage("Hello world")
+ echoServer.sendMessage("Hello world")
then: "we should receive the message"
conditions.eventually {
@@ -110,34 +109,34 @@ class SocketMessageProcessorTest extends Specification implements ManagerContain
}
when: "we send a message to the server"
- messageProcessor.sendMessage("Test;")
+ client.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()
+ when: "we request the client to disconnect"
+ client.disconnect()
- then: "the message processor should become DISCONNECTED"
+ then: "the client should become DISCONNECTED"
conditions.eventually {
- assert messageProcessor.connectionStatus == ConnectionStatus.DISCONNECTED
+ assert client.connectionStatus == ConnectionStatus.DISCONNECTED
assert connectionStatus == ConnectionStatus.DISCONNECTED
}
- when: "we reconnect the same message processor"
- messageProcessor.connect()
+ when: "we reconnect the same client"
+ client.connect()
- then: "the message processor status should become CONNECTED"
+ then: "the client status should become CONNECTED"
conditions.eventually {
- assert messageProcessor.connectionStatus == ConnectionStatus.CONNECTED
+ assert client.connectionStatus == ConnectionStatus.CONNECTED
assert connectionStatus == ConnectionStatus.CONNECTED
- assert socketServer.allChannels.size() == 2
+ assert echoServer.allChannels.size() == 1
}
when: "the server sends a message"
- socketServer.sendMessage("Is there anyone there?")
+ echoServer.sendMessage("Is there anyone there?")
then: "we should receive the message"
conditions.eventually {
@@ -145,7 +144,7 @@ class SocketMessageProcessorTest extends Specification implements ManagerContain
}
when: "we send a message to the server"
- messageProcessor.sendMessage("Yes there is!;")
+ client.sendMessage("Yes there is!;")
then: "we should get the same message back"
conditions.eventually {
@@ -153,25 +152,25 @@ class SocketMessageProcessorTest extends Specification implements ManagerContain
}
when: "we lose connection to the server"
- socketServer.stop()
+ echoServer.stop()
- then: "the message processor status should change to WAITING"
+ then: "the client status should change to WAITING"
conditions.eventually {
- assert messageProcessor.connectionStatus == ConnectionStatus.WAITING
+ assert client.connectionStatus == ConnectionStatus.WAITING
assert connectionStatus == ConnectionStatus.WAITING
}
when: "the connection to the server is restored"
- socketServer.start()
+ echoServer.start()
- then: "the message processor status should become CONNECTED"
+ then: "the client status should become CONNECTED"
conditions.eventually {
- assert messageProcessor.connectionStatus == ConnectionStatus.CONNECTED
+ assert client.connectionStatus == ConnectionStatus.CONNECTED
assert connectionStatus == ConnectionStatus.CONNECTED
}
when: "the server sends a message"
- socketServer.sendMessage("Is there anyone there?")
+ echoServer.sendMessage("Is there anyone there?")
then: "we should receive the message"
conditions.eventually {
@@ -179,7 +178,7 @@ class SocketMessageProcessorTest extends Specification implements ManagerContain
}
when: "we send a message to the server"
- messageProcessor.sendMessage("Yes there is!;")
+ client.sendMessage("Yes there is!;")
then: "we should get the same message back"
conditions.eventually {
@@ -187,17 +186,17 @@ class SocketMessageProcessorTest extends Specification implements ManagerContain
}
when: "we request the processor to disconnect"
- messageProcessor.disconnect()
+ client.disconnect()
- then: "the message processor should become DISCONNECTED"
+ then: "the client should become DISCONNECTED"
conditions.eventually {
- assert messageProcessor.connectionStatus == ConnectionStatus.DISCONNECTED
+ assert client.connectionStatus == ConnectionStatus.DISCONNECTED
assert connectionStatus == ConnectionStatus.DISCONNECTED
}
cleanup: "the server should be stopped"
- messageProcessor.disconnect()
- socketServer.stop()
+ client.disconnect()
+ echoServer.stop()
stopContainer(container)
}
}
diff --git a/test/src/test/groovy/org/openremote/test/protocol/UdpClientTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/UdpClientTest.groovy
new file mode 100644
index 000000000..f8c2027ca
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/protocol/UdpClientTest.groovy
@@ -0,0 +1,177 @@
+/*
+ * 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 io.netty.util.internal.SocketUtils
+import org.openremote.agent.protocol.udp.AbstractUdpClient
+import org.openremote.agent.protocol.udp.UdpStringServer
+import org.openremote.manager.concurrent.ManagerExecutorService
+import org.openremote.model.asset.agent.ConnectionStatus
+import org.openremote.test.ManagerContainerTrait
+import spock.lang.Specification
+import spock.util.concurrent.PollingConditions
+
+import java.util.function.Consumer
+
+/**
+ * This tests the {@link AbstractUdpClient} by creating a simple echo server that the client communicates with
+ */
+class UdpClientTest extends Specification implements ManagerContainerTrait {
+
+ def "Check client"() {
+
+ given: "expected conditions"
+ def conditions = new PollingConditions(timeout: 10, delay: 1)
+
+ and: "the container is started"
+ def serverPort = findEphemeralPort()
+ def clientPort = findEphemeralPort()
+ def container = startContainer(defaultConfig(serverPort), Collections.singletonList(new ManagerExecutorService()))
+ def protocolExecutorService = container.getService(ManagerExecutorService.class)
+
+ and: "a simple UDP echo server"
+ def echoServerPort = findEphemeralPort()
+ def echoServer = new UdpStringServer(protocolExecutorService, new InetSocketAddress(echoServerPort), ";", Integer.MAX_VALUE, true)
+ echoServer.addMessageConsumer({
+ message, channel, sender -> echoServer.sendMessage(message, sender)
+ })
+
+ and: "we add callback consumers on the server"
+ def serverConnectionStatus = echoServer.connectionStatus
+ echoServer.addConnectionStatusConsumer((Consumer<ConnectionStatus>) {
+ status -> serverConnectionStatus = status
+ })
+
+ and: "a simple UDP broadcast client"
+ def client = new AbstractUdpClient<String>(
+ "255.255.255.255",
+ echoServerPort,
+ clientPort,
+ protocolExecutorService) {
+
+ @Override
+ protected void decode(ByteBuf buf, List<String> messages) {
+ 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) {
+ buf.writeBytes(message.getBytes(CharsetUtil.UTF_8))
+ }
+ }
+
+ and: "we add callback consumers to the client"
+ def connectionStatus = client.getConnectionStatus()
+ String lastMessage
+ client.addMessageConsumer({
+ message -> lastMessage = message
+ })
+ client.addConnectionStatusConsumer({
+ status -> connectionStatus = status
+ })
+
+ when: "the server is started"
+ echoServer.start()
+
+ then: "the server should be running"
+ conditions.eventually {
+ assert echoServer.connectionStatus == ConnectionStatus.CONNECTED
+ assert serverConnectionStatus == ConnectionStatus.CONNECTED
+ }
+
+ when: "we call connect on the client"
+ client.connect()
+
+ then: "the client status should become CONNECTED"
+ conditions.eventually {
+ assert client.connectionStatus == ConnectionStatus.CONNECTED
+ assert connectionStatus == ConnectionStatus.CONNECTED
+ }
+
+ when: "the server sends a broadcast message"
+ echoServer.sendMessage("Hello world", SocketUtils.socketAddress("255.255.255.255", clientPort))
+
+ then: "we should receive the message"
+ conditions.eventually {
+ assert lastMessage == "Hello world"
+ }
+
+ when: "we send a message to the server"
+ client.sendMessage("Test;")
+
+ then: "we should get the same message back"
+ conditions.eventually {
+ assert lastMessage == "Test"
+ }
+
+ when: "we request the client to disconnect"
+ client.disconnect()
+
+ then: "the client should become DISCONNECTED"
+ conditions.eventually {
+ assert client.connectionStatus == ConnectionStatus.DISCONNECTED
+ assert connectionStatus == ConnectionStatus.DISCONNECTED
+ }
+
+ when: "we reconnect the same client"
+ client.connect()
+
+ then: "the client status should become CONNECTED"
+ conditions.eventually {
+ assert client.connectionStatus == ConnectionStatus.CONNECTED
+ assert connectionStatus == ConnectionStatus.CONNECTED
+ }
+
+ when: "the server sends a broadcast message"
+ echoServer.sendMessage("Is there anyone there?", SocketUtils.socketAddress("255.255.255.255", clientPort))
+
+ then: "we should receive the message"
+ conditions.eventually {
+ assert lastMessage == "Is there anyone there?"
+ }
+
+ when: "we send a message to the server"
+ client.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"
+ client.disconnect()
+
+ then: "the client should become DISCONNECTED"
+ conditions.eventually {
+ assert client.connectionStatus == ConnectionStatus.DISCONNECTED
+ assert connectionStatus == ConnectionStatus.DISCONNECTED
+ }
+
+ cleanup: "the server should be stopped"
+ client.disconnect()
+ echoServer.stop()
+ stopContainer(container)
+ }
+}
diff --git a/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy
index c31222ea4..dee4a44b0 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy
@@ -274,8 +274,9 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
given: "expected conditions"
def conditions = new PollingConditions(timeout: 10, initialDelay: 1)
- and: "the HTTP client protocol polling time units are set to milliseconds"
- HttpClientProtocol.POLLING_TIME_UNIT = TimeUnit.MILLISECONDS
+ and: "the HTTP client protocol min times are adjusted for testing"
+ HttpClientProtocol.MIN_POLLING_MILLIS = 10
+ HttpClientProtocol.MIN_PING_MILLIS = 10
when: "the container starts"
def serverPort = findEphemeralPort()
@@ -327,7 +328,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
Values.create("pingGet")
),
new MetaItem(
- HttpClientProtocol.META_PROTOCOL_PING_SECONDS,
+ HttpClientProtocol.META_PROTOCOL_PING_MILLIS,
Values.create(100) // Note for testing time unit is set to milliseconds
),
new MetaItem(
@@ -406,7 +407,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
Values.create("pingPost")
),
new MetaItem(
- HttpClientProtocol.META_PROTOCOL_PING_SECONDS,
+ HttpClientProtocol.META_PROTOCOL_PING_MILLIS,
Values.create(100) // Note for testing time unit is set to milliseconds
),
new MetaItem(
@@ -468,7 +469,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create("put_request_with_headers")),
new MetaItem(HttpClientProtocol.META_ATTRIBUTE_METHOD, Values.create(HttpMethod.PUT)),
new MetaItem(
- HttpClientProtocol.META_ATTRIBUTE_BODY,
+ Protocol.META_ATTRIBUTE_WRITE_VALUE,
Values.<ObjectValue>parse('{"prop1": "{$value}", "prop2": "prop2Value"}').get()
),
new MetaItem(
@@ -491,9 +492,9 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
.addMeta(
new MetaItem(MetaItemType.AGENT_LINK, new AttributeRef(agent.id, "protocolConfig").toArrayValue()),
new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create("get_poll_slow")),
- new MetaItem(HttpClientProtocol.META_ATTRIBUTE_POLLING_SECONDS, Values.create(50)), // This is ms in testing
+ new MetaItem(HttpClientProtocol.META_POLLING_MILLIS, Values.create(50)), // This is ms in testing
new MetaItem(
- Protocol.META_PROTOCOL_FILTERS,
+ Protocol.META_ATTRIBUTE_FILTERS,
Values.createArray().add(new RegexFilter("\\d+", 0, 0).toValue().get())
)
),
@@ -502,9 +503,9 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
.addMeta(
new MetaItem(MetaItemType.AGENT_LINK, new AttributeRef(agent.id, "protocolConfig").toArrayValue()),
new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create("get_poll_fast")),
- new MetaItem(HttpClientProtocol.META_ATTRIBUTE_POLLING_SECONDS, Values.create(40)), // This is ms in testing
+ new MetaItem(HttpClientProtocol.META_POLLING_MILLIS, Values.create(40)), // This is ms in testing
new MetaItem(
- Protocol.META_PROTOCOL_FILTERS,
+ Protocol.META_ATTRIBUTE_FILTERS,
Values.createArray().add(new RegexFilter("\\d+", 0, 1).toValue().get())
)
)
@@ -639,7 +640,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
.addMeta(
new MetaItem(MetaItemType.AGENT_LINK, new AttributeRef(agent.id, "protocolConfig3").toArrayValue()),
new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create("get_failure_401")),
- new MetaItem(HttpClientProtocol.META_ATTRIBUTE_POLLING_SECONDS, Values.create(50)), // This is ms in testing
+ new MetaItem(HttpClientProtocol.META_POLLING_MILLIS, Values.create(50)), // This is ms in testing
),
new AssetAttribute("getSuccess2", AttributeValueType.STRING)
.addMeta(
diff --git a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusBasicTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusBasicTest.groovy
index e9111f81a..d2b13ed00 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusBasicTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusBasicTest.groovy
@@ -28,7 +28,7 @@ import org.openremote.manager.concurrent.ManagerExecutorService
import org.openremote.model.value.ValueType
import org.openremote.model.value.Values
import org.openremote.test.ManagerContainerTrait
-import org.openremote.test.MockMessageProcessor
+import org.openremote.test.MockVelbusClient
import spock.lang.Shared
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
@@ -44,12 +44,12 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
def static VelbusNetwork network
@Shared
- def static MockMessageProcessor messageProcessor = new MockMessageProcessor()
+ def static MockVelbusClient messageProcessor = new MockVelbusClient()
@Shared
def static PollingConditions conditions = new PollingConditions(timeout: 10)
- static loadDevicePackets(MockMessageProcessor messageProcessor) {
+ static loadDevicePackets(MockVelbusClient messageProcessor) {
messageProcessor.mockPackets = [
/*
@@ -811,9 +811,9 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
VelbusNetwork.DELAY_BETWEEN_PACKET_WRITES_MILLISECONDS = 1; // Minimal delay for simulated network
// Uncomment and configure the below lines to communicate with an actual VELBUS network
-// def messageProcessor = new VelbusSocketMessageProcessor("192.168.0.65", 6000, protocolExecutorService);
+// def client = new VelbusSocketMessageProcessor("192.168.0.65", 6000, protocolExecutorService);
// VelbusNetwork.DELAY_BETWEEN_PACKET_WRITES_MILLISECONDS = 100;
-// def messageProcessor = new VelbusSerialMessageProcessor("COM6", 38400, protocolExecutorService);
+// def client = new VelbusSerialMessageProcessor("COM6", 38400, protocolExecutorService);
// VelbusNetwork.DELAY_BETWEEN_PACKET_WRITES_MILLISECONDS = 100;
network = new VelbusNetwork(messageProcessor, protocolExecutorService, null)
@@ -986,7 +986,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
}
when: "a button is long pressed on the device"
- network.messageProcessor.onMessageReceived(VelbusPacket.fromString("0F F8 32 04 00 00 00 20 A3 04 00 00 00 00"))
+ network.client.onMessageReceived(VelbusPacket.fromString("0F F8 32 04 00 00 00 20 A3 04 00 00 00 00"))
then: "the property value should change to LONG_PRESSED"
conditions.eventually {
@@ -995,7 +995,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
}
when: "the button is released on the device"
- network.messageProcessor.onMessageReceived(VelbusPacket.fromString("0F F8 32 04 00 00 20 00 A3 04 00 00 00 00"))
+ network.client.onMessageReceived(VelbusPacket.fromString("0F F8 32 04 00 00 20 00 A3 04 00 00 00 00"))
then: "the property value should return to RELEASED"
conditions.eventually {
@@ -1004,7 +1004,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
}
when: "a button is pressed on the device"
- network.messageProcessor.onMessageReceived(VelbusPacket.fromString("0F F8 32 04 00 20 00 00 A3 04 00 00 00 00"))
+ network.client.onMessageReceived(VelbusPacket.fromString("0F F8 32 04 00 20 00 00 A3 04 00 00 00 00"))
then: "the property value should change to PRESSED"
conditions.eventually {
@@ -1013,7 +1013,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
}
when: "the button is released on the device"
- network.messageProcessor.onMessageReceived(VelbusPacket.fromString("0F F8 32 04 00 00 20 00 A3 04 00 00 00 00"))
+ network.client.onMessageReceived(VelbusPacket.fromString("0F F8 32 04 00 00 20 00 A3 04 00 00 00 00"))
then: "the property value should return to RELEASED"
conditions.eventually {
@@ -1034,7 +1034,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
conditions.eventually {
device.getPropertyValue("CH22").getPropertyValue() == InputProcessor.ChannelState.PRESSED
}
- if (network.messageProcessor == messageProcessor) {
+ if (network.client == messageProcessor) {
assert messageProcessor.sentMessages.size() == 1
assert messageProcessor.sentMessages[0].toString() == "0F F8 32 04 00 20 00 00 A3 04 00 00 00 00"
}
@@ -1045,7 +1045,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
then: "the button release packet should have been sent to the message processor"
conditions.eventually {
device.getPropertyValue("CH22").getPropertyValue() == InputProcessor.ChannelState.RELEASED
- if (network.messageProcessor == messageProcessor) {
+ if (network.client == messageProcessor) {
assert messageProcessor.sentMessages.size() == 2
assert messageProcessor.sentMessages[1].toString() == "0F F8 32 04 00 00 20 00 A3 04 00 00 00 00"
}
@@ -1094,7 +1094,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
then: "the LED should be on"
conditions.eventually {
device.getPropertyValue("CH1_LED").getPropertyValue() == FeatureProcessor.LedState.ON
- if (network.messageProcessor == messageProcessor) {
+ if (network.client == messageProcessor) {
assert messageProcessor.sentMessages.size() == 1
assert messageProcessor.sentMessages[0].toString() == "0F FB 30 02 F6 01 CD 04 00 00 00 00 00 00"
}
@@ -1107,7 +1107,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
then: "the LED should be on slow"
conditions.eventually {
device.getPropertyValue("CH1_LED").getPropertyValue() == FeatureProcessor.LedState.SLOW
- if (network.messageProcessor == messageProcessor) {
+ if (network.client == messageProcessor) {
assert messageProcessor.sentMessages.size() == 1
assert messageProcessor.sentMessages[0].toString() == "0F FB 30 02 F7 01 CC 04 00 00 00 00 00 00"
}
@@ -1120,7 +1120,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
then: "the LED should be on fast"
conditions.eventually {
device.getPropertyValue("CH1_LED").getPropertyValue() == FeatureProcessor.LedState.FAST
- if (network.messageProcessor == messageProcessor) {
+ if (network.client == messageProcessor) {
assert messageProcessor.sentMessages.size() == 1
assert messageProcessor.sentMessages[0].toString() == "0F FB 30 02 F8 01 CB 04 00 00 00 00 00 00"
}
@@ -1133,7 +1133,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
then: "the LED should be on very fast"
conditions.eventually {
device.getPropertyValue("CH1_LED").getPropertyValue() == FeatureProcessor.LedState.VERYFAST
- if (network.messageProcessor == messageProcessor) {
+ if (network.client == messageProcessor) {
assert messageProcessor.sentMessages.size() == 1
assert messageProcessor.sentMessages[0].toString() == "0F FB 30 02 F9 01 CA 04 00 00 00 00 00 00"
}
@@ -1146,7 +1146,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
then: "the LED should be off"
conditions.eventually {
device.getPropertyValue("CH1_LED").getPropertyValue() == FeatureProcessor.LedState.OFF
- if (network.messageProcessor == messageProcessor) {
+ if (network.client == messageProcessor) {
assert messageProcessor.sentMessages.size() == 1
assert messageProcessor.sentMessages[0].toString() == "0F FB 30 02 F5 01 CE 04 00 00 00 00 00 00"
}
@@ -1190,7 +1190,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
}
when: "a button is long pressed on the device"
- network.messageProcessor.onMessageReceived(VelbusPacket.fromString("0F F8 0A 04 00 00 00 02 E9 04"))
+ network.client.onMessageReceived(VelbusPacket.fromString("0F F8 0A 04 00 00 00 02 E9 04"))
then: "the property value should change to LONG_PRESSED"
conditions.eventually {
@@ -1198,7 +1198,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
}
when: "the button is released on the device"
- network.messageProcessor.onMessageReceived(VelbusPacket.fromString("0F F8 0A 04 00 00 02 00 E9 04"))
+ network.client.onMessageReceived(VelbusPacket.fromString("0F F8 0A 04 00 00 02 00 E9 04"))
then: "the property value should return to RELEASED"
conditions.eventually {
@@ -1206,7 +1206,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
}
when: "a button is pressed on the device"
- network.messageProcessor.onMessageReceived(VelbusPacket.fromString("0F F8 0A 04 00 02 00 00 E9 04"))
+ network.client.onMessageReceived(VelbusPacket.fromString("0F F8 0A 04 00 02 00 00 E9 04"))
then: "the property value should change to PRESSED"
conditions.eventually {
@@ -1214,7 +1214,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
}
when: "the button is released on the device"
- network.messageProcessor.onMessageReceived(VelbusPacket.fromString("0F F8 0A 04 00 00 02 00 E9 04"))
+ network.client.onMessageReceived(VelbusPacket.fromString("0F F8 0A 04 00 00 02 00 E9 04"))
then: "the property value should return to RELEASED"
conditions.eventually {
@@ -1233,7 +1233,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
then: "the button press packet should have been sent to the message processor"
conditions.eventually {
device.getPropertyValue("CH3").getPropertyValue() == InputProcessor.ChannelState.PRESSED
- if (network.messageProcessor == messageProcessor) {
+ if (network.client == messageProcessor) {
assert messageProcessor.sentMessages.size() == 1
assert messageProcessor.sentMessages[0].toString() == "0F F8 0A 04 00 04 00 00 E7 04 00 00 00 00"
}
@@ -1245,7 +1245,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
then: "the button release packet should have been sent to the message processor"
conditions.eventually {
device.getPropertyValue("CH3").getPropertyValue() == InputProcessor.ChannelState.RELEASED
- if (network.messageProcessor == messageProcessor) {
+ if (network.client == messageProcessor) {
assert messageProcessor.sentMessages.size() == 2
assert messageProcessor.sentMessages[1].toString() == "0F F8 0A 04 00 00 04 00 E7 04 00 00 00 00"
}
@@ -1353,7 +1353,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
}
when: "we receive a temperature sensor value"
- network.messageProcessor.onMessageReceived(VelbusPacket.fromString("0F FB 30 07 E6 3F 60 30 A0 3F 80 AB 04"))
+ network.client.onMessageReceived(VelbusPacket.fromString("0F FB 30 07 E6 3F 60 30 A0 3F 80 AB 04"))
then: "the temperature value should be resolved to 0.1 degrees"
assert device.getPropertyValue("TEMP_CURRENT").getPropertyValue() == 31.7d
@@ -1693,7 +1693,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
device.writeProperty("MEMO_TEXT", Values.create(msg))
then: "the memo text property should contain the text and the correct packets should have been sent to the device"
- if (network.messageProcessor == messageProcessor) {
+ if (network.client == messageProcessor) {
conditions.eventually {
assert device.getPropertyValue("MEMO_TEXT").getPropertyValue() == msg.substring(0, 62)
assert messageProcessor.sentMessages.size() == 13
@@ -2036,7 +2036,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
}
when: "the counter updates on the device"
- network.messageProcessor.onMessageReceived(VelbusPacket.fromString("0F FB 0A 08 BE 68 00 00 00 71 23 46 E4 04"))
+ network.client.onMessageReceived(VelbusPacket.fromString("0F FB 0A 08 BE 68 00 00 00 71 23 46 E4 04"))
then: "the counter should update to match"
conditions.eventually {
@@ -2300,7 +2300,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {
}
then: "the dimmer should switch off again"
- if (network.messageProcessor == messageProcessor) {
+ if (network.client == messageProcessor) {
messageProcessor.onMessageReceived(VelbusPacket.fromString("0F F8 BB 04 00 00 02 00 38 04 00 00 00 00"))
messageProcessor.onMessageReceived(VelbusPacket.fromString("0F FB BB 08 B8 02 00 00 00 00 00 00 79 04"))
}
diff --git a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
index 510d461a2..198d78cdb 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
@@ -1,7 +1,7 @@
package org.openremote.test.protocol.velbus
import org.apache.commons.io.IOUtils
-import org.openremote.agent.protocol.MessageProcessor
+import org.openremote.agent.protocol.io.IoClient
import org.openremote.agent.protocol.velbus.AbstractVelbusProtocol
import org.openremote.agent.protocol.velbus.VelbusConfiguration
import org.openremote.agent.protocol.velbus.VelbusPacket
@@ -22,7 +22,7 @@ import org.openremote.model.file.FileInfo
import org.openremote.model.util.TextUtil
import org.openremote.model.value.Values
import org.openremote.test.ManagerContainerTrait
-import org.openremote.test.MockMessageProcessor
+import org.openremote.test.MockVelbusClient
import spock.lang.Shared
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
@@ -36,13 +36,13 @@ import static org.openremote.model.asset.agent.ProtocolConfiguration.initProtoco
class VelbusProtocolTest extends Specification implements ManagerContainerTrait {
@Shared
- static MockMessageProcessor messageProcessor = new MockMessageProcessor()
+ static MockVelbusClient messageProcessor = new MockVelbusClient()
@Shared
static AbstractVelbusProtocol velbusProtocol = new AbstractVelbusProtocol() {
@Override
- protected MessageProcessor<VelbusPacket> createMessageProcessor(AssetAttribute protocolConfiguration) throws RuntimeException {
+ protected IoClient<VelbusPacket> createClient(AssetAttribute protocolConfiguration) throws RuntimeException {
return messageProcessor
}