Skip to content

armgit / core

Public Imported from GitHub
0

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

Use calimero emulation server to test link/unlink of KNX protocol which connects to emulated KNX gateway

Marcus Redekerf3a1ee959187
diff --git a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXConnection.java b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXConnection.java
index 15352f4a5..c2306a480 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXConnection.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXConnection.java
@@ -1,9 +1,160 @@
package org.openremote.agent.protocol.knx;
-public class KNXConnection {
+import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ScheduledFuture;
+import java.util.function.Consumer;
+import java.util.logging.Level;
+import java.util.logging.Logger;
- public KNXConnection() {
- // TODO
+import org.openremote.agent.protocol.ConnectionStatus;
+import org.openremote.agent.protocol.ProtocolExecutorService;
+
+import tuwien.auto.calimero.CloseEvent;
+import tuwien.auto.calimero.FrameEvent;
+import tuwien.auto.calimero.KNXException;
+import tuwien.auto.calimero.link.KNXNetworkLink;
+import tuwien.auto.calimero.link.KNXNetworkLinkIP;
+import tuwien.auto.calimero.link.NetworkLinkListener;
+import tuwien.auto.calimero.link.medium.TPSettings;
+import tuwien.auto.calimero.process.ProcessCommunicator;
+import tuwien.auto.calimero.process.ProcessCommunicatorImpl;
+
+public class KNXConnection implements NetworkLinkListener {
+
+ protected ConnectionStatus connectionStatus = ConnectionStatus.DISCONNECTED;
+
+ 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 ScheduledFuture<?> reconnectTask;
+ protected int reconnectDelayMilliseconds = INITIAL_RECONNECT_DELAY_MILLIS;
+
+ protected final List<Consumer<ConnectionStatus>> connectionStatusConsumers = new ArrayList<>();
+
+ protected final String gatewayIp;
+ protected final ProtocolExecutorService executorService;
+ protected final int port = 3671;
+ protected KNXNetworkLink knxLink;
+
+ private static final Logger LOG = Logger.getLogger(KNXConnection.class.getName());
+
+ public KNXConnection(String gatewayIp, ProtocolExecutorService executorService) {
+ this.gatewayIp = gatewayIp;
+ this.executorService = executorService;
+ }
+
+ public synchronized void connect() {
+ if (connectionStatus != ConnectionStatus.DISCONNECTED && connectionStatus != ConnectionStatus.WAITING) {
+ LOG.finest("Must be disconnected before calling connect");
+ return;
+ }
+
+ LOG.fine("Connecting");
+ onConnectionStatusChanged(ConnectionStatus.CONNECTING);
+
+
+ final InetSocketAddress remote = new InetSocketAddress(gatewayIp, port);
+ try {
+ knxLink = KNXNetworkLinkIP.newTunnelingLink(null, remote, false, TPSettings.TP1);
+// ProcessCommunicator pc = new ProcessCommunicatorImpl(knxLink);
+ knxLink.addLinkListener(this);
+
+ //TODO start listening to group notifications using a process listener
+ //pc.addProcessListener(this);
+
+ if (knxLink.isOpen()) {
+ LOG.fine("Successfully connected to: " + gatewayIp + ":" + port);
+ reconnectTask = null;
+ reconnectDelayMilliseconds = INITIAL_RECONNECT_DELAY_MILLIS;
+ onConnectionStatusChanged(ConnectionStatus.CONNECTED);
+ } else {
+ LOG.log(Level.INFO, "Connection error");
+ // Failed to connect so schedule reconnection attempt
+ scheduleReconnect();
+ }
+ }
+ catch (final KNXException | InterruptedException | RuntimeException e) {
+ LOG.log(Level.INFO, "Connection error", e.getMessage());
+ scheduleReconnect();
+ }
+ }
+
+ public synchronized void disconnect() {
+ if (connectionStatus == ConnectionStatus.DISCONNECTING || connectionStatus == ConnectionStatus.DISCONNECTED) {
+ LOG.finest("Already disconnecting or disconnected");
+ return;
+ }
+
+ LOG.finest("Disconnecting");
+ onConnectionStatusChanged(ConnectionStatus.DISCONNECTING);
+ knxLink.removeLinkListener(this);
+ knxLink.close();
+ knxLink = null;
+ onConnectionStatusChanged(ConnectionStatus.DISCONNECTED);
+ }
+
+ public synchronized void addConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {
+ if (!connectionStatusConsumers.contains(connectionStatusConsumer)) {
+ connectionStatusConsumers.add(connectionStatusConsumer);
+ }
+ }
+
+ public synchronized void removeConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {
+ connectionStatusConsumers.remove(connectionStatusConsumer);
+ }
+
+ protected void onConnectionStatusChanged(ConnectionStatus connectionStatus) {
+ this.connectionStatus = connectionStatus;
+
+ synchronized (connectionStatusConsumers) {
+ connectionStatusConsumers.forEach(
+ consumer -> consumer.accept(connectionStatus)
+ );
+ }
+ }
+
+
+ @Override
+ public void indication(FrameEvent e) {
+ }
+
+ @Override
+ public void linkClosed(CloseEvent e) {
+ onConnectionStatusChanged(ConnectionStatus.CLOSED);
+ knxLink.removeLinkListener(this);
+ knxLink.close();
+ knxLink = null;
+ scheduleReconnect();
}
+ @Override
+ public void confirmation(FrameEvent e) {
+ }
+
+ protected synchronized void scheduleReconnect() {
+ if (reconnectTask != null) {
+ return;
+ }
+
+ onConnectionStatusChanged(ConnectionStatus.WAITING);
+
+ if (reconnectDelayMilliseconds < MAX_RECONNECT_DELAY_MILLIS) {
+ reconnectDelayMilliseconds *= RECONNECT_BACKOFF_MULTIPLIER;
+ reconnectDelayMilliseconds = Math.min(MAX_RECONNECT_DELAY_MILLIS, reconnectDelayMilliseconds);
+ }
+
+ LOG.finest("Scheduling reconnection in '" + reconnectDelayMilliseconds + "' milliseconds");
+
+ reconnectTask = executorService.schedule(() -> {
+ synchronized (KNXConnection.this) {
+ reconnectTask = null;
+ // Attempt to reconnect if not disconnecting
+ if (connectionStatus != ConnectionStatus.DISCONNECTING && connectionStatus != ConnectionStatus.DISCONNECTED) {
+ connect();
+ }
+ }
+ }, reconnectDelayMilliseconds);
+ }
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java
index 90acddcfa..b3806a45b 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java
@@ -2,7 +2,10 @@ package org.openremote.agent.protocol.knx;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
+import java.util.HashMap;
+import java.util.Map;
import java.util.Optional;
+import java.util.function.Consumer;
import java.util.logging.Logger;
import org.openremote.agent.protocol.AbstractProtocol;
@@ -10,17 +13,18 @@ import org.openremote.agent.protocol.ConnectionStatus;
import org.openremote.model.AbstractValueHolder;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.attribute.AttributeEvent;
-import org.openremote.model.attribute.AttributeState;
+import org.openremote.model.attribute.AttributeRef;
public class KNXProtocol extends AbstractProtocol {
private static final Logger LOG = Logger.getLogger(KNXProtocol.class.getName());
-
public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":knx";
public static final String KNX_GATEWAY_IP = PROTOCOL_NAME + ":gatewayIp";
+
+ final protected Map<String, KNXConnection> knxConnections = new HashMap<>();
+ final protected Map<AttributeRef, Consumer<ConnectionStatus>> statusConsumerMap = new HashMap<>();
-
@Override
public String getProtocolName() {
return PROTOCOL_NAME;
@@ -28,8 +32,8 @@ public class KNXProtocol extends AbstractProtocol {
@Override
protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
- Optional<String> gatewayIp = protocolConfiguration.getMetaItem(KNX_GATEWAY_IP).flatMap(AbstractValueHolder::getValueAsString);
- if (!gatewayIp.isPresent()) {
+ Optional<String> gatewayIpParam = protocolConfiguration.getMetaItem(KNX_GATEWAY_IP).flatMap(AbstractValueHolder::getValueAsString);
+ if (!gatewayIpParam.isPresent()) {
LOG.severe("No KNX gateway IP address provided for protocol configuration: " + protocolConfiguration);
updateStatus(protocolConfiguration.getReferenceOrThrow(), ConnectionStatus.ERROR);
return;
@@ -39,15 +43,46 @@ public class KNXProtocol extends AbstractProtocol {
updateStatus(protocolConfiguration.getReferenceOrThrow(), ConnectionStatus.DISABLED);
return;
}
-
- updateStatus(protocolConfiguration.getReferenceOrThrow(), ConnectionStatus.CONNECTED);
- //TODO Create KNXConnection for given IP and config. KNXConnection will be main class for KNX communication and will be the listener for bus events
+
+ AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();
+
+ synchronized (knxConnections) {
+ Consumer<ConnectionStatus> statusConsumer = status -> {
+ updateStatus(protocolRef, status);
+ };
+
+ KNXConnection knxConnection = knxConnections.computeIfAbsent(
+ gatewayIpParam.get(), gatewayIp ->
+ new KNXConnection(gatewayIp, executorService)
+ );
+ knxConnection.addConnectionStatusConsumer(statusConsumer);
+ knxConnection.connect();
+
+ synchronized (statusConsumerMap) {
+ statusConsumerMap.put(protocolRef, statusConsumer);
+ }
+ }
}
@Override
protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
- // TODO retrieve related KNX connection and close link to KNX bus
+ Consumer<ConnectionStatus> statusConsumer;
+ synchronized (statusConsumerMap) {
+ statusConsumer = statusConsumerMap.get(protocolConfiguration.getReferenceOrThrow());
+ }
+
+ String gatewayIp = protocolConfiguration.getMetaItem(KNX_GATEWAY_IP).flatMap(AbstractValueHolder::getValueAsString).orElse("");
+ synchronized (knxConnections) {
+ KNXConnection knxConnection = knxConnections.get(gatewayIp);
+ if (knxConnection != null) {
+ knxConnection.removeConnectionStatusConsumer(statusConsumer);
+
+ //TODO check if KNXConnection is still used
+ knxConnections.remove(gatewayIp);
+ knxConnection.disconnect();
+ }
+ }
}
@Override
@@ -70,7 +105,11 @@ public class KNXProtocol extends AbstractProtocol {
}
-
+ protected KNXConnection getConnection(String gatewayIp) {
+ synchronized (knxConnections) {
+ return knxConnections.get(gatewayIp);
+ }
+ }
//TODO call updateLinkedAttribute(AttributeState state, long timestamp) when receiving event from KNX bus
}
diff --git a/gradle.properties b/gradle.properties
index 46d1b399a..db5698422 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -29,6 +29,6 @@ tyrusVersion = 1.10
sunriseSunsetCalculatorVersion = 1.2
droolsVersion = 6.5.0.Final
quartzVersion= 2.2.3
-calimeroVersion = 2.3
+calimeroVersion = 2.4-SNAPSHOT
clingVersion = 2.1.1
uuidGeneratorVersion = 3.1.3
\ No newline at end of file
diff --git a/manager/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy b/manager/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy
index ee35b01c0..f0f0237ad 100644
--- a/manager/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy
@@ -19,6 +19,7 @@
*/
package org.openremote.test.protocol
+import org.apache.camel.language.simple.ast.BlockStart
import org.openremote.agent.protocol.AbstractProtocol
import org.openremote.agent.protocol.knx.KNXProtocol
import org.openremote.agent.protocol.ConnectionStatus
@@ -36,6 +37,7 @@ import org.openremote.model.value.Values
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
+import tuwien.auto.calimero.server.Launcher
/**
* This tests the KNX protocol and protocol implementation.
@@ -45,17 +47,20 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {
def "Check KNX protocol"() {
given: "expected conditions"
- def conditions = new PollingConditions(timeout: 10, delay: 1)
+ def conditions = new PollingConditions(timeout: 1, delay: 1)
+ and: "the KNX emulation server is started"
+ def knxEmulationServer = new Launcher("manager/test/src/test/resources/knx-server-config.xml")
+ def knxServerThread = new Thread(knxEmulationServer);
+ knxServerThread.start();
+
and: "the container is started"
def serverPort = findEphemeralPort()
- def container = startContainerNoDemoAssets(defaultConfig(serverPort), defaultServices())
+ def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())
def assetStorageService = container.getService(AssetStorageService.class)
def agentService = container.getService(AgentService.class)
def assetProcessingService = container.getService(AssetProcessingService.class)
- and: "the KNX emulation server is started"
- //TODO
when: "a KNX agent that uses the KNX protocol is created with a valid protocol configuration"
def knxAgent = new ServerAsset()
@@ -75,13 +80,24 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {
conditions.eventually {
assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfig").get().getReferenceOrThrow()) == ConnectionStatus.CONNECTED
}
-
conditions.eventually {
assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfigError").get().getReferenceOrThrow()) == ConnectionStatus.ERROR
}
-
+ when: "the connection to the KNX IP gateway is lost"
+ knxEmulationServer.quit()
+
+ then: "the protocol status should switch to closed, waiting, connecting, connected"
+ conditions.eventually {
+ assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfig").get().getReferenceOrThrow()) == ConnectionStatus.WAITING
+ }
+ conditions.eventually {
+ assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfig").get().getReferenceOrThrow()) == ConnectionStatus.CONNECTED
+ }
+
cleanup: "the server should be stopped"
stopContainer(container)
+
+
}
}
\ No newline at end of file
diff --git a/manager/test/src/test/resources/knx-server-config.xml b/manager/test/src/test/resources/knx-server-config.xml
index 7aad42827..62731cd86 100644
--- a/manager/test/src/test/resources/knx-server-config.xml
+++ b/manager/test/src/test/resources/knx-server-config.xml
@@ -6,11 +6,8 @@
<discovery listenNetIf="all" outgoingNetIf="all" activate="true" />
<!-- Provides the KNXnet/IP-side configuration for access to one KNX subnet -->
- <serviceContainer activate="true" routing="false" networkMonitoring="true"
- udpPort="3671" listenNetIf="any" reuseCtrlEP="false">
+ <serviceContainer activate="true" routing="false" networkMonitoring="true" udpPort="3671" listenNetIf="any" reuseCtrlEP="false">
<knxAddress type="individual">1.1.1</knxAddress>
- <disruptionBuffer expirationTimeout="30" udpPort="5555-5559" />
-
<knxSubnet type="emulate">1.1.1</knxSubnet>
<!-- KNX group address filter applied for this service container (optional) -->