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
KNX import using XST transformation provided by Calimero
Marcus Redekerd5a043f8a13c
diff --git a/agent/build.gradle b/agent/build.gradleindex 3a35c4bf1..65e9c009d 100644--- a/agent/build.gradle+++ b/agent/build.gradle@@ -24,4 +24,6 @@ dependencies {compile "org.fourthline.cling:cling-core:$clingVersion"compile "com.neuronrobotics:nrjavaserial:$nrjavaserialVersion"++ compile "net.sf.saxon:Saxon-HE:$saxonHEVersion"}\ No newline at end of filediff --git a/agent/src/main/java/org/openremote/agent/protocol/knx/EtsFileUriResolver.java b/agent/src/main/java/org/openremote/agent/protocol/knx/EtsFileUriResolver.javanew file mode 100644index 000000000..6f393232c--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/knx/EtsFileUriResolver.java@@ -0,0 +1,72 @@+package org.openremote.agent.protocol.knx;++import java.io.BufferedReader;+import java.io.ByteArrayInputStream;+import java.io.IOException;+import java.io.InputStream;+import java.io.InputStreamReader;+import java.io.Reader;+import java.io.StringWriter;+import java.io.Writer;+import java.util.logging.Level;+import java.util.logging.Logger;+import java.util.zip.ZipEntry;+import java.util.zip.ZipInputStream;++import javax.xml.transform.Source;+import javax.xml.transform.TransformerException;+import javax.xml.transform.URIResolver;+import javax.xml.transform.stream.StreamSource;++public class EtsFileUriResolver implements URIResolver {++ private static final Logger LOG = Logger.getLogger(KNXProtocol.class.getName());++ private byte[] data;++ public EtsFileUriResolver(byte[] fileData) {+ this.data = fileData;+ }++ @Override+ public Source resolve(String href, String base) throws TransformerException {+ ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(data));+ ZipEntry zipEntry = null;+ try {+ zipEntry = zin.getNextEntry();+ String entryData = null;+ while (zipEntry != null) {+ if (zipEntry.getName().equals(href)) {+ entryData = convertStreamToString(zin);+ break;+ }+ zipEntry = zin.getNextEntry();+ }+ return new StreamSource(new ByteArrayInputStream(entryData.getBytes()));+ } catch (IOException e) {+ LOG.log(Level.WARNING, "Could not create XML Stream Source for '" + href + "' from ETS project file.");+ }+ return null;+ }++ public static String convertStreamToString(InputStream is) throws IOException {+ if (is != null) {+ Writer writer = new StringWriter();++ char[] buffer = new char[1024];+ try {+ Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));+ int n;+ while ((n = reader.read(buffer)) != -1) {+ writer.write(buffer, 0, n);+ }+ } finally {+ is.close();+ }+ return writer.toString();+ } else {+ return "";+ }+ }++}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 b93135a4e..6ddc90f83 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@@ -220,7 +220,7 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {Value value;//TODO a more detailed conversion form KNX datapoint value to OpenRemote valueif (translator instanceof DPTXlatorBoolean) {- value = new BooleanValueImpl(Boolean.valueOf(translator.getValue().equals("on")));+ value = new BooleanValueImpl(((DPTXlatorBoolean)translator).getValueBoolean());} else {value = new NumberValueImpl(translator.getNumericValue());}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 abdb9acea..feb637cfa 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@@ -1,32 +1,66 @@package org.openremote.agent.protocol.knx;+import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;+import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;+import static org.openremote.model.util.TextUtil.REGEXP_PATTERN_INTEGER_POSITIVE_NON_ZERO;+import static org.openremote.model.util.TextUtil.isNullOrEmpty;++import java.io.ByteArrayInputStream;+import java.io.ByteArrayOutputStream;+import java.util.Arrays;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.function.Consumer;+import java.util.logging.Logger;+import java.util.zip.ZipEntry;+import java.util.zip.ZipInputStream;++import javax.xml.transform.Transformer;+import javax.xml.transform.TransformerFactory;+import javax.xml.transform.stream.StreamResult;+import javax.xml.transform.stream.StreamSource;++import org.apache.commons.io.IOUtils;import org.openremote.agent.protocol.AbstractProtocol;import org.openremote.agent.protocol.ConnectionStatus;import org.openremote.agent.protocol.ProtocolLinkedAttributeImport;+import org.openremote.container.util.Util;import org.openremote.model.AbstractValueHolder;import org.openremote.model.ValidationFailure;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetAttribute;-import org.openremote.model.attribute.*;+import org.openremote.model.asset.AssetMeta;+import org.openremote.model.asset.AssetType;+import org.openremote.model.asset.agent.AgentLink;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeState;+import org.openremote.model.attribute.AttributeType;+import org.openremote.model.attribute.AttributeValidationResult;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.attribute.MetaItemDescriptor;+import org.openremote.model.attribute.MetaItemDescriptorImpl;import org.openremote.model.file.FileInfo;import org.openremote.model.util.Pair;import org.openremote.model.value.Value;import org.openremote.model.value.ValueType;import org.openremote.model.value.Values;+import tuwien.auto.calimero.GroupAddress;+import tuwien.auto.calimero.KNXException;import tuwien.auto.calimero.KNXFormatException;import tuwien.auto.calimero.datapoint.CommandDP;import tuwien.auto.calimero.datapoint.Datapoint;+import tuwien.auto.calimero.datapoint.DatapointMap;import tuwien.auto.calimero.datapoint.StateDP;--import java.util.*;-import java.util.function.Consumer;-import java.util.logging.Logger;--import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;-import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;-import static org.openremote.model.util.TextUtil.REGEXP_PATTERN_INTEGER_POSITIVE_NON_ZERO;-import static org.openremote.model.util.TextUtil.isNullOrEmpty;+import tuwien.auto.calimero.dptxlator.DPTXlator;+import tuwien.auto.calimero.dptxlator.DPTXlatorBoolean;+import tuwien.auto.calimero.dptxlator.TranslatorTypes;+import tuwien.auto.calimero.xml.KNXMLException;+import tuwien.auto.calimero.xml.XmlInputFactory;+import tuwien.auto.calimero.xml.XmlReader;/*** This protocol is used to connect to a KNX bus via an IP interface.@@ -84,7 +118,8 @@ public class KNXProtocol extends AbstractProtocol implements ProtocolLinkedAttriprotected static final String VERSION = "1.0";- public static final String REGEXP_GROUP_ADDRESS = "^\\d/\\d/\\d$";+ public static final String REGEXP_GROUP_ADDRESS = "^\\d{1,3}/\\d{1,3}/\\d{1,3}$";+ public static final String REGEXP_BUS_ADDRESS = "^\\d\\.\\d\\.\\d$";public static final String REGEXP_DPT = "^\\d{1,2}\\.\\d{1,3}$";public static final String PATTERN_FAILURE_CONNECTION_TYPE = "TUNNELLING|ROUTING";public static final String PATTERN_FAILURE_DPT = "KNX DPT (e.g. 1.001)";@@ -95,7 +130,7 @@ public class KNXProtocol extends AbstractProtocol implements ProtocolLinkedAttrinew MetaItemDescriptorImpl("PROTOCOL_KNX_PORT", META_KNX_GATEWAY_PORT, ValueType.NUMBER, false, REGEXP_PATTERN_INTEGER_POSITIVE_NON_ZERO, MetaItemDescriptor.PatternFailure.INTEGER_POSITIVE_NON_ZERO.name(), 1, null, false),new MetaItemDescriptorImpl("PROTOCOL_KNX_USENAT", META_KNX_GATEWAY_USENAT, ValueType.BOOLEAN, false, null, null, 1, Values.create(false), false),new MetaItemDescriptorImpl("PROTOCOL_KNX_CONNECTION_TYPE", META_KNX_IP_CONNECTION_TYPE, ValueType.STRING, false, "^(TUNNELLING|ROUTING)$", PATTERN_FAILURE_CONNECTION_TYPE, 1, Values.create("TUNNELLING"), false),- new MetaItemDescriptorImpl("PROTOCOL_KNX_LOCAL_BUS_ADDRESS", META_KNX_LOCAL_BUS_ADDRESS, ValueType.STRING, false, REGEXP_GROUP_ADDRESS, "0.0.0", 1, null, false),+ new MetaItemDescriptorImpl("PROTOCOL_KNX_LOCAL_BUS_ADDRESS", META_KNX_LOCAL_BUS_ADDRESS, ValueType.STRING, false, REGEXP_BUS_ADDRESS, "0.0.0", 1, null, false),new MetaItemDescriptorImpl("PROTOCOL_KNX_LOCAL_IP", META_KNX_LOCAL_IP, ValueType.STRING, false, null, null, 1, null, false));@@ -417,7 +452,97 @@ public class KNXProtocol extends AbstractProtocol implements ProtocolLinkedAttri@Overridepublic Asset[] discoverLinkedAssetAttributes(AssetAttribute protocolConfiguration, FileInfo fileInfo) throws IllegalStateException {- // TODO: implement discovery using provided file info- return new Asset[0];+ try {++ String xmlData = null;+ byte[] data = Util.decodeBase64(fileInfo.getContents());+ ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(data));+ ZipEntry zipEntry = zin.getNextEntry();+ while (zipEntry != null) {+ if (zipEntry.getName().endsWith("/0.xml")) {+ xmlData = IOUtils.toString(zin, "UTF-8");+ break;+ }+ zipEntry = zin.getNextEntry();+ }++ // Create a transform factory instance.+ System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");+ TransformerFactory tfactory = TransformerFactory.newInstance();++ // Create a transformer for the stylesheet.+ Transformer transformer = tfactory.newTransformer(new StreamSource(this.getClass().getResourceAsStream("/ets_calimero_group_name.xsl")));++ // Set the URIResolver+ transformer.setURIResolver(new EtsFileUriResolver(data));++ // Transform the source XML into byte array+ ByteArrayOutputStream bos = new ByteArrayOutputStream();+ transformer.transform(new StreamSource(new ByteArrayInputStream(xmlData.getBytes())), new StreamResult(bos));+ byte[] result = bos.toByteArray();++ // we use a map of state-based datapoints and read from the transformed xml+ final DatapointMap<StateDP> datapoints = new DatapointMap<>();+ try (final XmlReader r = XmlInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(result))) {+ datapoints.load(r);+ } catch (final KNXMLException e) {+ LOG.warning("Error loading parsed ETS file: " + e.getMessage());+ }++ MetaItem agentLink = AgentLink.asAgentLinkMetaItem(protocolConfiguration.getReferenceOrThrow());+ Map<String, Asset> createdAssets = new HashMap<>();+ for (StateDP dp : datapoints.getDatapoints()) {+ if (dp.getName().endsWith("#A")) {+ createAsset(dp, false, agentLink, createdAssets);+ } else if (dp.getName().endsWith("#S")) {+ createAsset(dp, true, agentLink, createdAssets);+ } else {+ LOG.info("Only group addresses ending on #A or #S will be imported. Ignoring: " + dp.getName());+ }+ }++ return createdAssets.values().toArray(new Asset[createdAssets.values().size()]);++ } catch (Exception e) {+ throw new IllegalStateException("ETS import error", e);+ }+ }++ protected Asset 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;+ if (createdAssets.containsKey(assetName)) {+ asset = createdAssets.get(assetName);+ } else {+ asset = new Asset(assetName, AssetType.THING);+ }++ String attrName = assetName.replaceAll(" ", "");+ //TODO a more detailed conversion form KNX datapoint value to OpenRemote value+ DPTXlator translator = TranslatorTypes.createTranslator(0, datapoint.getDPT());+ AttributeType type;+ if (translator instanceof DPTXlatorBoolean) {+ type = AttributeType.BOOLEAN;+ } else {+ type = AttributeType.NUMBER;+ }+ AssetAttribute attr = asset.getAttribute(attrName).orElse(new AssetAttribute(attrName, type).setMeta(+ new MetaItem(AssetMeta.LABEL, Values.create(name)),+ new MetaItem(KNXProtocol.META_KNX_DPT, Values.create(datapoint.getDPT())),+ agentLink+ ));+ if (isStatusGA) {+ attr.addMeta(new MetaItem(KNXProtocol.META_KNX_STATUS_GA, Values.create(datapoint.getMainAddress().toString())));+ } else {+ attr.addMeta(new MetaItem(KNXProtocol.META_KNX_ACTION_GA, Values.create(datapoint.getMainAddress().toString())));+ }++ if (!asset.hasAttribute(attrName)) {+ asset.addAttributes(attr);+ }+ createdAssets.put(assetName, asset);+ return asset;}+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/knx/TypeMapper.java b/agent/src/main/java/org/openremote/agent/protocol/knx/TypeMapper.javanew file mode 100644index 000000000..b0dc85ed8--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/knx/TypeMapper.java@@ -0,0 +1,391 @@+package org.openremote.agent.protocol.knx;++import java.util.HashMap;+import java.util.Map;+import java.util.logging.Level;+import java.util.logging.Logger;++import org.openremote.model.attribute.AttributeType;+import org.openremote.model.value.Value;++import tuwien.auto.calimero.KNXException;+import tuwien.auto.calimero.KNXFormatException;+import tuwien.auto.calimero.KNXIllegalArgumentException;+import tuwien.auto.calimero.datapoint.Datapoint;+import tuwien.auto.calimero.dptxlator.DPT;+import tuwien.auto.calimero.dptxlator.DPTXlator;+import tuwien.auto.calimero.dptxlator.DPTXlator1BitControlled;+import tuwien.auto.calimero.dptxlator.DPTXlator2ByteFloat;+import tuwien.auto.calimero.dptxlator.DPTXlator2ByteUnsigned;+import tuwien.auto.calimero.dptxlator.DPTXlator4ByteFloat;+import tuwien.auto.calimero.dptxlator.DPTXlator4ByteSigned;+import tuwien.auto.calimero.dptxlator.DPTXlator4ByteUnsigned;+import tuwien.auto.calimero.dptxlator.DPTXlator8BitSigned;+import tuwien.auto.calimero.dptxlator.DPTXlator8BitUnsigned;+import tuwien.auto.calimero.dptxlator.DPTXlatorBoolean;+import tuwien.auto.calimero.dptxlator.DPTXlatorDate;+import tuwien.auto.calimero.dptxlator.DPTXlatorDateTime;+import tuwien.auto.calimero.dptxlator.DPTXlatorRGB;+import tuwien.auto.calimero.dptxlator.DPTXlatorSceneControl;+import tuwien.auto.calimero.dptxlator.DPTXlatorSceneNumber;+import tuwien.auto.calimero.dptxlator.DPTXlatorString;+import tuwien.auto.calimero.dptxlator.DPTXlatorTime;+import tuwien.auto.calimero.dptxlator.TranslatorTypes;++public class TypeMapper {++ private static final Logger LOG = Logger.getLogger(TypeMapper.class.getName());++ /** map dpt to OpenRemote type */+ static private Map<String, AttributeType> dptToTypeMap;++ /** map KNX DPT to OpenRemote type */+ static private Map<AttributeType, String> typeToDptMap;++ static {+ dptToTypeMap = new HashMap<String, AttributeType>();++ // Main number 1+ dptToTypeMap.put(DPTXlatorBoolean.DPT_SWITCH.getID(), AttributeType.BOOLEAN);+ dptToTypeMap.put(DPTXlatorBoolean.DPT_BOOL.getID(), AttributeType.BOOLEAN);+ dptToTypeMap.put(DPTXlatorBoolean.DPT_OPENCLOSE.getID(), AttributeType.BOOLEAN);++ // Main number 2+ dptToTypeMap.put(DPTXlator1BitControlled.DPT_SWITCH_CONTROL.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator1BitControlled.DPT_BOOL_CONTROL.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator1BitControlled.DPT_ENABLE_CONTROL.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator1BitControlled.DPT_RAMP_CONTROL.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator1BitControlled.DPT_ALARM_CONTROL.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator1BitControlled.DPT_BINARY_CONTROL.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator1BitControlled.DPT_STEP_CONTROL.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator1BitControlled.DPT_UPDOWN_CONTROL.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator1BitControlled.DPT_OPENCLOSE_CONTROL.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator1BitControlled.DPT_START_CONTROL.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator1BitControlled.DPT_STATE_CONTROL.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator1BitControlled.DPT_INVERT_CONTROL.getID(), AttributeType.NUMBER);++ // Main number 3+ // dptToTypeMap.put(DPTXlator3BitControlled.DPT_CONTROL_DIMMING.getID(), AttributeType.IncreaseDecrease);++ // Datapoint Types "8-Bit Unsigned Value", Main number 5+ dptToTypeMap.put(DPTXlator8BitUnsigned.DPT_SCALING.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator8BitUnsigned.DPT_ANGLE.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator8BitUnsigned.DPT_PERCENT_U8.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator8BitUnsigned.DPT_DECIMALFACTOR.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator8BitUnsigned.DPT_TARIFF.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator8BitUnsigned.DPT_VALUE_1_UCOUNT.getID(), AttributeType.NUMBER);++ // Datapoint Types "8-bit Signed Value", Main number 6+ dptToTypeMap.put(DPTXlator8BitSigned.DPT_PERCENT_V8.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator8BitSigned.DPT_VALUE_1_UCOUNT.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator8BitSigned.DPT_STATUS_MODE3.getID(), AttributeType.NUMBER);++ // Datapoint Types "2-Octet Unsigned Value", Main number 7+ dptToTypeMap.put(DPTXlator2ByteUnsigned.DPT_VALUE_2_UCOUNT.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteUnsigned.DPT_TIMEPERIOD.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteUnsigned.DPT_TIMEPERIOD_10.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteUnsigned.DPT_TIMEPERIOD_100.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteUnsigned.DPT_TIMEPERIOD_SEC.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteUnsigned.DPT_TIMEPERIOD_MIN.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteUnsigned.DPT_TIMEPERIOD_HOURS.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteUnsigned.DPT_PROP_DATATYPE.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteUnsigned.DPT_LENGTH.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteUnsigned.DPT_ELECTRICAL_CURRENT.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteUnsigned.DPT_BRIGHTNESS.getID(), AttributeType.NUMBER);++ // Datapoint Types "2-Octet Float Value", Main number 9+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_TEMPERATURE.getID(), AttributeType.TEMPERATURE_CELCIUS);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_TEMPERATURE_DIFFERENCE.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_TEMPERATURE_GRADIENT.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_INTENSITY_OF_LIGHT.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_WIND_SPEED.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_AIR_PRESSURE.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_HUMIDITY.getID(), AttributeType.HUMIDITY_PERCENTAGE);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_AIRQUALITY.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_TIME_DIFFERENCE1.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_TIME_DIFFERENCE2.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_VOLTAGE.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_ELECTRICAL_CURRENT.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_POWERDENSITY.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_KELVIN_PER_PERCENT.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_POWER.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_VOLUME_FLOW.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_RAIN_AMOUNT.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_TEMP_F.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator2ByteFloat.DPT_WIND_SPEED_KMH.getID(), AttributeType.NUMBER);++ // Datapoint Types "Time", Main number 10+ dptToTypeMap.put(DPTXlatorTime.DPT_TIMEOFDAY.getID(), AttributeType.DATETIME);++ // Datapoint Types “Date”", Main number 11+ dptToTypeMap.put(DPTXlatorDate.DPT_DATE.getID(), AttributeType.DATETIME);++ // Datapoint Types "4-Octet Unsigned Value", Main number 12+ dptToTypeMap.put(DPTXlator4ByteUnsigned.DPT_VALUE_4_UCOUNT.getID(), AttributeType.NUMBER);++ // Datapoint Types "4-Octet Signed Value", Main number 13+ dptToTypeMap.put(DPTXlator4ByteSigned.DPT_COUNT.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteSigned.DPT_FLOWRATE.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteSigned.DPT_ACTIVE_ENERGY.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteSigned.DPT_APPARENT_ENERGY.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteSigned.DPT_REACTIVE_ENERGY.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteSigned.DPT_ACTIVE_ENERGY_KWH.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteSigned.DPT_APPARENT_ENERGY_KVAH.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteSigned.DPT_REACTIVE_ENERGY_KVARH.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteSigned.DPT_DELTA_TIME.getID(), AttributeType.NUMBER);++ // Datapoint Types "4-Octet Float Value", Main number 14+ dptToTypeMap.put(DPTXlator4ByteFloat.DPT_ACCELERATION_ANGULAR.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteFloat.DPT_ANGLE_DEG.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteFloat.DPT_ELECTRIC_CURRENT.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteFloat.DPT_ELECTRIC_POTENTIAL.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteFloat.DPT_FREQUENCY.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteFloat.DPT_POWER.getID(), AttributeType.NUMBER);+ dptToTypeMap.put(DPTXlator4ByteFloat.DPT_PRESSURE.getID(), AttributeType.NUMBER);++ // Datapoint Types "String", Main number 16+ dptToTypeMap.put(DPTXlatorString.DPT_STRING_8859_1.getID(), AttributeType.STRING);++ // Datapoint Types "Scene Number", Main number 17+ dptToTypeMap.put(DPTXlatorSceneNumber.DPT_SCENE_NUMBER.getID(), AttributeType.NUMBER);++ // Datapoint Types "Scene Control", Main number 18+ dptToTypeMap.put(DPTXlatorSceneControl.DPT_SCENE_CONTROL.getID(), AttributeType.NUMBER);++ // Datapoint Types "DateTime", Main number 19+ dptToTypeMap.put(DPTXlatorDateTime.DPT_DATE_TIME.getID(), AttributeType.DATETIME);++ // Datapoint Types "RGB Color", Main number 232+ dptToTypeMap.put(DPTXlatorRGB.DPT_RGB.getID(), AttributeType.COLOR_RGB);++ typeToDptMap = new HashMap<AttributeType, String>();+ typeToDptMap.put(AttributeType.BOOLEAN, DPTXlatorBoolean.DPT_SWITCH.getID());+ typeToDptMap.put(AttributeType.PERCENTAGE, DPTXlator8BitUnsigned.DPT_SCALING.getID());+ typeToDptMap.put(AttributeType.NUMBER, DPTXlator2ByteFloat.DPT_TEMPERATURE.getID());+ typeToDptMap.put(AttributeType.DATETIME, DPTXlatorTime.DPT_TIMEOFDAY.getID());+ typeToDptMap.put(AttributeType.STRING, DPTXlatorString.DPT_STRING_8859_1.getID());+ typeToDptMap.put(AttributeType.COLOR_RGB, DPTXlatorRGB.DPT_RGB.getID());+ }++ public String toDPTValue(AttributeType type, String dptID) {++ DPT dpt;+ int mainNumber = getMainNumber(dptID);+ if (mainNumber == -1) {+ LOG.warning("toDPTValue couldn't identify mainnumber in dptID: " + dptID);+ return null;+ }++ try {+ DPTXlator translator = TranslatorTypes.createTranslator(mainNumber, dptID);+ dpt = translator.getType();++ } catch (KNXException e) {+ e.printStackTrace();+ return null;+ }++ // // check for HSBType first, because it extends PercentType as well+ // if (type == AttributeType.COLOR_RGB) {+ // Color color = ((HSBType) type).toColor();+ //+ // return "r:" + Integer.toString(color.getRed()) + " g:" + Integer.toString(color.getGreen()) + " b:"+ // + Integer.toString(color.getBlue());+ // } else if (type instanceof OnOffType) {+ // return type.equals(OnOffType.OFF) ? dpt.getLowerValue() : dpt.getUpperValue();+ // } else if (type instanceof UpDownType) {+ // return type.equals(UpDownType.UP) ? dpt.getLowerValue() : dpt.getUpperValue();+ // } else if (type instanceof IncreaseDecreaseType) {+ // DPT valueDPT = ((DPTXlator3BitControlled.DPT3BitControlled) dpt).getControlDPT();+ // return type.equals(IncreaseDecreaseType.DECREASE) ? valueDPT.getLowerValue() + " 5"+ // : valueDPT.getUpperValue() + " 5";+ // } else if (type instanceof OpenClosedType) {+ // return type.equals(OpenClosedType.CLOSED) ? dpt.getLowerValue() : dpt.getUpperValue();+ // } else if (type instanceof StopMoveType) {+ // return type.equals(StopMoveType.STOP) ? dpt.getLowerValue() : dpt.getUpperValue();+ // } else if (type instanceof PercentType) {+ // return type.toString();+ // } else if (type instanceof DecimalType) {+ // switch (mainNumber) {+ // case 2:+ // DPT valueDPT = ((DPTXlator1BitControlled.DPT1BitControlled) dpt).getValueDPT();+ // switch (((DecimalType) type).intValue()) {+ // case 0:+ // return "0 " + valueDPT.getLowerValue();+ // case 1:+ // return "0 " + valueDPT.getUpperValue();+ // case 2:+ // return "1 " + valueDPT.getLowerValue();+ // default:+ // return "1 " + valueDPT.getUpperValue();+ // }+ // case 18:+ // int intVal = ((DecimalType) type).intValue();+ // if (intVal > 63) {+ // return "learn " + (intVal - 0x80);+ // } else {+ // return "activate " + intVal;+ // }+ // default:+ // return type.toString();+ // }+ // } else if (type instanceof StringType) {+ // return type.toString();+ // } else if (type instanceof DateTimeType) {+ // return formatDateTime((DateTimeType) type, dptID);+ // }++ // logger.debug("toDPTValue: Couldn't get value for {} dpt id {} (no mapping).", type, dptID);++ return null;+ }++ public Value toValue(Datapoint datapoint, byte[] data) {+ try {+ DPTXlator translator = TranslatorTypes.createTranslator(datapoint.getMainNumber(), datapoint.getDPT());+ translator.setData(data);+ String value = translator.getValue();++ String id = translator.getType().getID();+ LOG.fine("toValue datapoint DPT = " + datapoint.getDPT());++ int mainNumber = getMainNumber(id);+ if (mainNumber == -1) {+ LOG.warning("toValue: couldn't identify mainnumber in dptID: " + id);+ return null;+ }+ int subNumber = getSubNumber(id);+ if (subNumber == -1) {+ LOG.warning("toType: couldn't identify sub number in dptID: " + id);+ return null;+ }+ // /*+ // * Following code section deals with specific mapping of values from KNX to openHAB types were the String+ // * received from the DPTXlator is not sufficient to set the openHAB type or has bugs+ // */+ // switch (mainNumber) {+ // case 1:+ // DPTXlatorBoolean translatorBoolean = (DPTXlatorBoolean) translator;+ // return new BooleanValueImpl(translatorBoolean.getValueBoolean());+ //+ // case 2:+ // DPTXlator1BitControlled translator1BitControlled = (DPTXlator1BitControlled) translator;+ // int decValue = (translator1BitControlled.getControlBit() ? 2 : 0)+ // + (translator1BitControlled.getValueBit() ? 1 : 0);+ // return new NumberValueImpl(decValue);+ // case 18:+ // DPTXlatorSceneControl translatorSceneControl = (DPTXlatorSceneControl) translator;+ // int decimalValue = translatorSceneControl.getSceneNumber();+ // if (value.startsWith("learn")) {+ // decimalValue += 0x80;+ // }+ // value = String.valueOf(decimalValue);+ // break;+ // }+ //+ // Class<? extends Type> typeClass = toAttributeType(id);+ // if (typeClass == null) {+ // return null;+ // }+ //+ // if (typeClass.equals(PercentType.class)) {+ // return PercentType.valueOf(value.split(" ")[0]);+ // }+ // if (typeClass.equals(AttributeType.NUMBER)) {+ // return DecimalType.valueOf(value.split(" ")[0]);+ // }+ // if (typeClass.equals(StringType.class)) {+ // return StringType.valueOf(value);+ // }+ //+ // if (typeClass.equals(DateTimeType.class)) {+ // String date = formatDateTime(value, datapoint.getDPT());+ // if ((date == null) || (date.isEmpty())) {+ // logger.debug("toType: KNX clock msg ignored: date object null or empty {}.", date);+ // return null;+ // } else {+ // return DateTimeType.valueOf(date);+ // }+ // }+ //+ // if (typeClass.equals(HSBType.class)) {+ // // value has format of "r:<red value> g:<green value> b:<blue value>"+ // int r = Integer.parseInt(value.split(" ")[0].split(":")[1]);+ // int g = Integer.parseInt(value.split(" ")[1].split(":")[1]);+ // int b = Integer.parseInt(value.split(" ")[2].split(":")[1]);+ //+ // Color color = new Color(r, g, b);+ // return new HSBType(color);+ // }+ } catch (KNXFormatException kfe) {+ LOG.info("Translator couldn't parse data for datapoint type '" + datapoint.getDPT() + "' (KNXFormatException).");+ } catch (KNXIllegalArgumentException kiae) {+ LOG.info("Translator couldn't parse data for datapoint type '" + datapoint.getDPT() + "' (KNXIllegalArgumentException).");+ } catch (KNXException e) {+ LOG.log(Level.WARNING, "Failed creating a translator for datapoint type '" + datapoint.getDPT() + "'.", e);+ }++ return null;+ }++ static public AttributeType toAttributeType(String dptId) {+ LOG.finer("toTypeClass looking for dptId = " + dptId);+ return dptToTypeMap.get(dptId);+ }++ static public String toDPTid(AttributeType type) {+ return typeToDptMap.get(type);+ }++ /**+ * Retrieves sub number from a DTP ID such as "14.001"+ *+ * @param dptID+ * String with DPT ID+ * @return sub number or -1+ */+ private int getSubNumber(String dptID) {+ int result = -1;+ if (dptID == null) {+ throw new IllegalArgumentException("Parameter dptID cannot be null");+ }++ int dptSepratorPosition = dptID.indexOf('.');+ if (dptSepratorPosition > 0) {+ try {+ result = Integer.parseInt(dptID.substring(dptSepratorPosition + 1, dptID.length()));+ } catch (NumberFormatException nfe) {+ LOG.warning("toType couldn't identify main and/or sub number in dptID (NumberFormatException): " + dptID);+ } catch (IndexOutOfBoundsException ioobe) {+ LOG.warning("toType couldn't identify main and/or sub number in dptID (IndexOutOfBoundsException): " + dptID);+ }+ }+ return result;+ }++ /**+ * Retrieves main number from a DTP ID such as "14.001"+ *+ * @param dptID+ * String with DPT ID+ * @return main number or -1+ */+ private int getMainNumber(String dptID) {+ int result = -1;+ if (dptID == null) {+ throw new IllegalArgumentException("Parameter dptID cannot be null");+ }++ int dptSepratorPosition = dptID.indexOf('.');+ if (dptSepratorPosition > 0) {+ try {+ result = Integer.parseInt(dptID.substring(0, dptSepratorPosition));+ } catch (NumberFormatException nfe) {+ LOG.warning("toType couldn't identify main and/or sub number in dptID (NumberFormatException): " + dptID);+ } catch (IndexOutOfBoundsException ioobe) {+ LOG.warning("toType couldn't identify main and/or sub number in dptID (IndexOutOfBoundsException): " + dptID);+ }+ }+ return result;+ }+}diff --git a/agent/src/main/resources/ets_calimero_group_name.xsl b/agent/src/main/resources/ets_calimero_group_name.xslnew file mode 100644index 000000000..41f453d3c--- /dev/null+++ b/agent/src/main/resources/ets_calimero_group_name.xsl@@ -0,0 +1,146 @@+<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs">+<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>++<!-- For ETS 4 project files, replace the xmlns ending `13` with `11` -->+<xsl:template match="/" xmlns:b="http://knx.org/xml/project/13">++<xsl:for-each select="b:KNX/b:Project/b:Installations/b:Installation/b:Topology">+<datapoints>+<xsl:for-each select="b:Area/b:Line/b:DeviceInstance/b:ComObjectInstanceRefs/b:ComObjectInstanceRef">+<xsl:sort select="b:Connectors/b:Send/@GroupAddressRefId"/>+<xsl:if test="not(preceding::b:Connectors/b:Send/@GroupAddressRefId = current()/b:Connectors/b:Send/@GroupAddressRefId)">+<xsl:for-each select="b:Connectors">+<xsl:variable name="verz" select="document(concat(substring(../@RefId,0,7),'/',substring-before(../@RefId, '_O'), '.xml'))/b:KNX/b:ManufacturerData/b:Manufacturer/b:ApplicationPrograms/b:ApplicationProgram/b:Static/b:ComObjectTable/b:ComObject[@Id = ../../b:ComObjectRefs/b:ComObjectRef[@Id = current()/../@RefId]/@RefId]" />+<xsl:variable name="grosse">+<xsl:choose>+ <xsl:when test="substring-after($verz/@ObjectSize,' ') = 'Bytes'">+ <xsl:value-of select="xs:decimal(substring-before($verz/@ObjectSize,' '))*8" />+ </xsl:when>+ <xsl:otherwise>+ <xsl:value-of select="substring-before($verz/@ObjectSize,' ')" />+ </xsl:otherwise>+</xsl:choose>+</xsl:variable>++<xsl:variable name="comObjectTableDpt">+ <xsl:choose>+ <xsl:when test="starts-with($verz/@DatapointType,'DPST-')">+ <xsl:value-of select="substring-after($verz/@DatapointType, '-')" />+ </xsl:when>+ <xsl:otherwise>+ <xsl:value-of select="''" />+ </xsl:otherwise>+ </xsl:choose>+</xsl:variable>++<xsl:variable name="master" select="document('knx_master.xml')/b:KNX/b:MasterData/b:DatapointTypes/b:DatapointType[@SizeInBit = $grosse]" />+<xsl:variable name="master2" select="document('knx_master.xml')/b:KNX/b:MasterData/b:DatapointTypes/b:DatapointType/b:DatapointSubtypes/b:DatapointSubtype[@Id = current()/../@DatapointType]" />+<xsl:variable name="master3" select="document('knx_master.xml')/b:KNX/b:MasterData/b:DatapointTypes/b:DatapointType[@Id = current()/../@DatapointType]" />+<xsl:variable name="graddress" select="/b:KNX/b:Project/b:Installations/b:Installation/b:GroupAddresses/b:GroupRanges/b:GroupRange/b:GroupRange" />+<xsl:variable name="loc" select="/b:KNX/b:Project/b:Installations/b:Installation/b:GroupAddresses/b:GroupRanges/b:GroupRange/b:GroupRange" />+<datapoint>+ <xsl:attribute name="stateBased">+ <xsl:value-of select="'true'"/>+ </xsl:attribute>+ <xsl:attribute name="name">+ <xsl:for-each select="b:Send">+ <knxAddress type="group">+ <xsl:value-of select="$graddress/b:GroupAddress[@Id = current()/@GroupAddressRefId]/@Name"/>+ </knxAddress>+ </xsl:for-each>+ </xsl:attribute>+ <xsl:attribute name="mainNumber">+ <xsl:choose>+ <xsl:when test="../@DatapointType != ''">+ <xsl:choose>+ <xsl:when test="string-length(../@DatapointType) > 5">+ <xsl:value-of select="$master2/../../@Number"/>+ </xsl:when>+ <xsl:otherwise>+ <xsl:value-of select="$master3/@Number"/>+ </xsl:otherwise>+ </xsl:choose>+ </xsl:when>+ <xsl:when test="$comObjectTableDpt != ''">+ <xsl:value-of select="concat('', substring-before($comObjectTableDpt, '-'))"/>+ </xsl:when>+ <xsl:otherwise>+ <xsl:value-of select="$master[1]/@Number"/>+ </xsl:otherwise>+ </xsl:choose>+ </xsl:attribute>+ <xsl:attribute name="dptID">+ <xsl:choose>+ <xsl:when test="../@DatapointType != ''">+ <xsl:choose>+ <xsl:when test="string-length(../@DatapointType) > 5">+ <xsl:value-of select="concat($master2/../../@Number, '.',format-number($master2/@Number, '000') )"/>+ </xsl:when>+ <xsl:otherwise>+ <xsl:value-of select="concat($master3/@Number, '.001')"/>+ </xsl:otherwise>+ </xsl:choose>+ </xsl:when>+ <xsl:when test="$comObjectTableDpt != ''">+ <xsl:value-of select="concat(substring-before($comObjectTableDpt, '-'), '.',+ format-number(xs:decimal(substring-after($comObjectTableDpt, '-')), '000') )"/>+ </xsl:when>+ <xsl:otherwise>+ <xsl:value-of select="concat($master[1]/@Number,'.',format-number($master[1]/b:DatapointSubtypes/b:DatapointSubtype[1]/@Number, '000'))"/>+ </xsl:otherwise>+ </xsl:choose>+ </xsl:attribute>+ <xsl:attribute name="priority">+ <xsl:choose>+ <xsl:when test="../@Priority">+ <xsl:value-of select="../@Priority"/>+ </xsl:when>+ <xsl:when test="$verz/@Priority">+ <xsl:value-of select="$verz/@Priority"/>+ </xsl:when>+ <xsl:otherwise>+ <xsl:text>low</xsl:text>+ </xsl:otherwise>+ </xsl:choose>+ </xsl:attribute>+ <xsl:if test="string-length(../@Description) > 0">+ <xsl:comment><xsl:value-of select="../@Description"/></xsl:comment>+ </xsl:if>+ <xsl:for-each select="b:Send">+ <knxAddress type="group">+ <xsl:value-of select="$graddress/b:GroupAddress[@Id = current()/@GroupAddressRefId]/@Address"/>+ </knxAddress>+ </xsl:for-each>+ <expiration timeout="0"/>+ <location>+ <xsl:for-each select="b:Send">+ <xsl:value-of select="concat($loc/b:GroupAddress[@Id = current()/@GroupAddressRefId]/../../@Name,'/',$loc/b:GroupAddress[@Id = current()/@GroupAddressRefId]/../@Name)"/>+ </xsl:for-each>+ </location>+ <xsl:choose>+ <xsl:when test="b:Receive">+ <updatingAddresses>+ <xsl:for-each select="b:Receive">+ <knxAddress type="group">+ <xsl:value-of select="$graddress/b:GroupAddress[@Id = current()/@GroupAddressRefId]/@Address"/>+ </knxAddress>+ </xsl:for-each>+ </updatingAddresses>+ </xsl:when>+ <xsl:otherwise>+ <updatingAddresses>+ <xsl:text></xsl:text>+ </updatingAddresses>+ </xsl:otherwise>+ </xsl:choose>+ <invalidatingAddresses>+ <xsl:text></xsl:text>+ </invalidatingAddresses>+</datapoint>+</xsl:for-each>+</xsl:if>+</xsl:for-each>+</datapoints>+</xsl:for-each>+</xsl:template>+</xsl:stylesheet>diff --git a/gradle.properties b/gradle.propertiesindex 5faec0106..842fb19e7 100644--- a/gradle.properties+++ b/gradle.properties@@ -32,4 +32,5 @@ quartzVersion= 2.2.3calimeroVersion = 2.4-SNAPSHOTclingVersion = 2.1.1uuidGeneratorVersion = 3.1.3-nrjavaserialVersion = 3.13.0\ No newline at end of file+nrjavaserialVersion = 3.13.0+saxonHEVersion = 9.8.0-3\ No newline at end of filediff --git a/manager/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy b/manager/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovynew file mode 100644index 000000000..5567e47da--- /dev/null+++ b/manager/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy@@ -0,0 +1,129 @@+/*+ * 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 tuwien.auto.calimero.server.knxnetip.DefaultServiceContainer++import static org.openremote.model.asset.AssetMeta.DESCRIPTION+import static org.openremote.model.asset.AssetMeta.LABEL+import static org.openremote.model.Constants.*+import static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD+import static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULT+import static org.openremote.container.util.MapAccess.getString++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+import org.openremote.manager.server.agent.AgentService+import org.openremote.manager.server.asset.AssetProcessingService+import org.openremote.manager.server.asset.AssetStorageService+import org.openremote.manager.server.asset.ServerAsset+import org.openremote.manager.shared.agent.AgentResource+import org.openremote.model.Constants+import org.openremote.model.asset.AssetAttribute+import org.openremote.model.asset.AssetMeta+import org.openremote.model.asset.AssetType+import org.openremote.model.asset.agent.ProtocolConfiguration+import org.openremote.model.attribute.*+import org.openremote.model.value.Values+import org.openremote.model.file.FileInfo+import org.openremote.test.KNXTestingNetworkLink+import org.openremote.test.ManagerContainerTrait+import spock.lang.Ignore+import spock.lang.Specification+import spock.util.concurrent.PollingConditions+import java.util.Base64+++import java.nio.file.Files++/**+ * This tests the KNX protocol import routine+ */+class KNXImportTest extends Specification implements ManagerContainerTrait {++ def "Check KNX protocol import"() {++ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 10, initialDelay: 1, delay: 1)++ and: "the container is started"+ def serverPort = findEphemeralPort()+ def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def agentService = container.getService(AgentService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def knxProtocol = container.getService(KNXProtocol.class)++ when: "a KNX agent that uses the KNX protocol is created. to test the import we don't need a valid protocol configuration"+ def knxAgent = new ServerAsset()+ knxAgent.setName("KNX Agent")+ knxAgent.setType(AssetType.AGENT)+ knxAgent.setAttributes(+ ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute("knxConfigError1"), KNXProtocol.PROTOCOL_NAME)+ )+ knxAgent.setRealmId(Constants.MASTER_REALM)+ knxAgent = assetStorageService.merge(knxAgent)++ then: "the protocol configurations should be linked and their deployment status should be available in the agent service"+ conditions.eventually {+ assert agentService.getProtocolDeploymentStatus(knxAgent.getAttribute("knxConfigError1").get().getReferenceOrThrow()) == ConnectionStatus.ERROR+ }++ when: "an authenticated admin user"+ def accessToken = authenticate(+ container,+ MASTER_REALM,+ KEYCLOAK_CLIENT_ID,+ MASTER_REALM_ADMIN_USER,+ getString(container.getConfig(), SETUP_KEYCLOAK_ADMIN_PASSWORD, SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULT)+ ).token++ and: "the agent resource"+ def agentResource = getClientTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AgentResource.class)++ and: "the container is running"+ container.isRunning()++ then: "the container should settle down and the agent should be deployed"+ conditions.eventually {+ assert agentService.getAgents().containsKey(knxAgent.id)+ assert noEventProcessedIn(assetProcessingService, 500)+ }++ when: "discovery is requested with a ETS project file"+ byte[] data = Files.readAllBytes(new File("manager/test/src/test/resources/knx-import-testproject.knxproj").toPath());+ String base64Content =","+ Base64.getEncoder().encodeToString(data)+ def fileInfo = new FileInfo("knx-import-testproject.knxproj", base64Content, true)+ def assets = agentResource.importLinkedAttributes(null, knxAgent.getId(), "knxConfigError1", null, null, fileInfo)++ then: "the new things and attributes should be created"+ conditions.eventually {+ assert assets.length == 10+ //TODO+ }++ cleanup: "the server should be stopped"+ stopContainer(container)++ }+}\ No newline at end of filediff --git a/manager/test/src/test/resources/knx-import-testproject.knxproj b/manager/test/src/test/resources/knx-import-testproject.knxprojnew file mode 100644index 000000000..3d27f7a10Binary files /dev/null and b/manager/test/src/test/resources/knx-import-testproject.knxproj differ