100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
KNXProtocol updates to fix #47
Rich Turner1243fa9cc7c2
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.javaindex e2570db1c..27de77b1e 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,33 +1,12 @@package org.openremote.agent.protocol.knx;-import java.net.InetAddress;-import java.net.InetSocketAddress;-import java.net.UnknownHostException;-import java.util.ArrayList;-import java.util.HashMap;-import java.util.List;-import java.util.Map;-import java.util.Optional;-import java.util.concurrent.ScheduledFuture;-import java.util.function.Consumer;-import java.util.logging.Level;-import java.util.logging.Logger;-import org.apache.commons.lang3.StringUtils;-import org.openremote.model.asset.agent.ConnectionStatus;import org.openremote.agent.protocol.ProtocolExecutorService;+import org.openremote.model.asset.agent.ConnectionStatus;+import org.openremote.model.util.Pair;import org.openremote.model.value.Value;--import tuwien.auto.calimero.CloseEvent;-import tuwien.auto.calimero.DataUnitBuilder;-import tuwien.auto.calimero.DetachEvent;-import tuwien.auto.calimero.FrameEvent;-import tuwien.auto.calimero.IndividualAddress;-import tuwien.auto.calimero.KNXAckTimeoutException;-import tuwien.auto.calimero.KNXException;+import tuwien.auto.calimero.*;import tuwien.auto.calimero.datapoint.Datapoint;-import tuwien.auto.calimero.datapoint.DatapointMap;-import tuwien.auto.calimero.datapoint.DatapointModel;import tuwien.auto.calimero.datapoint.StateDP;import tuwien.auto.calimero.dptxlator.DPTXlator;import tuwien.auto.calimero.link.KNXNetworkLink;@@ -39,6 +18,15 @@ import tuwien.auto.calimero.process.ProcessCommunicatorImpl;import tuwien.auto.calimero.process.ProcessEvent;import tuwien.auto.calimero.process.ProcessListener;+import java.net.InetAddress;+import java.net.InetSocketAddress;+import java.net.UnknownHostException;+import java.util.*;+import java.util.concurrent.ScheduledFuture;+import java.util.function.Consumer;+import java.util.logging.Level;+import java.util.logging.Logger;+public class KNXConnection implements NetworkLinkListener, ProcessListener {protected ConnectionStatus connectionStatus = ConnectionStatus.DISCONNECTED;@@ -56,8 +44,8 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {protected final String connectionType;protected KNXNetworkLink knxLink;protected ProcessCommunicator processCommunicator;- protected DatapointModel<StateDP> datapoints = new DatapointMap<>();- protected Map<StateDP, List<Consumer<Value>>> datapointValueConsumers = new HashMap<>();+ protected final Map<GroupAddress, byte[]> groupAddressStateMap = new HashMap<>();+ protected final Map<GroupAddress, List<Pair<StateDP, Consumer<Value>>>> groupAddressConsumerMap = new HashMap<>();protected final String gatewayIp;@@ -76,8 +64,8 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {this.executorService = executorService;this.connectionType = connectionType;this.localIp = localIp;- this.remotePort = remotePort.intValue();- this.useNat = useNat.booleanValue();+ this.remotePort = remotePort;+ this.useNat = useNat;this.localKNXAddress = localKNXAddress;}@@ -90,7 +78,7 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {LOG.fine("Connecting");onConnectionStatusChanged(ConnectionStatus.CONNECTING);- InetSocketAddress localEndPoint = null;+ InetSocketAddress localEndPoint;InetSocketAddress remoteEndPoint = new InetSocketAddress(this.gatewayIp, this.remotePort);try {TPSettings tpSettings = new TPSettings(new IndividualAddress(this.localKNXAddress));@@ -115,6 +103,19 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {reconnectTask = null;reconnectDelayMilliseconds = INITIAL_RECONNECT_DELAY_MILLIS;onConnectionStatusChanged(ConnectionStatus.CONNECTED);++ // Get the values of all registered group addresses+ LOG.fine("Initialising group address values");+ synchronized (groupAddressConsumerMap) {+ groupAddressConsumerMap.forEach((groupAddress, datapointConsumerList) -> {+ if (!datapointConsumerList.isEmpty()) {+ // Take first data point for the group address and request the value+ Pair<StateDP, Consumer<Value>> datapointConsumer = datapointConsumerList.get(0);+ getGroupAddressValue(datapointConsumer.key.getMainAddress(), datapointConsumer.key.getPriority());+ }+ });+ }+} else {LOG.log(Level.INFO, "Connection error");// Failed to connect so schedule reconnection attempt@@ -159,14 +160,12 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {connectionStatusConsumers.remove(connectionStatusConsumer);}- protected void onConnectionStatusChanged(ConnectionStatus connectionStatus) {+ protected synchronized void onConnectionStatusChanged(ConnectionStatus connectionStatus) {this.connectionStatus = connectionStatus;- synchronized (connectionStatusConsumers) {- connectionStatusConsumers.forEach(- consumer -> consumer.accept(connectionStatus)- );- }+ connectionStatusConsumers.forEach(+ consumer -> consumer.accept(connectionStatus)+ );}public void sendCommand(Datapoint datapoint, Optional<Value> value) {@@ -177,61 +176,58 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {DPTXlator translator = TypeMapper.toDPTXlator(datapoint, val);processCommunicator.write(datapoint.getMainAddress(), translator);}- } catch (KNXAckTimeoutException acke) {- onConnectionStatusChanged(ConnectionStatus.CLOSED);- processCommunicator.detach();- knxLink.removeLinkListener(this);- knxLink.close();- knxLink = null;- scheduleReconnect();+ } catch (KNXAckTimeoutException e) {+ LOG.log(Level.INFO, "Failed to send KNX value: " + datapoint + " : " + value, e);+ onConnectionError();} catch (Exception e) {LOG.severe(e.getMessage());}}-- public void groupWrite(final ProcessEvent e) {- if (datapoints.contains(e.getDestination())) {- Datapoint datapoint = datapoints.get(e.getDestination());- try {- Value value = TypeMapper.toORValue(datapoint, e.getASDU());- for (Consumer<Value> consumer : datapointValueConsumers.get(datapoint)) {- consumer.accept(value);- }- } catch (Exception ex) {- LOG.log(Level.WARNING, "Could translate KNX event: " + e, ex);- }- }- }-- public void groupReadRequest(final ProcessEvent e) { groupWrite(e); }-- public void groupReadResponse(final ProcessEvent e) {- groupWrite(e);++ /**+ * A group address has changed on the KNX network so notify consumers+ */+ @Override+ public void groupWrite(final ProcessEvent e) {+ onGroupAddressUpdated(e.getDestination(), e.getASDU());}-- public void detached(final DetachEvent e) {}-- public void monitorStateDP(StateDP datapoint, Consumer<Value> consumer) {- this.datapoints.add(datapoint);- List<Consumer<Value>> consumers = this.datapointValueConsumers.get(datapoint);- if (consumers == null) {- consumers = new ArrayList<>();- this.datapointValueConsumers.put(datapoint, consumers);++ protected void onGroupAddressUpdated(GroupAddress groupAddress, byte[] value) {+ synchronized (groupAddressStateMap) {+ // Update the state map and notify consumers+ groupAddressStateMap.compute(groupAddress, (ga, oldValue) -> value);}- consumers.add(consumer);- try {- LOG.fine("Sending read request to KNX status datapoint '" + datapoint);- this.knxLink.sendRequest(datapoint.getMainAddress(), datapoint.getPriority(), DataUnitBuilder.createLengthOptimizedAPDU(0x00, null));- } catch (Exception e) {- LOG.log(Level.INFO, "Error sending KNX read request for META_KNX_DPT: " + datapoint, e);+ synchronized (groupAddressConsumerMap) {+ groupAddressConsumerMap.computeIfPresent(groupAddress, (ga, datapointAndConsumerList) -> {+ datapointAndConsumerList.forEach(datapointAndConsumer -> {+ StateDP datapoint = datapointAndConsumer.key;+ Consumer<Value> consumer = datapointAndConsumer.value;+ updateConsumer(value, datapoint, consumer);+ });++ return datapointAndConsumerList;+ });}}-- public void stopMonitoringStateDP(StateDP datapoint) {- this.datapoints.remove(datapoint);++ @Override+ public void groupReadRequest(final ProcessEvent e) {+ // RT: From description of super method I don't think we should update internal state in response to this but could be wrong+ //groupWrite(e);+ }++ @Override+ public void groupReadResponse(final ProcessEvent e) {+ groupWrite(e);}-++ @Override+ public void detached(final DetachEvent e) {+ LOG.log(Level.INFO, "KNX link detached", e.getSource());+ }++@Overridepublic void indication(FrameEvent e) {}@@ -239,18 +235,101 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {@Overridepublic void linkClosed(CloseEvent e) {LOG.log(Level.INFO, "KNX link closed", e.getReason());- onConnectionStatusChanged(ConnectionStatus.CLOSED);+ // RT: Is this called when deliberately disconnecting or just when an error occurs?+ onConnectionError();+ }++ @Override+ public void confirmation(FrameEvent e) {+ }++ protected void onConnectionError() {+ onConnectionStatusChanged(ConnectionStatus.ERROR);processCommunicator.detach();knxLink.removeLinkListener(this);knxLink.close();knxLink = null;++ // Clear out the group address states+ List<GroupAddress> groupAddresses = Arrays.asList(groupAddressStateMap.keySet().toArray(new GroupAddress[groupAddressStateMap.size()]));+ groupAddresses.forEach(groupAddress -> onGroupAddressUpdated(groupAddress, null));+scheduleReconnect();}- @Override- public void confirmation(FrameEvent e) {+ /**+ * Add a consumer for the specified {@link StateDP}.+ */+ public void addDatapointValueConsumer(StateDP datapoint, Consumer<Value> consumer) {+ synchronized (groupAddressConsumerMap) {+ List<Pair<StateDP, Consumer<Value>>> groupAddressConsumers = groupAddressConsumerMap+ .computeIfAbsent(datapoint.getMainAddress(), groupAddress -> new ArrayList<>());++ groupAddressConsumers.add(new Pair<>(datapoint, consumer));++ // Look for existing value for this GA+ synchronized (groupAddressStateMap) {+ groupAddressStateMap.compute(datapoint.getMainAddress(), (groupAddress, groupValue) -> {+ if (groupValue == null) {+ // State not available for this group address so request it+ getGroupAddressValue(datapoint.getMainAddress(), datapoint.getPriority());+ } else {+ updateConsumer(groupValue, datapoint, consumer);+ }++ return groupValue;+ });+ }+ }}-++ /**+ * Remove a consumer for the specified {@link StateDP}.+ * <p>+ * <b>NOTE: The {@link StateDP} must be the same instance as supplied at registration.</b>+ */+ public void removeDatapointValueConsumer(StateDP datapoint) {+ synchronized (groupAddressConsumerMap) {+ groupAddressConsumerMap.computeIfPresent(datapoint.getMainAddress(), (groupAddress, datapointConsumerList) -> {+ if (datapointConsumerList.removeIf(datapointConsumer -> datapointConsumer.key == datapoint)) {+ if (datapointConsumerList.isEmpty()) {+ datapointConsumerList = null;+ }+ }+ return datapointConsumerList;+ });+ }+ }++ protected void getGroupAddressValue(GroupAddress groupAddress, Priority priority) {+ if (knxLink == null || !knxLink.isOpen()) {+ LOG.fine("Cannot send read request not currently connected: " + groupAddress);+ return;+ }++ try {+ LOG.fine("Sending read request to KNX group address: " + groupAddress);+ this.knxLink.sendRequest(groupAddress, priority, DataUnitBuilder.createLengthOptimizedAPDU(0x00, null));+ } catch (Exception e) {+ LOG.log(Level.INFO, "Error sending KNX read request for group address: " + groupAddress, e);+ }+ }++ protected void updateConsumer(byte[] data, StateDP datapoint, Consumer<Value> consumer) {+ // Convert to OR Value and notify the consumer+ Value value = null;++ if (data != null) {+ try {+ value = TypeMapper.toORValue(datapoint, data);+ } catch (Exception ex) {+ LOG.log(Level.WARNING, "Couldn't translate Group address value to DPT type: " + datapoint, ex);+ }+ }++ consumer.accept(value);+ }+protected synchronized void scheduleReconnect() {if (reconnectTask != null) {return;@@ -275,5 +354,4 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {}}, 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.javaindex cdca9de3b..f4d93b5fa 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@@ -220,14 +220,15 @@ public class KNXProtocol extends AbstractProtocol implements ProtocolLinkedAttriString connectionType = protocolConfiguration.getMetaItem(META_KNX_IP_CONNECTION_TYPE).flatMap(AbstractValueHolder::getValueAsString).orElse("TUNNELLING");if (!connectionType.equals("TUNNELLING") && !connectionType.equals("ROUTING")) {LOG.severe("KNX connectionType can either be 'TUNNELLING' or 'ROUTING' for protocol configuration: " + protocolConfiguration);- updateStatus(protocolConfiguration.getReferenceOrThrow(), ConnectionStatus.ERROR);+ updateStatus(protocolConfiguration.getReferenceOrThrow(), ConnectionStatus.ERROR_CONFIGURATION);return;}Optional<String> gatewayIpParam = protocolConfiguration.getMetaItem(META_KNX_GATEWAY_IP).flatMap(AbstractValueHolder::getValueAsString);- if (!gatewayIpParam.isPresent() && connectionType.equals("TUNNELLING")) {- LOG.severe("No KNX gateway IP address provided for TUNNELLING mode for protocol configuration: " + protocolConfiguration);- updateStatus(protocolConfiguration.getReferenceOrThrow(), ConnectionStatus.ERROR);+ // RT: KNXConnection constructor implies gateway IP is always required so removed TUNNELLING only check here+ if (!gatewayIpParam.isPresent()) {+ LOG.severe("No KNX gateway IP address provided for protocol configuration: " + protocolConfiguration);+ updateStatus(protocolConfiguration.getReferenceOrThrow(), ConnectionStatus.ERROR_CONFIGURATION);return;}@@ -244,9 +245,7 @@ public class KNXProtocol extends AbstractProtocol implements ProtocolLinkedAttriAttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();synchronized (knxConnections) {- Consumer<ConnectionStatus> statusConsumer = status -> {- updateStatus(protocolRef, status);- };+ Consumer<ConnectionStatus> statusConsumer = status -> updateStatus(protocolRef, status);KNXConnection knxConnection = knxConnections.computeIfAbsent(gatewayIpParam.get(), gatewayIp ->@@ -396,10 +395,8 @@ public class KNXProtocol extends AbstractProtocol implements ProtocolLinkedAttrireturn;}- StateDP datapoint = new StateDP(new GroupAddress(groupAddress), attributeRef.getAttributeName());- datapoint.setDPT(0, dpt);-- knxConnection.monitorStateDP(datapoint, value -> handleKNXValueChange(attributeRef, value));+ StateDP datapoint = new StateDP(new GroupAddress(groupAddress), attributeRef.getAttributeName(), 0, dpt);+ knxConnection.addDatapointValueConsumer(datapoint, value -> handleKNXValueChange(attributeRef, value));attributeStatusMap.put(attributeRef, new Pair<>(knxConnection, datapoint));LOG.info("Attribute registered for status updates: " + attributeRef + " with datapoint: " + datapoint);@@ -415,7 +412,7 @@ public class KNXProtocol extends AbstractProtocol implements ProtocolLinkedAttrisynchronized (attributeStatusMap) {Pair<KNXConnection, StateDP> controlInfo = attributeStatusMap.remove(attributeRef);if (controlInfo != null) {- controlInfo.key.stopMonitoringStateDP(controlInfo.value);+ controlInfo.key.removeDatapointValueConsumer(controlInfo.value);}}}@@ -425,12 +422,6 @@ public class KNXProtocol extends AbstractProtocol implements ProtocolLinkedAttrireturn attributeActionMap;}-- public Map<AttributeRef, Pair<KNXConnection, StateDP>> getAttributeStatusMap() {- return attributeStatusMap;- }--protected boolean isKNXConnectionStillUsed(KNXConnection knxConnection) {boolean clientStillUsed;@@ -516,7 +507,7 @@ public class KNXProtocol extends AbstractProtocol implements ProtocolLinkedAttri}}- protected Asset createAsset(StateDP datapoint, boolean isStatusGA, MetaItem agentLink, Map<String, Asset> createdAssets) throws KNXException {+ protected void createAsset(StateDP datapoint, boolean isStatusGA, MetaItem agentLink, Map<String, Asset> createdAssets) throws KNXException {String name = datapoint.getName().substring(0, datapoint.getName().length()-3);String assetName = name.replaceAll(" -.*-", "");Asset asset;@@ -544,7 +535,6 @@ public class KNXProtocol extends AbstractProtocol implements ProtocolLinkedAttriasset.addAttributes(attr);}createdAssets.put(assetName, asset);- return asset;}}diff --git a/manager/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy b/manager/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovyindex 0e24c37a5..851377b11 100644--- a/manager/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy@@ -72,7 +72,7 @@ class KNXImportTest extends Specification implements ManagerContainerTrait {then: "the protocol configurations should be linked and their deployment status should be available in the agent service"conditions.eventually {- assert agentService.getProtocolConnectionStatus(knxAgent.getAttribute("knxConfigError1").get().getReferenceOrThrow()) == ConnectionStatus.ERROR+ assert agentService.getProtocolConnectionStatus(knxAgent.getAttribute("knxConfigError1").get().getReferenceOrThrow()) == ConnectionStatus.ERROR_CONFIGURATION}when: "an authenticated admin user"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.groovyindex 2aa0b0393..69cac6e41 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@@ -109,10 +109,10 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {assert agentService.getProtocolConnectionStatus(knxAgent.getAttribute("knxConfig").get().getReferenceOrThrow()) == ConnectionStatus.CONNECTED}conditions.eventually {- assert agentService.getProtocolConnectionStatus(knxAgent.getAttribute("knxConfigError1").get().getReferenceOrThrow()) == ConnectionStatus.ERROR+ assert agentService.getProtocolConnectionStatus(knxAgent.getAttribute("knxConfigError1").get().getReferenceOrThrow()) == ConnectionStatus.ERROR_CONFIGURATION}conditions.eventually {- assert agentService.getProtocolConnectionStatus(knxAgent.getAttribute("knxConfigError2").get().getReferenceOrThrow()) == ConnectionStatus.ERROR+ assert agentService.getProtocolConnectionStatus(knxAgent.getAttribute("knxConfigError2").get().getReferenceOrThrow()) == ConnectionStatus.ERROR_CONFIGURATION}diff --git a/model/src/main/java/org/openremote/model/asset/agent/ConnectionStatus.java b/model/src/main/java/org/openremote/model/asset/agent/ConnectionStatus.javaindex 152b0d664..e587d8a6f 100644--- a/model/src/main/java/org/openremote/model/asset/agent/ConnectionStatus.java+++ b/model/src/main/java/org/openremote/model/asset/agent/ConnectionStatus.java@@ -71,6 +71,11 @@ public enum ConnectionStatus {*/ERROR_AUTHENTICATION,+ /**+ * A configuration related error has occurred.+ */+ ERROR_CONFIGURATION,+/*** A general error has occurred that prevents normal operation.*/