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
Work on KNX protocol
Marcus Redekere1631ef75464
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 c2306a480..bdb8e48a4 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@@ -3,6 +3,7 @@ package org.openremote.agent.protocol.knx;import java.net.InetSocketAddress;import java.util.ArrayList;import java.util.List;+import java.util.Optional;import java.util.concurrent.ScheduledFuture;import java.util.function.Consumer;import java.util.logging.Level;@@ -10,18 +11,26 @@ import java.util.logging.Logger;import org.openremote.agent.protocol.ConnectionStatus;import org.openremote.agent.protocol.ProtocolExecutorService;+import org.openremote.model.value.BooleanValue;+import org.openremote.model.value.NumberValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.ValueException;import tuwien.auto.calimero.CloseEvent;+import tuwien.auto.calimero.DetachEvent;import tuwien.auto.calimero.FrameEvent;import tuwien.auto.calimero.KNXException;+import tuwien.auto.calimero.datapoint.Datapoint;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;+import tuwien.auto.calimero.process.ProcessEvent;+import tuwien.auto.calimero.process.ProcessListener;-public class KNXConnection implements NetworkLinkListener {+public class KNXConnection implements NetworkLinkListener, ProcessListener {protected ConnectionStatus connectionStatus = ConnectionStatus.DISCONNECTED;@@ -37,6 +46,7 @@ public class KNXConnection implements NetworkLinkListener {protected final ProtocolExecutorService executorService;protected final int port = 3671;protected KNXNetworkLink knxLink;+ protected ProcessCommunicator processCommunicator;private static final Logger LOG = Logger.getLogger(KNXConnection.class.getName());@@ -57,15 +67,16 @@ public class KNXConnection implements NetworkLinkListener {final InetSocketAddress remote = new InetSocketAddress(gatewayIp, port);try {+ //TODO accept local address, local port, useNat as extra connection params from protocl configuration+ //final InetSocketAddress localSocket = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);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);+ processCommunicator = new ProcessCommunicatorImpl(knxLink);+ processCommunicator.addProcessListener(this);+ knxLink.addLinkListener(this);+reconnectTask = null;reconnectDelayMilliseconds = INITIAL_RECONNECT_DELAY_MILLIS;onConnectionStatusChanged(ConnectionStatus.CONNECTED);@@ -89,9 +100,14 @@ public class KNXConnection implements NetworkLinkListener {LOG.finest("Disconnecting");onConnectionStatusChanged(ConnectionStatus.DISCONNECTING);- knxLink.removeLinkListener(this);- knxLink.close();- knxLink = null;+ if (processCommunicator != null) {+ processCommunicator.detach();+ }+ if (knxLink != null) {+ knxLink.removeLinkListener(this);+ knxLink.close();+ knxLink = null;+ }onConnectionStatusChanged(ConnectionStatus.DISCONNECTED);}@@ -115,6 +131,64 @@ public class KNXConnection implements NetworkLinkListener {}}+ public void sendCommand(Datapoint datapoint, Optional<Value> value) {+ try {+ if (this.connectionStatus == ConnectionStatus.CONNECTED && value.isPresent()) {+ //TODO a more detailed conversion of value to needed KNX datapoint value+ Value val = value.get();+ switch (val.getType()) {+ case BOOLEAN:+ processCommunicator.write(datapoint.getMainAddress(), ((BooleanValue)val).getBoolean());+ break;+ case NUMBER:+ processCommunicator.write(datapoint.getMainAddress(),(float) ((NumberValue)val).getNumber(), datapoint.getMainNumber() == 14);+ break;+ default:+ break;+ }+ }+ } catch (ValueException | KNXException e) {+ LOG.severe(e.getMessage());+ }+ }++ public void groupWrite(final ProcessEvent e) {+ //TODO listen on groupWrites to statusGA and update attribute+ }++ public void groupReadRequest(final ProcessEvent e) { }++ public void groupReadResponse(final ProcessEvent e) {+ //TODO listen on readResponses to statusGA and update attribute+ }++ public void detached(final DetachEvent e) {}++//TODO when registering statusGA send readRequest for initial status+// public synchronized MeasurementRegistration monitorReadGroupAddress(int deviceId, String measurementName, BiConsumer<MeasurementRegistration, Measurement> consumer) {+// // Enervalis API v1 cannot provide device info for a list of devices by ID+// // (devices would need to be grouped into a device group first) - instead lets+// // just poll all devices that this user has access to and extract the ones we're+// // interested in - may not be ideal but let's assume we're going to want to monitor+// // most of the devices.+//+// // Normalise the measurement name (case insensitive)+// measurementName = measurementName.toLowerCase().trim();+//+// // Build registration hash key+// String regKey = deviceId + "_" + measurementName;+//+// // Build registration+// Datapoint datapoint = new StateD (deviceId, measurementName, consumer);+//+// List<MeasurementRegistration> registrations =+// measurementRegistrations.computeIfAbsent(regKey, k -> new ArrayList<>());+// registrations.add(registration);+//+// startDevicePolling();+// return registration;+// }+@Overridepublic void indication(FrameEvent e) {@@ -122,7 +196,9 @@ public class KNXConnection implements NetworkLinkListener {@Overridepublic void linkClosed(CloseEvent e) {+ LOG.log(Level.INFO, "KNX link closed", e.getReason());onConnectionStatusChanged(ConnectionStatus.CLOSED);+ processCommunicator.detach();knxLink.removeLinkListener(this);knxLink.close();knxLink = null;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 b3806a45b..38e13c06c 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@@ -14,6 +14,13 @@ import org.openremote.model.AbstractValueHolder;import org.openremote.model.asset.AssetAttribute;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.util.Pair;++import tuwien.auto.calimero.GroupAddress;+import tuwien.auto.calimero.KNXFormatException;+import tuwien.auto.calimero.datapoint.CommandDP;+import tuwien.auto.calimero.datapoint.Datapoint;+import tuwien.auto.calimero.datapoint.StateDP;public class KNXProtocol extends AbstractProtocol {@@ -21,9 +28,14 @@ public class KNXProtocol extends AbstractProtocol {public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":knx";public static final String KNX_GATEWAY_IP = PROTOCOL_NAME + ":gatewayIp";+ public static final String DPT = PROTOCOL_NAME + ":dpt";+ public static final String STATUS_GA = PROTOCOL_NAME + ":statusGA";+ public static final String ACTION_GA = PROTOCOL_NAME + ":actionGA";final protected Map<String, KNXConnection> knxConnections = new HashMap<>();final protected Map<AttributeRef, Consumer<ConnectionStatus>> statusConsumerMap = new HashMap<>();+ final protected Map<AttributeRef, Pair<KNXConnection, Datapoint>> attributeActionMap = new HashMap<>();+ final protected Map<AttributeRef, Pair<KNXConnection, Datapoint>> attributeStatusMap = new HashMap<>();@Overridepublic String getProtocolName() {@@ -76,33 +88,94 @@ public class KNXProtocol extends AbstractProtocol {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();+ if (!isKNXConnectionStillUsed(knxConnection)) {+ knxConnection.removeConnectionStatusConsumer(statusConsumer);+ knxConnection.disconnect();+ knxConnections.remove(gatewayIp);+ }}}}@Overrideprotected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {- // TODO different attributes can have same group address- //create calimero StateDP ga, name, read address, write address+ String gatewayIp = protocolConfiguration.getMetaItem(KNX_GATEWAY_IP).flatMap(AbstractValueHolder::getValueAsString).orElse("");+ final AttributeRef attributeRef = attribute.getReferenceOrThrow();++ // Check there is a DPT+ Optional<String> dpt = attribute.getMetaItem(DPT).flatMap(AbstractValueHolder::getValueAsString);+ if (!dpt.isPresent()) {+ LOG.severe("No DPT for protocol attribute: " + attributeRef);+ return;+ }+ Optional<String> statusGA = attribute.getMetaItem(STATUS_GA).flatMap(AbstractValueHolder::getValueAsString);+ Optional<String> actionGA = attribute.getMetaItem(ACTION_GA).flatMap(AbstractValueHolder::getValueAsString);++ if (!statusGA.isPresent() && !actionGA.isPresent()) {+ LOG.warning("No status group address or action group address provided so nothing to do for protocol attribute: " + attributeRef);+ return;+ }++ KNXConnection knxConnection = getConnection(gatewayIp);++ if (knxConnection == null) {+ // Means that the protocol configuration is disabled+ return;+ }++ // If this attribute relates to a read groupthen start monitoring that measurement and broadcast any changes to the value+ statusGA.ifPresent(groupAddress -> {+ try {+ addStatusDatapoint(attributeRef, knxConnection, groupAddress, dpt.get());+ } catch (KNXFormatException e) {+ LOG.severe("Give action group address is invalid for protocol attribute: " + attributeRef + " - " + e.getMessage());+ }+ });++ // If this attribute relates to an action then store it+ actionGA.ifPresent(groupAddress -> {+ try {+ addActionDatapoint(attributeRef, knxConnection, groupAddress, dpt.get());+ } catch (KNXFormatException e) {+ LOG.severe("Give action group address is invalid for protocol attribute: " + attributeRef + " - " + e.getMessage());+ }+ });}+@Overrideprotected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {- // TODO+ final AttributeRef attributeRef = attribute.getReferenceOrThrow();++ // If this attribute is registered for status updates then un-subscribe it+ removeStatusDatapoint(attributeRef);+ // If this attribute has a stored action then remove it+ removeActionDatapoint(attributeRef);}@Overrideprotected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration) {- // TODO groupWrite - event.getAttributeRef() to identify groupaddress- // event.getValue() - new value to send to knx-+ if (!protocolConfiguration.isEnabled()) {+ LOG.fine("Protocol configuration is disabled so ignoring write request");+ return;+ }++ synchronized (attributeActionMap) {+ Pair<KNXConnection, Datapoint> controlInfo = attributeActionMap.get(event.getAttributeRef());++ if (controlInfo == null) {+ LOG.fine("Attribute isn't linked to a KNX datapoint so cannot process write: " + event);+ return;+ }++ LOG.fine("Sending to KNX datapoint '" + controlInfo.value + "': " + event.getValue());+ controlInfo.key.sendCommand(controlInfo.value, event.getValue());++ // We assume KNX actuator will send new status on relevant status group address which will be picked up by listener and updates the state again later+ updateLinkedAttribute(event.getAttributeState());+ }}protected KNXConnection getConnection(String gatewayIp) {@@ -111,5 +184,75 @@ public class KNXProtocol extends AbstractProtocol {}}- //TODO call updateLinkedAttribute(AttributeState state, long timestamp) when receiving event from KNX bus+ protected void addActionDatapoint(AttributeRef attributeRef, KNXConnection knxConnection, String groupAddress, String dpt) throws KNXFormatException {+ synchronized (attributeActionMap) {+ Datapoint datapoint = new CommandDP(new GroupAddress(groupAddress), attributeRef.getAttributeName());+ datapoint.setDPT(0, dpt);+ Pair<KNXConnection, Datapoint> controlInfo = attributeActionMap.get(attributeRef);+ if (controlInfo != null) {+ return;+ }++ attributeActionMap.put(attributeRef, new Pair<>(knxConnection, datapoint));+ LOG.info("Attribute registered for sending commands: " + attributeRef);+ }+ }++ protected void removeActionDatapoint(AttributeRef attributeRef) {+ synchronized (attributeActionMap) {+ attributeActionMap.remove(attributeRef);+ }+ }++ protected void addStatusDatapoint(AttributeRef attributeRef, KNXConnection knxConnection, String groupAddress, String dpt) throws KNXFormatException {+ synchronized (attributeStatusMap) {+ Datapoint datapoint = new StateDP(new GroupAddress(groupAddress), attributeRef.getAttributeName());+ datapoint.setDPT(0, dpt);+ Pair<KNXConnection, Datapoint> controlInfo = attributeStatusMap.get(attributeRef);+ if (controlInfo != null) {+ return;+ }++ //TODO inform listener on KNXConnection to update this attribute when changes are coming in. then call updateLinkedAttribute()+ //updateLinkedAttribute(AttributeState state, long timestamp) when receiving event from KNX bus++ attributeStatusMap.put(attributeRef, new Pair<>(knxConnection, datapoint));+ LOG.info("Attribute registered for sending commands: " + attributeRef);+ }+ }++ protected void removeStatusDatapoint(AttributeRef attributeRef) {+ //TODO remove from listener on KNXConnection+ synchronized (attributeStatusMap) {+ attributeStatusMap.remove(attributeRef);+ }+ }+++ public Map<AttributeRef, Pair<KNXConnection, Datapoint>> getAttributeActionMap() {+ return attributeActionMap;+ }+++ public Map<AttributeRef, Pair<KNXConnection, Datapoint>> getAttributeStatusMap() {+ return attributeStatusMap;+ }+++ protected boolean isKNXConnectionStillUsed(KNXConnection knxConnection) {+ boolean clientStillUsed;++ synchronized (attributeStatusMap) {+ clientStillUsed = attributeStatusMap.values().stream().anyMatch(p -> p.key == knxConnection);+ }++ if (!clientStillUsed) {+ synchronized (attributeActionMap) {+ clientStillUsed = attributeActionMap.values().stream().anyMatch(p -> p.key == knxConnection);+ }+ }++ return clientStillUsed;+ }+}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 8119d971f..9fedf2b19 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,9 @@*/package org.openremote.test.protocol+import static org.openremote.model.asset.AssetMeta.DESCRIPTION+import static org.openremote.model.asset.AssetMeta.LABEL+import org.apache.camel.language.simple.ast.BlockStartimport org.openremote.agent.protocol.AbstractProtocolimport org.openremote.agent.protocol.knx.KNXProtocol@@ -49,13 +52,13 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {def "Check KNX protocol"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 1, delay: 1)+ def conditions = new PollingConditions(timeout: 10, initialDelay: 1.5, 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 = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())@@ -86,20 +89,58 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfigError").get().getReferenceOrThrow()) == ConnectionStatus.ERROR}- when: "the connection to the KNX IP gateway is lost"- knxEmulationServer.quit()+// 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.CLOSED+// }+// conditions.eventually {+// assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfig").get().getReferenceOrThrow()) == ConnectionStatus.WAITING+// }+// conditions.eventually {+// assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfig").get().getReferenceOrThrow()) == ConnectionStatus.CONNECTING+// }+// conditions.eventually {+// assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfig").get().getReferenceOrThrow()) == ConnectionStatus.CONNECTED+// }- then: "the protocol status should switch to closed, waiting, connecting, connected"++ when: "a thing asset is created that links it's attributes to the knx protocol configuration"+ def knxThing = new ServerAsset("Living Room Assset", AssetType.THING, knxAgent)+ knxThing.setAttributes(+ new AssetAttribute("light1ToggleOnOff", AttributeType.BOOLEAN)+ .setMeta(+ new MetaItem(LABEL, Values.create("Light 1 Toggle On/Off")),+ new MetaItem(DESCRIPTION, Values.create("Light 1 for living room")),+ new MetaItem(KNXProtocol.ACTION_GA, Values.create("1/0/17")),+ new MetaItem(KNXProtocol.STATUS_GA, Values.create("0/4/14")),+ new MetaItem(KNXProtocol.DPT, Values.create("1.001")),+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(knxAgent.getId(), "knxConfig").toArrayValue())+ )+ )+ knxThing = assetStorageService.merge(knxThing)++ then: "the mock thing to be fully deployed"conditions.eventually {- assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfig").get().getReferenceOrThrow()) == ConnectionStatus.WAITING+ ((KNXProtocol) agentService.getProtocol(knxAgent.getAttribute("knxConfig").get())).getAttributeActionMap().get(knxThing.getAttribute("light1ToggleOnOff")) != null}+++ when: "change light1ToggleOnOff value to 'true'"+ def switchChange = new AttributeEvent(knxThing.getId(), "light1ToggleOnOff", Values.create(false))+ assetProcessingService.sendAttributeEvent(switchChange)++ then: ""conditions.eventually {- assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfig").get().getReferenceOrThrow()) == ConnectionStatus.CONNECTED+ knxThing.getAttribute("light1ToggleOnOff") != null}+cleanup: "the server should be stopped"stopContainer(container)-+ knxEmulationServer.quit()}}\ No newline at end of file