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
Finished first version of KNX protocol
Marcus Redekerb9cfe56b02a1
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 bdb8e48a4..d4060c66b 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,26 +1,41 @@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.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 org.openremote.model.value.impl.BooleanValueImpl;+import org.openremote.model.value.impl.NumberValueImpl;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.KNXException;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.dptxlator.DPTXlatorBoolean;+import tuwien.auto.calimero.dptxlator.TranslatorTypes;import tuwien.auto.calimero.link.KNXNetworkLink;import tuwien.auto.calimero.link.KNXNetworkLinkIP;import tuwien.auto.calimero.link.NetworkLinkListener;@@ -42,17 +57,34 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {protected final List<Consumer<ConnectionStatus>> connectionStatusConsumers = new ArrayList<>();- protected final String gatewayIp;protected final ProtocolExecutorService executorService;protected final int port = 3671;+ 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 String gatewayIp;++ private int remotePort;++ private boolean useNat;++ private String localKNXAddress;++ private String localIp;private static final Logger LOG = Logger.getLogger(KNXConnection.class.getName());- public KNXConnection(String gatewayIp, ProtocolExecutorService executorService) {+ public KNXConnection(String gatewayIp, String connectionType, ProtocolExecutorService executorService, String localIp, Integer remotePort, Boolean useNat, String localKNXAddress) {this.gatewayIp = gatewayIp;this.executorService = executorService;+ this.connectionType = connectionType;+ this.localIp = localIp;+ this.remotePort = remotePort.intValue();+ this.useNat = useNat.booleanValue();+ this.localKNXAddress = localKNXAddress;}public synchronized void connect() {@@ -64,12 +96,21 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {LOG.fine("Connecting");onConnectionStatusChanged(ConnectionStatus.CONNECTING);-- 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);+ InetSocketAddress localEndPoint = null;+ InetSocketAddress remoteEndPoint = new InetSocketAddress(this.gatewayIp, this.remotePort);+ try {+ TPSettings tpSettings = new TPSettings(new IndividualAddress(this.localKNXAddress));+ if (StringUtils.isNotBlank(this.localIp)) {+ localEndPoint = new InetSocketAddress(this.localIp, 0);+ } else {+ InetAddress localHost = InetAddress.getLocalHost();+ localEndPoint = new InetSocketAddress(localHost, 0);+ }+ if (this.connectionType.equals("TUNNELLING")) {+ knxLink = KNXNetworkLinkIP.newTunnelingLink(localEndPoint, remoteEndPoint, this.useNat, tpSettings);+ } else {+ knxLink = KNXNetworkLinkIP.newRoutingLink(localEndPoint.getAddress(), remoteEndPoint.getAddress(), tpSettings);+ }if (knxLink.isOpen()) {LOG.fine("Successfully connected to: " + gatewayIp + ":" + port);@@ -86,10 +127,13 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {scheduleReconnect();}}- catch (final KNXException | InterruptedException | RuntimeException e) {+ catch (final KNXException | InterruptedException e) {LOG.log(Level.INFO, "Connection error", e.getMessage());scheduleReconnect();}+ catch (final UnknownHostException e) {+ LOG.log(Level.INFO, "Connection error", e.getMessage());+ }}public synchronized void disconnect() {@@ -134,7 +178,8 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {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+ LOG.fine("Sending to KNX action datapoint '" + datapoint + "': " + value);+ //TODO a more detailed conversion from OpenRemote value to needed KNX datapoint valueValue val = value.get();switch (val.getType()) {case BOOLEAN:@@ -153,42 +198,59 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {}public void groupWrite(final ProcessEvent e) {- //TODO listen on groupWrites to statusGA and update attribute+ if (datapoints.contains(e.getDestination())) {+ StateDP datapoint = datapoints.get(e.getDestination());+ final String dpt = datapoint.getDPT();+ DPTXlator translator = null;+ try {+ translator = TranslatorTypes.createTranslator(0, dpt);+ translator.setData(e.getASDU());+ LOG.info("Received KNX event: " + translator.getType().getID() + " (" + translator.getType().getDescription() + ") is " + translator.getValue() + " (" + translator.getNumericValue() + ") - " + datapoint.getName());++ Value value;+ //TODO a more detailed conversion form KNX datapoint value to OpenRemote value+ if (translator instanceof DPTXlatorBoolean) {+ value = new BooleanValueImpl(Boolean.valueOf(translator.getValue().equals("on")));+ } else {+ value = new NumberValueImpl(translator.getNumericValue());+ }+ for (Consumer<Value> consumer : datapointValueConsumers.get(datapoint)) {+ consumer.accept(value);+ }+ } catch (KNXException ex) {+ LOG.log(Level.WARNING, "Could translate KNX event: " + e, ex);+ }+ }}- public void groupReadRequest(final ProcessEvent e) { }+ public void groupReadRequest(final ProcessEvent e) { groupWrite(e); }public void groupReadResponse(final ProcessEvent e) {- //TODO listen on readResponses to statusGA and update attribute+ groupWrite(e);}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;-// }-+ 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);+ }+ 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 DPT: " + datapoint, e);+ }+ }++ public void stopMonitoringStateDP(StateDP datapoint) {+ this.datapoints.remove(datapoint);+ }@Overridepublic void indication(FrameEvent e) {@@ -233,4 +295,5 @@ 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 38e13c06c..0ee3a66e8 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,7 +14,9 @@ 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.attribute.AttributeState;import org.openremote.model.util.Pair;+import org.openremote.model.value.Value;import tuwien.auto.calimero.GroupAddress;import tuwien.auto.calimero.KNXFormatException;@@ -22,12 +24,55 @@ import tuwien.auto.calimero.datapoint.CommandDP;import tuwien.auto.calimero.datapoint.Datapoint;import tuwien.auto.calimero.datapoint.StateDP;+/**+ * This protocol is used to connecto to a KNX bus via an IP interface.+ */public class KNXProtocol extends AbstractProtocol {private static final Logger LOG = Logger.getLogger(KNXProtocol.class.getName());public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":knx";++ //Protocol specific configuration meta items+ /**+ * IP address of the KNX gateway to connect to in TUNNEL mode. Optional if {@link #KNX_IP_CONNECTION_TYPE} is ROUTING.<br>+ * In ROUTING mode, the IP address specifies the multicast group to join.+ */public static final String KNX_GATEWAY_IP = PROTOCOL_NAME + ":gatewayIp";++ /**+ * The KNX gateway port to connect to in TUNNEL mode. Not used in ROUTING mode.<br>+ * Default: 3671+ */+ public static final String KNX_GATEWAY_PORT = PROTOCOL_NAME + ":gatewayPort";++ /**+ * <code>TRUE</code> to use network address translation in TUNNELLING mode, <code>FALSE</code>+ * to use the default (non aware) mode; parameter is ignored for ROUTING<br>+ * Default: <code>FALSE</code>+ */+ public static final String KNX_GATEWAY_USENAT = PROTOCOL_NAME + ":useNAT";++ /**+ * ServiceMode mode of communication to open, <code>connectionType</code> is one of TUNNELLING or ROUTING<br>+ * Default: TUNNELLING+ */+ public static final String KNX_IP_CONNECTION_TYPE = PROTOCOL_NAME + ":connectionType";++ /**+ * Device individual address to use as source address in KNX messages.<br>+ * Default: 0.0.0+ */+ public static final String KNX_LOCAL_BUS_ADDRESS = PROTOCOL_NAME + ":localBusAddress";++ /**+ * Local IP address or hostname to establish connection from.<br>+ * Default: hostname+ */+ public static final String KNX_LOCAL_IP = PROTOCOL_NAME + ":localIP";+++ //Attribute specific configuration meta itemspublic 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";@@ -35,7 +80,7 @@ public class KNXProtocol extends AbstractProtocol {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<>();+ final protected Map<AttributeRef, Pair<KNXConnection, StateDP>> attributeStatusMap = new HashMap<>();@Overridepublic String getProtocolName() {@@ -44,9 +89,16 @@ public class KNXProtocol extends AbstractProtocol {@Overrideprotected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ String connectionType = protocolConfiguration.getMetaItem(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);+ return;+ }+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);+ 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);return;}@@ -56,6 +108,11 @@ public class KNXProtocol extends AbstractProtocol {return;}+ String localIp = protocolConfiguration.getMetaItem(KNX_LOCAL_IP).flatMap(AbstractValueHolder::getValueAsString).orElse(null);+ Integer remotePort = protocolConfiguration.getMetaItem(KNX_GATEWAY_PORT).flatMap(AbstractValueHolder::getValueAsInteger).orElse(Integer.valueOf(3671));+ String localKNXAddress = protocolConfiguration.getMetaItem(KNX_LOCAL_BUS_ADDRESS).flatMap(AbstractValueHolder::getValueAsString).orElse("0.0.0");+ Boolean useNat = protocolConfiguration.getMetaItem(KNX_GATEWAY_USENAT).flatMap(AbstractValueHolder::getValueAsBoolean).orElse(Boolean.FALSE);+AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();synchronized (knxConnections) {@@ -65,7 +122,7 @@ public class KNXProtocol extends AbstractProtocol {KNXConnection knxConnection = knxConnections.computeIfAbsent(gatewayIpParam.get(), gatewayIp ->- new KNXConnection(gatewayIp, executorService)+ new KNXConnection(gatewayIp, connectionType, executorService, localIp, remotePort, useNat, localKNXAddress));knxConnection.addConnectionStatusConsumer(statusConsumer);knxConnection.connect();@@ -170,7 +227,6 @@ public class KNXProtocol extends AbstractProtocol {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@@ -186,15 +242,16 @@ public class KNXProtocol extends AbstractProtocol {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;}+ Datapoint datapoint = new CommandDP(new GroupAddress(groupAddress), attributeRef.getAttributeName());+ datapoint.setDPT(0, dpt);+attributeActionMap.put(attributeRef, new Pair<>(knxConnection, datapoint));- LOG.info("Attribute registered for sending commands: " + attributeRef);+ LOG.info("Attribute registered for sending commands: " + attributeRef + " with datapoint: " + datapoint);}}@@ -206,25 +263,32 @@ public class KNXProtocol extends AbstractProtocol {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);+ Pair<KNXConnection, StateDP> controlInfo = attributeStatusMap.get(attributeRef);if (controlInfo != null) {return;}++ StateDP datapoint = new StateDP(new GroupAddress(groupAddress), attributeRef.getAttributeName());+ datapoint.setDPT(0, dpt);- //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-+ knxConnection.monitorStateDP(datapoint, value -> handleKNXValueChange(attributeRef, value));+attributeStatusMap.put(attributeRef, new Pair<>(knxConnection, datapoint));- LOG.info("Attribute registered for sending commands: " + attributeRef);+ LOG.info("Attribute registered for status updates: " + attributeRef + " with datapoint: " + datapoint);}}+ protected void handleKNXValueChange(AttributeRef attributeRef, Value value) {+ LOG.fine("KNX protocol received value '" + value + "' for : " + attributeRef);+ updateLinkedAttribute(new AttributeState(attributeRef, value));+ }+protected void removeStatusDatapoint(AttributeRef attributeRef) {- //TODO remove from listener on KNXConnectionsynchronized (attributeStatusMap) {- attributeStatusMap.remove(attributeRef);+ Pair<KNXConnection, StateDP> controlInfo = attributeStatusMap.remove(attributeRef);+ if (controlInfo != null) {+ controlInfo.key.stopMonitoringStateDP(controlInfo.value);+ }}}@@ -234,7 +298,7 @@ public class KNXProtocol extends AbstractProtocol {}- public Map<AttributeRef, Pair<KNXConnection, Datapoint>> getAttributeStatusMap() {+ public Map<AttributeRef, Pair<KNXConnection, StateDP>> getAttributeStatusMap() {return attributeStatusMap;}diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BuiltinSetupTasks.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BuiltinSetupTasks.javaindex 72ea801e9..021e9b7f7 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BuiltinSetupTasks.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BuiltinSetupTasks.java@@ -48,6 +48,7 @@ import static org.openremote.container.util.MapAccess.getBoolean;* <li>{@link #SETUP_IMPORT_DEMO_ASSETS} depends on {@link #SETUP_IMPORT_DEMO_USERS}</li>* <li>{@link #SETUP_IMPORT_DEMO_SCENES} depends on {@link #SETUP_IMPORT_DEMO_ASSETS}</li>* <li>{@link #SETUP_IMPORT_DEMO_RULES} depends on {@link #SETUP_IMPORT_DEMO_SCENES}</li>+ * <li>{@link #SETUP_IMPORT_KNX_DEMO_ASSETS} depends on {@link #SETUP_IMPORT_DEMO_ASSETS}</li>* </ul>*/public class BuiltinSetupTasks extends AbstractSetupTasks {@@ -57,12 +58,16 @@ public class BuiltinSetupTasks extends AbstractSetupTasks {public static final String SETUP_IMPORT_DEMO_ASSETS = "SETUP_IMPORT_DEMO_ASSETS";public static final String SETUP_IMPORT_DEMO_SCENES = "SETUP_IMPORT_DEMO_SCENES";public static final String SETUP_IMPORT_DEMO_RULES = "SETUP_IMPORT_DEMO_RULES";+ public static final String SETUP_IMPORT_KNX_DEMO_ASSETS = "SETUP_IMPORT_KNX_DEMO_ASSETS";@Overridepublic List<Setup> createTasks(Container container) {boolean cleanDatabase = getBoolean(container.getConfig(), SETUP_INIT_CLEAN_DATABASE, container.isDevMode());+ // KNX demo assets to test real physical KNX bus. A KNX IP gateway and knx bus is needed+ boolean importKNXDemoAssets = getBoolean(container.getConfig(), SETUP_IMPORT_KNX_DEMO_ASSETS, false);+// Too many rules are difficult to debug, so they are optionalboolean importDemoRules = getBoolean(container.getConfig(), SETUP_IMPORT_DEMO_RULES, container.isDevMode());@@ -70,7 +75,7 @@ public class BuiltinSetupTasks extends AbstractSetupTasks {boolean importDemoScenes = importDemoRules || getBoolean(container.getConfig(), SETUP_IMPORT_DEMO_SCENES, container.isDevMode());// If importing demo rules we have to import demo assets- boolean importDemoAssets = importDemoRules || getBoolean(container.getConfig(), SETUP_IMPORT_DEMO_ASSETS, container.isDevMode());+ boolean importDemoAssets = importDemoRules || importKNXDemoAssets || getBoolean(container.getConfig(), SETUP_IMPORT_DEMO_ASSETS, container.isDevMode());// If importing demo assets we have to import demo usersboolean importDemoUsers = importDemoAssets || getBoolean(container.getConfig(), SETUP_IMPORT_DEMO_USERS, container.isDevMode());@@ -95,6 +100,10 @@ public class BuiltinSetupTasks extends AbstractSetupTasks {if (importDemoRules) {addTask(new RulesDemoSetup(container));}++ if (importKNXDemoAssets) {+ addTask(new ManagerDemoKNXSetup(container));+ }} else {if (cleanDatabase) {addTask(new ManagerCleanSetup(container));diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoKNXSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoKNXSetup.javanew file mode 100644index 000000000..c9e9d5759--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoKNXSetup.java@@ -0,0 +1,108 @@+/*+ * Copyright 2016, 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.manager.server.setup.builtin;++import static org.openremote.model.asset.AssetMeta.DESCRIPTION;+import static org.openremote.model.asset.AssetMeta.LABEL;+import static org.openremote.model.asset.AssetType.AGENT;+import static org.openremote.model.asset.AssetType.BUILDING;+import static org.openremote.model.asset.AssetType.ROOM;+import static org.openremote.model.asset.agent.ProtocolConfiguration.initProtocolConfiguration;++import org.openremote.agent.protocol.knx.KNXProtocol;+import org.openremote.container.Container;+import org.openremote.manager.server.asset.ServerAsset;+import org.openremote.manager.server.setup.AbstractManagerSetup;+import org.openremote.manager.shared.security.Tenant;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetMeta;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeType;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.value.Values;++import com.vividsolutions.jts.geom.Coordinate;++public class ManagerDemoKNXSetup extends AbstractManagerSetup {++ public String masterRealmId;++ public ManagerDemoKNXSetup(Container container) {+ super(container);+ }++ @Override+ public void execute() throws Exception {++ KeycloakDemoSetup keycloakDemoSetup = setupService.getTaskOfType(KeycloakDemoSetup.class);+ Tenant masterTenant = keycloakDemoSetup.masterTenant;+ masterRealmId = masterTenant.getId();++ // ########### KNX assets in 'master' realm ####################+ ServerAsset knxOffice = new ServerAsset("KNX Building", BUILDING);+ knxOffice.setRealmId(masterTenant.getId());+ //knxOffice.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));+ knxOffice = assetStorageService.merge(knxOffice);++ ServerAsset knxAgent = new ServerAsset("KNX Agent", AGENT, knxOffice);+ knxAgent.setAttributes(+ initProtocolConfiguration(new AssetAttribute("knxConfig"), KNXProtocol.PROTOCOL_NAME)+ .addMeta(+ new MetaItem(KNXProtocol.KNX_GATEWAY_IP, Values.create("192.168.100.10"))+ )+ );+ knxAgent.setRealmId(masterTenant.getId());+ knxAgent = assetStorageService.merge(knxAgent);++ ServerAsset knxThing = new ServerAsset("Office", ROOM, knxOffice);+ knxThing.setAttributes(+ new AssetAttribute("Light1_Switch", AttributeType.BOOLEAN)+ .setMeta(+ new MetaItem(LABEL, Values.create("Light 1 (Switch)")),+ new MetaItem(DESCRIPTION, Values.create("Light 1 connected to a KNX switch actuator")),+ 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())+ ),+ new AssetAttribute("Light2_Switch", AttributeType.BOOLEAN)+ .setMeta(+ new MetaItem(LABEL, Values.create("Light 2 (Switch)")),+ new MetaItem(DESCRIPTION, Values.create("Light 2 connected to a KNX dimming actuator")),+ new MetaItem(KNXProtocol.ACTION_GA, Values.create("1/0/11")),+ new MetaItem(KNXProtocol.STATUS_GA, Values.create("0/4/10")),+ new MetaItem(KNXProtocol.DPT, Values.create("1.001")),+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(knxAgent.getId(), "knxConfig").toArrayValue())+ ),+ new AssetAttribute("Light2_Dimming", AttributeType.PERCENTAGE)+ .setMeta(+ new MetaItem(LABEL, Values.create("Light 2 (Dimming)")),+ new MetaItem(DESCRIPTION, Values.create("Light 2 connected to a KNX dimming actuator")),+ new MetaItem(KNXProtocol.ACTION_GA, Values.create("1/0/13")),+ new MetaItem(KNXProtocol.STATUS_GA, Values.create("0/4/11")),+ new MetaItem(KNXProtocol.DPT, Values.create("5.001")),+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(knxAgent.getId(), "knxConfig").toArrayValue())+ )+ );+++ knxThing = assetStorageService.merge(knxThing);+ }+}\ No newline at end of filediff --git a/manager/test/src/main/groovy/org/openremote/test/KNXTestingNetworkLink.java b/manager/test/src/main/groovy/org/openremote/test/KNXTestingNetworkLink.javaindex c3e95cb2f..11deb8ce6 100644--- a/manager/test/src/main/groovy/org/openremote/test/KNXTestingNetworkLink.java+++ b/manager/test/src/main/groovy/org/openremote/test/KNXTestingNetworkLink.java@@ -2,20 +2,32 @@ package org.openremote.test;import java.util.ArrayList;import java.util.List;+import java.util.logging.Logger;++import org.openremote.agent.protocol.knx.KNXProtocol;import tuwien.auto.calimero.FrameEvent;+import tuwien.auto.calimero.GroupAddress;import tuwien.auto.calimero.IndividualAddress;import tuwien.auto.calimero.KNXAddress;import tuwien.auto.calimero.KNXFormatException;import tuwien.auto.calimero.KNXTimeoutException;+import tuwien.auto.calimero.Priority;import tuwien.auto.calimero.cemi.CEMI;+import tuwien.auto.calimero.cemi.CEMIFactory;import tuwien.auto.calimero.cemi.CEMILData;+import tuwien.auto.calimero.internal.EventListeners;+import tuwien.auto.calimero.knxnetip.util.KnxAddressesDIB;import tuwien.auto.calimero.link.AbstractLink;import tuwien.auto.calimero.link.KNXLinkClosedException;+import tuwien.auto.calimero.link.NetworkLinkListener;import tuwien.auto.calimero.link.medium.KNXMediumSettings;+import tuwien.auto.calimero.server.VirtualLink;public class KNXTestingNetworkLink extends AbstractLink {+ private static final Logger LOG = Logger.getLogger(KNXTestingNetworkLink.class.getName());+private static KNXTestingNetworkLink instance;private String lastDataReceived;@@ -24,14 +36,14 @@ public class KNXTestingNetworkLink extends AbstractLink {KNXTestingNetworkLink.instance = this;}-- @Override- protected void onSend(KNXAddress dst, byte[] msg, boolean waitForCon) throws KNXTimeoutException, KNXLinkClosedException {- }-@Overrideprotected void onSend(CEMILData msg, boolean waitForCon) throws KNXTimeoutException, KNXLinkClosedException {- this.lastDataReceived = byteArrayToHex(msg.getPayload());+ if (msg.getDestination().toString().equals("0/4/14")) {++ } else {+ LOG.info("KNX bus received message: " + msg);+ this.lastDataReceived = byteArrayToHex(msg.getPayload());+ }}@Override@@ -53,4 +65,10 @@ public class KNXTestingNetworkLink extends AbstractLink {public String getLastDataReceived() {return this.lastDataReceived;}++ @Override+ protected void onSend(KNXAddress dst, byte[] msg, boolean waitForCon) throws KNXTimeoutException, KNXLinkClosedException {+ // TODO Auto-generated method stub++ }}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 793eaba4f..2af05e28d 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@@ -47,7 +47,6 @@ import tuwien.auto.calimero.server.Launcher/*** This tests the KNX protocol and protocol implementation.*/-@Ignore // TODO Verify test on other machinesclass KNXProtocolTest extends Specification implements ManagerContainerTrait {def "Check KNX protocol"() {@@ -77,9 +76,14 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {knxAgent.setAttributes(ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute("knxConfig"), KNXProtocol.PROTOCOL_NAME).addMeta(- new MetaItem(KNXProtocol.KNX_GATEWAY_IP, Values.create("localhost"))+ new MetaItem(KNXProtocol.KNX_GATEWAY_IP, Values.create("localhost")),+ new MetaItem(KNXProtocol.KNX_LOCAL_IP, Values.create("localhost"))),- ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute("knxConfigError"), KNXProtocol.PROTOCOL_NAME)+ ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute("knxConfigError1"), KNXProtocol.PROTOCOL_NAME),+ ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute("knxConfigError2"), KNXProtocol.PROTOCOL_NAME)+ .addMeta(+ new MetaItem(KNXProtocol.KNX_IP_CONNECTION_TYPE, Values.create("dummy"))+ ))knxAgent.setRealmId(Constants.MASTER_REALM)knxAgent = assetStorageService.merge(knxAgent)@@ -89,7 +93,10 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfig").get().getReferenceOrThrow()) == ConnectionStatus.CONNECTED}conditions.eventually {- assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfigError").get().getReferenceOrThrow()) == ConnectionStatus.ERROR+ assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfigError1").get().getReferenceOrThrow()) == ConnectionStatus.ERROR+ }+ conditions.eventually {+ assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfigError2").get().getReferenceOrThrow()) == ConnectionStatus.ERROR}@@ -114,22 +121,22 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {}- when: "change light1ToggleOnOff value to 'false'"- def switchChange = new AttributeEvent(knxThing.getId(), "light1ToggleOnOff", Values.create(false))+ when: "change light1ToggleOnOff value to 'true'"+ def switchChange = new AttributeEvent(knxThing.getId(), "light1ToggleOnOff", Values.create(true))assetProcessingService.sendAttributeEvent(switchChange)then: "the correct data should arrive on KNX bus"conditions.eventually {- assert knxTestingNetwork.getLastDataReceived().equals("0080") == true+ assert knxTestingNetwork.getLastDataReceived().equals("0081") == true}- when: "change light1ToggleOnOff value to 'true'"- switchChange = new AttributeEvent(knxThing.getId(), "light1ToggleOnOff", Values.create(true))+ when: "change light1ToggleOnOff value to 'false'"+ switchChange = new AttributeEvent(knxThing.getId(), "light1ToggleOnOff", Values.create(false))assetProcessingService.sendAttributeEvent(switchChange)then: "the correct data should arrive on KNX bus"conditions.eventually {- assert knxTestingNetwork.getLastDataReceived().equals("0081") == true+ assert knxTestingNetwork.getLastDataReceived().equals("0080") == true}cleanup: "the server should be stopped"