Skip to content

armgit / core

Public Imported from GitHub
0

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

Added IKEA Tradfri protocol (#191)

RensvdLindenb8ed94ba6770
diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt
index e06982de6..efe9c4078 100644
--- a/CONTRIBUTORS.txt
+++ b/CONTRIBUTORS.txt
@@ -2,3 +2,5 @@ Christian Bauer <[email protected]>
Richard Turner <[email protected]>
Michael Rademaker <[email protected]>
Robin Dekkers <[email protected]>
+Rens van der Linden
+Stijn Groenen
diff --git a/agent/build.gradle b/agent/build.gradle
index 5464c019c..fb25789f2 100644
--- a/agent/build.gradle
+++ b/agent/build.gradle
@@ -28,6 +28,11 @@ dependencies {
}
compile "net.sf.saxon:Saxon-HE:$saxonHEVersion"
+
+ //IKEA Tradfri agent dependencies
+ compile "org.eclipse.californium:californium-core:$californiumCoreVersion"
+ compile "org.eclipse.californium:scandium:$californiumScandiumVersion"
+
}
jar {
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriAsset.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriAsset.java
new file mode 100644
index 000000000..91cf45b07
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriAsset.java
@@ -0,0 +1,68 @@
+package org.openremote.agent.protocol.tradfri;
+
+import org.openremote.agent.protocol.ProtocolAssetService;
+import org.openremote.agent.protocol.tradfri.device.Device;
+import org.openremote.container.util.UniqueIdentifierGenerator;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.attribute.MetaItem;
+
+/**
+ * Abstract class for TRÅDFRI assets
+ */
+public abstract class TradfriAsset extends Asset {
+
+ /**
+ * The device.
+ */
+ protected Device device;
+
+ /**
+ * The asset service.
+ */
+ protected ProtocolAssetService assetService;
+
+ /**
+ * The agent link.
+ */
+ protected MetaItem agentLink;
+
+ /**
+ * Construct the TradfriAsset class.
+ * @param parentId the parent id.
+ * @param device the device.
+ * @param assetType the asset type.
+ * @param assetService the asset service.
+ */
+ public TradfriAsset(String parentId, Device device, AssetType assetType, ProtocolAssetService assetService, MetaItem agentLink) {
+ super(device.getName() != null && !device.getName().isEmpty() ? device.getName() : "Unnamed " + device.getInstanceId(), assetType);
+ this.device = device;
+ this.assetService = assetService;
+ this.agentLink = agentLink;
+ if(parentId != null && !parentId.isEmpty()){
+ setParentId(parentId);
+ setRealm(assetService.findAsset(parentId).getRealm());
+ }
+ setId(UniqueIdentifierGenerator.generateId("tradfri_" + device.getInstanceId()));
+ this.createAssetAttributes();
+ this.setInitialValues();
+ this.createEventHandlers();
+ device.enableObserve();
+ assetService.mergeAsset(this);
+ }
+
+ /**
+ * Method to create the asset attributes
+ */
+ public abstract void createAssetAttributes();
+
+ /**
+ * Method to create the event handlers
+ */
+ public abstract void createEventHandlers();
+
+ /**
+ * Method to set the initial values
+ */
+ public abstract void setInitialValues();
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriConnection.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriConnection.java
new file mode 100644
index 000000000..2d002dc78
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriConnection.java
@@ -0,0 +1,185 @@
+package org.openremote.agent.protocol.tradfri;
+
+import org.openremote.agent.protocol.tradfri.device.Device;
+import org.openremote.agent.protocol.tradfri.device.Gateway;
+import org.openremote.agent.protocol.tradfri.device.Light;
+import org.openremote.agent.protocol.tradfri.device.Plug;
+import org.openremote.agent.protocol.tradfri.util.Credentials;
+
+import org.openremote.agent.protocol.ProtocolExecutorService;
+import org.openremote.model.asset.agent.ConnectionStatus;
+import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.syslog.SyslogCategory;
+
+import java.util.function.Consumer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Logger;
+
+import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
+
+/**
+ * The class that represents the configuration for the IKEA TRÅDFRI connection.
+ */
+public class TradfriConnection {
+
+ /**
+ * The connection status, the default is disconnected
+ */
+ protected ConnectionStatus connectionStatus = ConnectionStatus.DISCONNECTED;
+
+ /**
+ * The connection status consumers of the IKEA TRÅDFRI connection
+ */
+ protected final List<Consumer<ConnectionStatus>> connectionStatusConsumers = new ArrayList<>();
+
+ /**
+ * The executor service of the IKEA TRÅDFRI connection
+ */
+ protected final ProtocolExecutorService executorService;
+
+ /**
+ * The IP address of the gateway
+ */
+ protected final String gatewayIp;
+
+ /**
+ * The security code that's needed to connect to the gateway.
+ */
+ protected final String securityCode;
+
+ /**
+ * The logger for the IKEA TRÅDFRI connection.
+ */
+ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, TradfriConnection.class);
+
+ /**
+ * The IKEA TRÅDFRI gateway.
+ */
+ private Gateway gateway;
+
+ /**
+ * Construct the TradfriConnection class.
+ * @param gatewayIp the IP address of the gateway.
+ * @param securityCode the security code to connect to the gateway.
+ * @param executorService the executor service.
+ */
+ public TradfriConnection(String gatewayIp, String securityCode, ProtocolExecutorService executorService) {
+ this.gatewayIp = gatewayIp;
+ this.securityCode = securityCode;
+ this.executorService = executorService;
+ }
+
+ /**
+ * Handles the connection.
+ * @return the gateway.
+ */
+ public synchronized Gateway connect() {
+ if (connectionStatus == ConnectionStatus.CONNECTED || connectionStatus == ConnectionStatus.CONNECTING) {
+ LOG.finest("Already connected or connection in progress");
+ }
+
+ onConnectionStatusChanged(ConnectionStatus.CONNECTING);
+
+ try {
+ Gateway gateway = new Gateway(gatewayIp);
+ gateway.setTimeout(10000L);
+ Credentials credentials = gateway.connect(securityCode);
+ if (credentials != null) {
+ if (gateway.enableObserve()) {
+ this.gateway = gateway;
+ onConnectionStatusChanged(ConnectionStatus.CONNECTED);
+ return gateway;
+ }
+ }
+ }
+ catch (Exception exception) {
+ LOG.warning("An exception occured when connecting to Tradfri gateway: " + exception);
+ }
+ return null;
+ }
+
+ /**
+ * Updates the connection status.
+ * @param connectionStatus the connection status.
+ */
+ protected synchronized void onConnectionStatusChanged(ConnectionStatus connectionStatus) {
+ this.connectionStatus = connectionStatus;
+
+ connectionStatusConsumers.forEach(
+ consumer -> consumer.accept(connectionStatus)
+ );
+ }
+
+ /**
+ * Adds a connection status consumer.
+ * @param connectionStatusConsumer the connection status consumer.
+ */
+ public synchronized void addConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {
+ if (!connectionStatusConsumers.contains(connectionStatusConsumer)) {
+ connectionStatusConsumers.add(connectionStatusConsumer);
+ }
+ }
+
+ /**
+ * Handles the disconnection.
+ */
+ public synchronized void disconnect() {
+ if (connectionStatus != ConnectionStatus.CONNECTED) return;
+ LOG.finest("Disconnecting");
+ onConnectionStatusChanged(ConnectionStatus.DISCONNECTING);
+ if(gateway.disableObserve()){
+ onConnectionStatusChanged(ConnectionStatus.DISCONNECTED);
+ }
+ }
+
+ /**
+ * Removes the connection status consumer.
+ * @param connectionStatusConsumer the connection status consumer.
+ */
+ public synchronized void removeConnectionStatusConsumer(java.util.function.Consumer<ConnectionStatus> connectionStatusConsumer) {
+ connectionStatusConsumers.remove(connectionStatusConsumer);
+ }
+
+ /**
+ * Method to update the values of the device attributes,
+ * based on the values entered in the User Interface.
+ * @param device the device to which the update applies.
+ * @param event the event representing the update.
+ */
+ public void controlDevice(Device device, AttributeEvent event) {
+ try {
+ if (this.connectionStatus == ConnectionStatus.CONNECTED && event.getValue().isPresent()) {
+ if (device.isLight()){
+ Light light = device.toLight();
+ switch (event.getAttributeName()) {
+ case "lightDimLevel":
+ light.setBrightness((int) Float.parseFloat(event.getValue().get().toString()));
+ break;
+ case "lightStatus":
+ light.setOn(Boolean.parseBoolean(event.getValue().get().toString()));
+ break;
+ case "colorGBW":
+ String digits = event.getValue().get().toString().replaceAll("[^0-9.,]+","");
+ String[] numbers = digits.split(",");
+ light.setColourRGB(Integer.parseInt(numbers[0]), Integer.parseInt(numbers[1]), Integer.parseInt(numbers[2]));
+ break;
+ case "colorTemperature":
+ light.setColourTemperature((int) Float.parseFloat(event.getValue().get().toString()));
+ break;
+ }
+ }
+ else if (device.isPlug()) {
+ Plug plug = device.toPlug();
+ switch (event.getAttributeName()){
+ case "plugStatus":
+ plug.setOn(Boolean.parseBoolean(event.getValue().get().toString()));
+ break;
+ }
+ }
+ }
+ } catch (Exception exception) {
+ LOG.severe(exception.getMessage());
+ }
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriLightAsset.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriLightAsset.java
new file mode 100644
index 000000000..1015a0ae0
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriLightAsset.java
@@ -0,0 +1,159 @@
+package org.openremote.agent.protocol.tradfri;
+
+import org.openremote.agent.protocol.ProtocolAssetService;
+import org.openremote.agent.protocol.tradfri.device.Light;
+import org.openremote.agent.protocol.tradfri.device.event.*;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.attribute.MetaItem;
+import org.openremote.model.value.Values;
+
+import java.util.Optional;
+
+import static org.openremote.model.attribute.AttributeValueType.NUMBER;
+import static org.openremote.model.attribute.MetaItemType.*;
+
+public class TradfriLightAsset extends TradfriAsset {
+
+ /**
+ * Construct the TradfriLightAsset class.
+ * @param parentId parent id.
+ * @param agentLink the agent link.
+ * @param light the light.
+ * @param assetService the asset service.
+ */
+ public TradfriLightAsset(String parentId, MetaItem agentLink, Light light, ProtocolAssetService assetService) {
+ super(parentId, light, AssetType.LIGHT, assetService, agentLink);
+ }
+
+ /**
+ * Method to create the asset attributes
+ */
+ @Override
+ public void createAssetAttributes() {
+ Optional<AssetAttribute> lightDimLevelOptional = getAttribute("lightDimLevel");
+ if (lightDimLevelOptional.isPresent()) {
+ AssetAttribute lightDimLevel = lightDimLevelOptional.get();
+ lightDimLevel.setType(NUMBER);
+ lightDimLevel.addMeta(
+ new MetaItem(RANGE_MIN, Values.create(0)),
+ new MetaItem(RANGE_MAX, Values.create(254)),
+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),
+ new MetaItem(ACCESS_RESTRICTED_WRITE, Values.create(true)),
+ agentLink
+ );
+ lightDimLevel.setDescription("The brightness (0 - 254) of the TRÅDFRI light (Only for dimmable lights)");
+ lightDimLevel.setReadOnly(false);
+ }
+
+ Optional<AssetAttribute> lightStatusOptional = getAttribute("lightStatus");
+ if(lightStatusOptional.isPresent()){
+ AssetAttribute lightStatus = lightStatusOptional.get();
+ lightStatus.addMeta(
+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),
+ new MetaItem(ACCESS_RESTRICTED_WRITE, Values.create(true)),
+ agentLink
+ );
+ lightStatus.setDescription("The state of the TRÅDFRI light (Checked means on, unchecked means off)");
+ lightStatus.setReadOnly(false);
+ }
+
+ Optional<AssetAttribute> colorGBWOptional = getAttribute("colorGBW");
+ if(colorGBWOptional.isPresent()){
+ AssetAttribute colorGBW = colorGBWOptional.get();
+ colorGBW.addMeta(
+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),
+ new MetaItem(ACCESS_RESTRICTED_WRITE, Values.create(true)),
+ agentLink
+ );
+ colorGBW.setDescription("The color of the TRÅDFRI light (Only for RGB lights)");
+ colorGBW.setReadOnly(false);
+ }
+
+ AssetAttribute colorTemperature = new AssetAttribute("colorTemperature", NUMBER, Values.create(0));
+ colorTemperature.addMeta(
+ new MetaItem(RANGE_MIN, Values.create(250)),
+ new MetaItem(RANGE_MAX, Values.create(454)),
+ new MetaItem(LABEL, Values.create("Color Temperature")),
+ new MetaItem(DESCRIPTION, Values.create("The color temperature (250 - 454) of the TRÅDFRI light (Only for white spectrum lights)")),
+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),
+ new MetaItem(ACCESS_RESTRICTED_WRITE, Values.create(true)),
+ new MetaItem(READ_ONLY, Values.create(false)),
+ agentLink
+ );
+ addAttributes(colorTemperature);
+ }
+
+ /**
+ * Method to create the event handlers
+ */
+ @Override
+ public void createEventHandlers() {
+ Asset asset = this;
+ EventHandler<LightChangeOnEvent> lightOnOffEventHandler = new EventHandler<LightChangeOnEvent>() {
+ @Override
+ public void handle(LightChangeOnEvent event) {
+ Optional<AssetAttribute> lightStatus = getAttribute("lightStatus");
+ Light light = device.toLight();
+ if(lightStatus.isPresent() && light.getOn() != null) lightStatus.get().setValue(Values.create(light.getOn()));
+ assetService.mergeAsset(asset);
+ }
+ };
+
+ EventHandler<LightChangeBrightnessEvent> lightBrightnessEventHandler = new EventHandler<LightChangeBrightnessEvent>() {
+ @Override
+ public void handle(LightChangeBrightnessEvent event) {
+ Optional<AssetAttribute> lightDimLevel = getAttribute("lightDimLevel");
+ Light light = device.toLight();
+ if(lightDimLevel.isPresent() && light.getBrightness() != null) lightDimLevel.get().setValue(Values.create(light.getBrightness()));
+ assetService.mergeAsset(asset);
+ }
+ };
+
+ EventHandler<LightChangeColourEvent> lightColourChangeEventHandler = new EventHandler<LightChangeColourEvent>() {
+ @Override
+ public void handle(LightChangeColourEvent event) {
+ Optional<AssetAttribute> colorGBW = getAttribute("colorGBW");
+ Light light = device.toLight();
+ if(colorGBW.isPresent() && light.getColourRGB() != null) colorGBW.get().setValue(Values.createObject().put("red", light.getColourRGB().getRed()).put("green", light.getColourRGB().getGreen()).put("blue", light.getColourRGB().getBlue()));
+ assetService.mergeAsset(asset);
+ }
+ };
+
+ EventHandler<LightChangeColourTemperatureEvent> lightColorTemperatureEventHandler = new EventHandler<LightChangeColourTemperatureEvent>() {
+ @Override
+ public void handle(LightChangeColourTemperatureEvent event) {
+ Optional<AssetAttribute> colorTemperature = getAttribute("colorTemperature");
+ Light light = device.toLight();
+ if(colorTemperature.isPresent() && light.getColourTemperature() != null) colorTemperature.get().setValue(Values.create(light.getColourTemperature()));
+ assetService.mergeAsset(asset);
+ }
+ };
+ Light light = device.toLight();
+ light.addEventHandler(lightOnOffEventHandler);
+ light.addEventHandler(lightBrightnessEventHandler);
+ light.addEventHandler(lightColourChangeEventHandler);
+ light.addEventHandler(lightColorTemperatureEventHandler);
+ }
+
+ /**
+ * Method to set the initial values
+ */
+ @Override
+ public void setInitialValues() {
+ Light light = device.toLight();
+
+ Optional<AssetAttribute> lightStatus = getAttribute("lightStatus");
+ if(lightStatus.isPresent() && light.getOn() != null) lightStatus.get().setValue(Values.create(light.getOn()));
+
+ Optional<AssetAttribute> lightDimLevel = getAttribute("lightDimLevel");
+ if(lightDimLevel.isPresent() && light.getBrightness() != null) lightDimLevel.get().setValue(Values.create(light.getBrightness()));
+
+ Optional<AssetAttribute> colorGBW = getAttribute("colorGBW");
+ if(colorGBW.isPresent() && light.getColourRGB() != null) colorGBW.get().setValue(Values.createObject().put("red", light.getColourRGB().getRed()).put("green", light.getColourRGB().getGreen()).put("blue", light.getColourRGB().getBlue()));
+
+ Optional<AssetAttribute> colorTemperature = getAttribute("colorTemperature");
+ if(colorTemperature.isPresent() && light.getColourTemperature() != null) colorTemperature.get().setValue(Values.create(light.getColourTemperature()));
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriPlugAsset.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriPlugAsset.java
new file mode 100644
index 000000000..789aa01d4
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriPlugAsset.java
@@ -0,0 +1,77 @@
+package org.openremote.agent.protocol.tradfri;
+
+import org.openremote.agent.protocol.ProtocolAssetService;
+import org.openremote.agent.protocol.tradfri.device.Plug;
+import org.openremote.agent.protocol.tradfri.device.event.EventHandler;
+import org.openremote.agent.protocol.tradfri.device.event.PlugChangeOnEvent;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.attribute.MetaItem;
+import org.openremote.model.value.Values;
+
+import java.util.Optional;
+
+import static org.openremote.model.attribute.AttributeValueType.BOOLEAN;
+import static org.openremote.model.attribute.MetaItemType.*;
+
+public class TradfriPlugAsset extends TradfriAsset {
+
+ /**
+ * Construct the TradfriPlugAsset class
+ * @param parentId the parent id.
+ * @param agentLink the agent link.
+ * @param plug the plug.
+ * @param assetService the asset service.
+ */
+ public TradfriPlugAsset(String parentId, MetaItem agentLink, Plug plug, ProtocolAssetService assetService) {
+ super(parentId, plug, AssetType.THING, assetService, agentLink);
+ }
+
+ /**
+ * Method to create the asset attributes
+ */
+ @Override
+ public void createAssetAttributes() {
+ AssetAttribute plugStatus = new AssetAttribute("plugStatus", BOOLEAN, Values.create(false));
+ plugStatus.addMeta(
+ new MetaItem(LABEL, Values.create("Plug Status")),
+ new MetaItem(DESCRIPTION, Values.create("The state of the TRÅDFRI plug (Checked means on, unchecked means off)")),
+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),
+ new MetaItem(ACCESS_RESTRICTED_WRITE, Values.create(true)),
+ new MetaItem(READ_ONLY, Values.create(false)),
+ new MetaItem(RULE_STATE, Values.create(true)),
+ new MetaItem(STORE_DATA_POINTS, Values.create(true)),
+ agentLink
+ );
+ setAttributes(plugStatus);
+ }
+
+ /**
+ * Method to create the event handlers
+ */
+ @Override
+ public void createEventHandlers() {
+ Asset asset = this;
+ EventHandler<PlugChangeOnEvent> plugOnOffEventHandler = new EventHandler<PlugChangeOnEvent>() {
+ @Override
+ public void handle(PlugChangeOnEvent event) {
+ Optional<AssetAttribute> plugStatus = getAttribute("plugStatus");
+ Plug plug = device.toPlug();
+ if(plugStatus.isPresent() && plug.getOn() != null) plugStatus.get().setValue(Values.create(plug.getOn()));
+ assetService.mergeAsset(asset);
+ }
+ };
+ device.addEventHandler(plugOnOffEventHandler);
+ }
+
+ /**
+ * Method to set the initial values
+ */
+ @Override
+ public void setInitialValues() {
+ Plug plug = device.toPlug();
+ Optional<AssetAttribute> plugStatus = getAttribute("plugStatus");
+ if(plugStatus.isPresent() && plug.getOn() != null) plugStatus.get().setValue(Values.create(plug.getOn()));
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriProtocol.java
new file mode 100644
index 000000000..0b3fa534f
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriProtocol.java
@@ -0,0 +1,394 @@
+package org.openremote.agent.protocol.tradfri;
+
+import org.openremote.agent.protocol.tradfri.device.Device;
+import org.openremote.agent.protocol.tradfri.device.Gateway;
+import org.openremote.agent.protocol.tradfri.device.Light;
+import org.openremote.agent.protocol.tradfri.device.Plug;
+
+import org.openremote.agent.protocol.AbstractProtocol;
+import org.openremote.agent.protocol.tradfri.device.event.*;
+import org.openremote.container.util.UniqueIdentifierGenerator;
+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.asset.agent.AgentLink;
+import org.openremote.model.asset.agent.ConnectionStatus;
+import org.openremote.model.attribute.*;
+import org.openremote.model.syslog.SyslogCategory;
+import org.openremote.model.util.Pair;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.ValueType;
+
+import java.util.*;
+import java.util.logging.Logger;
+import java.util.function.Consumer;
+
+import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
+import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;
+import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
+import static org.openremote.model.util.TextUtil.isNullOrEmpty;
+
+/**
+ * The class that represents the configuration for the IKEA TRÅDFRI protocol.
+ */
+public class TradfriProtocol extends AbstractProtocol {
+
+ /**
+ * The logger for the IKEA TRÅDFRI protocol.
+ */
+ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, TradfriProtocol.class);
+
+ /**
+ * The protocol name for the IKEA TRÅDFRI protocol.
+ */
+ public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":tradfri";
+
+ /**
+ * The display name for the IKEA TRÅDFRI protocol.
+ */
+ public static final String PROTOCOL_DISPLAY_NAME = "IKEA TRÅDFRI";
+
+ /**
+ * The meta gateway host for the IKEA TRÅDFRI protocol.
+ */
+ public static final String META_TRADFRI_GATEWAY_HOST = PROTOCOL_NAME + ":gatewayHost";
+
+ /**
+ * The meta security code for the IKEA TRÅDFRI protocol
+ * This security code is used when connecting to the gateway.
+ */
+ public static final String META_TRADFRI_SECURITY_CODE = PROTOCOL_NAME + ":securityCode";
+
+ /**
+ * The current version of the IKEA TRÅDFRI protocol
+ */
+ protected static final String VERSION = "1.0";
+
+ /**
+ * The protocol meta item descriptors that are used to connect to the gateway.
+ * The first MetaItemDescriptorImpl is used to hold the entered IP address of the Gateway.
+ * The second MetaItemDescriptorImpl is used to hold the entered security code (needed to connect to the gateway).
+ */
+ protected static final List<MetaItemDescriptor> PROTOCOL_CONFIG_META_ITEM_DESCRIPTORS = Arrays.asList(
+ new MetaItemDescriptorImpl(META_TRADFRI_GATEWAY_HOST, ValueType.STRING, false, null, null, 1, null, false, null, null, null),
+ new MetaItemDescriptorImpl(META_TRADFRI_SECURITY_CODE, ValueType.STRING, false, null, null, 1, null, false, null, null, null)
+ );
+
+ /**
+ * Map to store/manage the connections to the gateway.
+ */
+ final protected Map<String, TradfriConnection> tradfriConnections = new HashMap<>();
+
+ /**
+ * Map to store/manage the TRÅDFRI devices.
+ */
+ final protected HashMap<String, Device> tradfriDevices = new HashMap<>();
+
+ /**
+ * Map to store/manage the consumer of the connection status.
+ */
+ final protected Map<AttributeRef, Consumer<ConnectionStatus>> statusConsumerMap = new HashMap<>();
+
+ /**
+ * Map to store/manage the attributes of the TRÅDFRI devices.
+ */
+ final protected Map<AttributeRef, Pair<TradfriConnection, Device>> attributeMap = new HashMap<>();
+
+ /**
+ * Gets the name of the protocol.
+ * @return the name of the protocol.
+ */
+ @Override
+ public String getProtocolName() {
+ return PROTOCOL_NAME;
+ }
+
+ /**
+ * Gets the display name of the protocol.
+ * @return the display name of the protocol.
+ */
+ @Override
+ public String getProtocolDisplayName() {
+ return PROTOCOL_DISPLAY_NAME;
+ }
+
+ /**
+ * Gets the current version number of the protocol.
+ * @return the current version number of the protocol.
+ */
+ @Override
+ public String getVersion() {
+ return VERSION;
+ }
+
+ /**
+ * Gets the protocol configuration template.
+ * @return the configuration template of the protocol.
+ */
+ @Override
+ public AssetAttribute getProtocolConfigurationTemplate() {
+ return super.getProtocolConfigurationTemplate()
+ .addMeta(
+ new MetaItem(META_TRADFRI_GATEWAY_HOST, null),
+ new MetaItem(META_TRADFRI_SECURITY_CODE, null)
+ );
+ }
+
+ /**
+ * Gets the protocol configuration meta item descriptors.
+ * @return the protocol configuration meta item descriptors.
+ */
+ @Override
+ protected List<MetaItemDescriptor> getProtocolConfigurationMetaItemDescriptors() {
+ return PROTOCOL_CONFIG_META_ITEM_DESCRIPTORS;
+ }
+
+ /**
+ * Gets the linked attribute meta item descriptors.
+ * @return the linked attribute meta item descriptors.
+ */
+ @Override
+ protected List<MetaItemDescriptor> getLinkedAttributeMetaItemDescriptors() {
+ return null;
+ }
+
+ /**
+ * Validates the protocol configuration.
+ * @param protocolConfiguration the protocol configuration
+ * @return the attribute validation result.
+ */
+ @Override
+ public AttributeValidationResult validateProtocolConfiguration(AssetAttribute protocolConfiguration){
+ AttributeValidationResult result = super.validateProtocolConfiguration(protocolConfiguration);
+ if (result.isValid()) {
+ boolean ipFound = false;
+ if (protocolConfiguration.getMeta() != null && !protocolConfiguration.getMeta().isEmpty()) {
+ for (int i = 0; i < protocolConfiguration.getMeta().size(); i++) {
+ MetaItem actionMetaItem = protocolConfiguration.getMeta().get(i);
+ if (isMetaNameEqualTo(actionMetaItem, META_TRADFRI_GATEWAY_HOST)) {
+ ipFound = true;
+ if (isNullOrEmpty(actionMetaItem.getValueAsString().orElse(null))) {
+ result.addMetaFailure(
+ new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_VALUE_IS_REQUIRED, ValueType.STRING.name())
+ );
+ }
+ }
+ }
+ }
+ if (!ipFound) {
+ result.addMetaFailure(
+ new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_MISSING, META_TRADFRI_GATEWAY_HOST)
+ );
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Manages the configuration of the protocol.
+ * Checks if assets are not duplicated, makes the connection to the gateway,
+ * retrieves the devices, and adds a event handler for the gateway.
+ * @param protocolConfiguration the protocol configuration.
+ */
+ @Override
+ protected void doLinkProtocolConfiguration(Asset agent, AssetAttribute protocolConfiguration) {
+ Optional<String> gatewayIpParam = protocolConfiguration.getMetaItem(META_TRADFRI_GATEWAY_HOST).flatMap(AbstractValueHolder::getValueAsString);
+ if (!gatewayIpParam.isPresent()) {
+ LOG.severe("No Tradfri gateway IP address provided for protocol configuration: " + protocolConfiguration);
+ updateStatus(protocolConfiguration.getReferenceOrThrow(), ConnectionStatus.ERROR_CONFIGURATION);
+ return;
+ }
+
+ String securityCode = protocolConfiguration.getMetaItem(META_TRADFRI_SECURITY_CODE).flatMap(AbstractValueHolder::getValueAsString).orElse("");
+ AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();
+ MetaItem agentLink = AgentLink.asAgentLinkMetaItem(protocolConfiguration.getReferenceOrThrow());
+ synchronized (tradfriConnections) {
+ Consumer<ConnectionStatus> statusConsumer = status -> updateStatus(protocolRef, status);
+
+ TradfriConnection tradfriConnection = tradfriConnections.computeIfAbsent(
+ gatewayIpParam.get(), gatewayIp ->
+ new TradfriConnection(gatewayIp, securityCode, executorService)
+ );
+ tradfriConnection.addConnectionStatusConsumer(statusConsumer);
+ Gateway gateway = tradfriConnection.connect();
+ if(gateway != null){
+ Device[] devices = gateway.getDevices();
+ if(devices != null){
+ addDevices(devices, agentLink, protocolConfiguration);
+ EventHandler<GatewayEvent> gatewayEventHandler = new EventHandler<GatewayEvent>() {
+ @Override
+ public void handle(GatewayEvent event) {
+ Device[] newDevices = event.getGateway().getDevices();
+ if(newDevices == null) return;
+ ArrayList<Device> added = new ArrayList<>();
+ HashMap<String, Device> removed = (HashMap<String, Device>) tradfriDevices.clone();
+ for (Device device : newDevices) {
+ String name = UniqueIdentifierGenerator.generateId("tradfri_" + device.getInstanceId());
+ if (tradfriDevices.containsKey(name)) {
+ removed.remove(name);
+ } else {
+ added.add(device);
+ }
+ }
+ addDevices(added.toArray(new Device[added.size()]), agentLink, protocolConfiguration);
+ for (String removedDeviceId : removed.keySet()) {
+ tradfriDevices.remove(removedDeviceId);
+ assetService.deleteAsset(removedDeviceId);
+ }
+ }
+ };
+ gateway.addEventHandler(gatewayEventHandler);
+ }
+ } else {
+ updateStatus(protocolConfiguration.getReferenceOrThrow(), ConnectionStatus.ERROR_CONFIGURATION);
+ }
+ synchronized (statusConsumerMap) {
+ statusConsumerMap.put(protocolRef, statusConsumer);
+ }
+ }
+ }
+
+ /**
+ * Handles the disconnections of the protocol.
+ * @param protocolConfiguration the protocol configuration.
+ */
+ @Override
+ protected void doUnlinkProtocolConfiguration(Asset agent, AssetAttribute protocolConfiguration) {
+ Consumer<ConnectionStatus> statusConsumer;
+ synchronized (statusConsumerMap) {
+ statusConsumer = statusConsumerMap.get(protocolConfiguration.getReferenceOrThrow());
+ }
+
+ String gatewayIp = protocolConfiguration.getMetaItem(META_TRADFRI_GATEWAY_HOST).flatMap(AbstractValueHolder::getValueAsString).orElse("");
+ synchronized (tradfriConnections) {
+ TradfriConnection tradfriConnection = tradfriConnections.get(gatewayIp);
+ if (tradfriConnection != null) {
+ tradfriConnection.removeConnectionStatusConsumer(statusConsumer);
+ for (Device device: tradfriDevices.values()) {
+ device.getEventHandlers().clear();
+ device.disableObserve();
+ }
+
+ tradfriConnection.disconnect();
+ tradfriConnections.remove(gatewayIp);
+ }
+ }
+ }
+
+ /**
+ * Links the attribute.
+ * @param attribute the attribute of the asset.
+ * @param protocolConfiguration the protocol configuration.
+ */
+ @Override
+ protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+ String gatewayIp = protocolConfiguration.getMetaItem(META_TRADFRI_GATEWAY_HOST).flatMap(AbstractValueHolder::getValueAsString).orElse("");
+ final AttributeRef attributeRef = attribute.getReferenceOrThrow();
+ TradfriConnection tradfriConnection = getConnection(gatewayIp);
+ if (tradfriConnection == null) return;
+ if(tradfriDevices.containsKey(attributeRef.getEntityId())){
+ Device device = tradfriDevices.get(attributeRef.getEntityId());
+ addDevice(attributeRef, tradfriConnection, device);
+ }
+ }
+
+ /**
+ * Unlinks the attribute.
+ * @param attribute the attribute of the asset.
+ * @param protocolConfiguration the protocol configuration.
+ */
+ @Override
+ protected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+ final AttributeRef attributeRef = attribute.getReferenceOrThrow();
+ removeDevice(attributeRef);
+ }
+
+ /**
+ * Handles the updates of the attribute values
+ * @param event the event that contains the attribute ref.
+ * @param processedValue the processed value.
+ * @param protocolConfiguration the protocol configuration.
+ */
+ @Override
+ protected void processLinkedAttributeWrite(AttributeEvent event, Value processedValue, AssetAttribute protocolConfiguration) {
+ if (!protocolConfiguration.isEnabled()) {
+ LOG.fine("Protocol configuration is disabled so ignoring write request");
+ return;
+ }
+
+ synchronized (attributeMap) {
+ Pair<TradfriConnection, Device> controlInfo = attributeMap.get(event.getAttributeRef());
+
+ if (controlInfo == null) {
+ LOG.fine("Attribute is not linked to a Tradfri light so cannot process event: " + event);
+ return;
+ }
+ controlInfo.key.controlDevice(controlInfo.value, event);
+ }
+ }
+
+ /**
+ * Method to retrieve the connection.
+ * @param gatewayIp the gateway IP address of the connection.
+ * @return the corresponding TRÅDFRI connection.
+ */
+ protected TradfriConnection getConnection(String gatewayIp) {
+ synchronized (tradfriConnections) {
+ return tradfriConnections.get(gatewayIp);
+ }
+ }
+
+ /**
+ * Adds a device to the attributeMap.
+ * By doing this, the attribute is registered for sending commands.
+ * @param attributeRef the reference of the entity.
+ * @param tradfriConnection the TRÅDFRI connection.
+ * @param device the TRÅDFRI device that needs to be added to the map.
+ */
+ protected void addDevice(AttributeRef attributeRef, TradfriConnection tradfriConnection, Device device) {
+ synchronized (attributeMap) {
+ Pair<TradfriConnection, Device> controlInfo = attributeMap.get(attributeRef);
+ if (controlInfo != null) {
+ return;
+ }
+ attributeMap.put(attributeRef, new Pair<>(tradfriConnection, device));
+ LOG.info("Attribute registered for sending commands: " + attributeRef + " with device: " + device);
+ }
+ }
+
+ /**
+ * Removes a device from the attributeMap.
+ * By doing this, the attribute is unregistered for sending commands.
+ * @param attributeRef the reference of the entity.
+ */
+ protected void removeDevice(AttributeRef attributeRef) {
+ synchronized (attributeMap) {
+ attributeMap.remove(attributeRef);
+ }
+ }
+
+ /**
+ * Checks the device type, and creates an asset for that device type.
+ * @param devices the discovered devices.
+ * @param agentLink the agent link.
+ * @param protocolConfiguration the protocol configuration.
+ */
+ private void addDevices(Device[] devices, MetaItem agentLink, AssetAttribute protocolConfiguration){
+ String parentId = null;
+ Optional<String> assetId = protocolConfiguration.getAssetId();
+ if(assetId.isPresent()) parentId = assetId.get();
+ for (Device device : devices) {
+ if (device.isPlug()) {
+ Plug plug = device.toPlug();
+ Asset asset = new TradfriPlugAsset(parentId, agentLink, plug, assetService);
+ tradfriDevices.put(asset.getId(), plug);
+ }
+ else if (device.isLight()) {
+ Light light = device.toLight();
+ Asset asset = new TradfriLightAsset(parentId, agentLink, light, assetService);
+ tradfriDevices.put(asset.getId(), light);
+ }
+ }
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Device.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Device.java
new file mode 100644
index 000000000..7cbb6624d
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Device.java
@@ -0,0 +1,228 @@
+package org.openremote.agent.protocol.tradfri.device;
+
+import org.openremote.agent.protocol.tradfri.device.event.EventHandler;
+import org.openremote.agent.protocol.tradfri.util.ApiEndpoint;
+import org.openremote.agent.protocol.tradfri.util.CoapClient;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * The class that represents an IKEA TRÅDFRI device
+ */
+public class Device {
+
+ /**
+ * The name of the device
+ */
+ private String name;
+
+ /**
+ * The creation date of the device
+ */
+ private Long creationDate;
+
+ /**
+ * The instance id of the device
+ */
+ private Integer instanceId;
+
+ /**
+ * The information of the device
+ */
+ private DeviceInfo deviceInfo;
+
+ /**
+ * The properties of the device
+ */
+ private DeviceProperties properties;
+
+ /**
+ * A CoAP client that can be used to communicate with the device using the IKEA TRÅDFRI gateway
+ */
+ protected CoapClient coapClient;
+
+ /**
+ * The observer that observes the device to automagically detect changes
+ */
+ private DeviceObserver observer;
+
+ /**
+ * The event handlers registered for the device
+ */
+ private List<EventHandler> eventHandlers;
+
+ /**
+ * Construct the Device class
+ * @param name The name of the device
+ * @param creationDate The creation date of the device
+ * @param instanceId The instance id of the device
+ * @param deviceInfo The information of the device
+ * @param coapClient A CoAP client that can be used to communicate with the device using the IKEA TRÅDFRI gateway
+ */
+ public Device(String name, Long creationDate, Integer instanceId, DeviceInfo deviceInfo, CoapClient coapClient){
+ this.name = name;
+ this.creationDate = creationDate;
+ this.instanceId = instanceId;
+ this.deviceInfo = deviceInfo;
+ this.coapClient = coapClient;
+ this.eventHandlers = new ArrayList<>();
+ }
+
+ /**
+ * Get the name of the device
+ * @return The name of the device
+ */
+ public String getName() {
+ return this.name;
+ }
+
+ /**
+ * Get the creation date of the device
+ * @return The creation date of the device
+ */
+ public Long getCreationDate() {
+ return this.creationDate;
+ }
+
+ /**
+ * Get the instance id of the device
+ * @return The instance id of the device
+ */
+ public Integer getInstanceId() {
+ return this.instanceId;
+ }
+
+ /**
+ * Get the information of the device
+ * @return The information of the device
+ */
+ public DeviceInfo getDeviceInfo() {
+ return this.deviceInfo;
+ }
+
+ /**
+ * Set the name of the device
+ * @param name The name of the device
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Set the creation date of the device
+ * @param creationDate The creation date of the device
+ */
+ public void setCreationDate(Long creationDate) {
+ this.creationDate = creationDate;
+ }
+
+ /**
+ * Set the instance id of the device
+ * @param instanceId The instance id of the device
+ */
+ public void setInstanceId(Integer instanceId) {
+ this.instanceId = instanceId;
+ }
+
+ /**
+ * Get the properties of the device
+ * @return The properties of the device
+ */
+ public DeviceProperties getProperties(){
+ return this.properties;
+ }
+
+ /**
+ * Set the properties of the device
+ * @param properties The properties of the device
+ */
+ public void setProperties(DeviceProperties properties){
+ this.properties = properties;
+ }
+
+ /**
+ * Get the CoAP endpoint of the device
+ * @return The CoAP endpoint of the device
+ */
+ public String getEndpoint(){
+ return ApiEndpoint.getUri(ApiEndpoint.DEVICES, String.valueOf(getInstanceId()));
+ }
+
+ /**
+ * Enable observe to automagically detect changes to the device
+ * @return True if successfully enabled observe, false if not
+ */
+ public boolean enableObserve() {
+ if(observer == null) observer = new DeviceObserver(this, this.coapClient);
+ return observer.start();
+ }
+
+ /**
+ * Disable observe
+ * @return True if successfully disabled observe, false if not
+ */
+ public boolean disableObserve() {
+ if(observer == null) return false;
+ return observer.stop();
+ }
+
+ /**
+ * Get a list of event handlers for the device
+ * @return A list of event handlers for the device
+ */
+ public List<EventHandler> getEventHandlers(){
+ return eventHandlers;
+ }
+
+ /**
+ * Add an event handler to the device
+ * @param eventHandler The event handler to add to the device
+ */
+ public void addEventHandler(EventHandler eventHandler){
+ this.eventHandlers.add(eventHandler);
+ }
+
+ /**
+ * Remove an event handler from the device
+ * @param eventHandler The event handler to remove from the device
+ */
+ public void removeEventHandler(EventHandler eventHandler){
+ this.eventHandlers.remove(eventHandler);
+ }
+
+ /**
+ * Check if the device is a {@link Light}
+ * @return True if the device is a {@link Light}, false if not
+ */
+ public boolean isLight(){
+ return this instanceof Light;
+ }
+
+ /**
+ * Convert the device to the {@link Light} class
+ * @return The device as {@link Light}
+ */
+ public Light toLight(){
+ if(isLight()) return (Light) this;
+ return null;
+ }
+
+ /**
+ * Check if the device is a {@link Plug}
+ * @return True if the device is a {@link Plug}, false if not
+ */
+ public boolean isPlug(){
+ return this instanceof Plug;
+ }
+
+ /**
+ * Convert the device to the {@link Plug} class
+ * @return The device as {@link Plug}
+ */
+ public Plug toPlug(){
+ if(isPlug()) return (Plug) this;
+ return null;
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/DeviceInfo.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/DeviceInfo.java
new file mode 100644
index 000000000..ad2b99f0a
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/DeviceInfo.java
@@ -0,0 +1,136 @@
+package org.openremote.agent.protocol.tradfri.device;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.agent.protocol.tradfri.util.ApiCode;
+
+/**
+ * The class that contains the information of an IKEA TRÅDFRI device
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class DeviceInfo extends DeviceProperties{
+
+ /**
+ * The manufacturer of the device
+ */
+ @JsonProperty(ApiCode.MANUFACTURER)
+ private String manufacturer;
+
+ /**
+ * The model name of the device
+ */
+ @JsonProperty(ApiCode.MODEL_NAME)
+ private String modelName;
+
+ /**
+ * The serial of the device
+ */
+ @JsonProperty(ApiCode.SERIAL)
+ private String serial;
+
+ /**
+ * The firmware version of the device
+ */
+ @JsonProperty(ApiCode.FIRMWARE_VERSION)
+ private String firmwareVersion;
+
+ /**
+ * The battery level of the device
+ */
+ @JsonProperty(ApiCode.BATTERY_LEVEL)
+ private Integer batteryLevel;
+
+ /**
+ * Construct the DeviceInfo class
+ */
+ public DeviceInfo(){
+ }
+
+ /**
+ * Get the manufacturer of the device
+ * @return The manufacturer of the device
+ */
+ public String getManufacturer() {
+ return this.manufacturer;
+ }
+
+ /**
+ * Get the model name of the device
+ * @return The model name of the device
+ */
+ public String getModelName() {
+ return this.modelName;
+ }
+
+ /**
+ * Get the serial of the device
+ * @return The serial of the device
+ */
+ public String getSerial() {
+ return this.serial;
+ }
+
+ /**
+ * Get the firmware version of the device
+ * @return The firmware version of the device
+ */
+ public String getFirmwareVersion() {
+ return this.firmwareVersion;
+ }
+
+ /**
+ * Get the battery level of the device
+ * @return The battery level of the device
+ */
+ public Integer getBatteryLevel() {
+ return this.batteryLevel;
+ }
+
+ /**
+ * Set the manufacturer of the device<br>
+ * <i>Note: This does not change the actual device</i>
+ * @param manufacturer The new manufacturer of the device
+ */
+ public void setManufacturer(String manufacturer) {
+ this.manufacturer = manufacturer;
+ }
+
+ /**
+ * Set the model name of the device<br>
+ * <i>Note: This does not change the actual device</i>
+ * @param modelName The new model name of the device
+ */
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ /**
+ * Set the serial of the device<br>
+ * <i>Note: This does not change the actual device</i>
+ * @param serial The new serial of the device
+ */
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+ /**
+ * Set the firmware version of the device<br>
+ * <i>Note: This does not change the actual device</i>
+ * @param firmwareVersion The new firmware version of the device
+ */
+ public void setFirmwareVersion(String firmwareVersion) {
+ this.firmwareVersion = firmwareVersion;
+ }
+
+ /**
+ * Set the battery level of the device<br>
+ * <i>Note: This does not change the actual device</i>
+ * @param batteryLevel The new battery level of the device
+ */
+ public void setBatteryLevel(Integer batteryLevel) {
+ this.batteryLevel = batteryLevel;
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/DeviceObserver.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/DeviceObserver.java
new file mode 100644
index 000000000..1451df191
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/DeviceObserver.java
@@ -0,0 +1,82 @@
+package org.openremote.agent.protocol.tradfri.device;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.openremote.agent.protocol.tradfri.device.event.*;
+import org.openremote.agent.protocol.tradfri.payload.DeviceResponse;
+import org.openremote.agent.protocol.tradfri.util.CoapClient;
+
+import java.util.ArrayList;
+
+/**
+ * The class that observes a device to automagically detect changes
+ */
+public class DeviceObserver extends Observer {
+
+ /**
+ * The device to observe
+ */
+ private Device device;
+
+ /**
+ * An object mapper used for mapping JSON responses from the IKEA TRÅDFRI gateway to Java classes
+ */
+ private ObjectMapper objectMapper;
+
+ /**
+ * Construct the DeviceObserver class
+ * @param device The device to observe
+ * @param coapClient A CoAP client that can be used to communicate with the device using the IKEA TRÅDFRI gateway
+ */
+ public DeviceObserver(Device device, CoapClient coapClient) {
+ super(device.getEndpoint(), coapClient);
+ this.device = device;
+ this.objectMapper = new ObjectMapper();
+ }
+
+ /**
+ * Handles a new response from the CoAP client and calls the appropriate event handlers for the device
+ * @param payload The payload of the response to the CoAP request
+ */
+ @Override
+ public void callEventHandlers(String payload) {
+ try {
+ DeviceResponse response = objectMapper.readValue(payload, DeviceResponse.class);
+ ArrayList<DeviceEvent> events = new ArrayList<>();
+ ArrayList<EventHandler> called = new ArrayList<>();
+ if(device.isLight()){
+ LightProperties oldProperties = (LightProperties) device.getProperties();
+ if(response.getLightProperties() != null && response.getLightProperties().length > 0) device.setProperties(response.getLightProperties()[0]);
+ LightProperties newProperties = (LightProperties) device.getProperties();
+ events.add(new LightEvent(device.toLight()));
+ ArrayList<DeviceEvent> changeEvents = new ArrayList<>();
+ if(checkChanges(oldProperties.getOn(), newProperties.getOn())) changeEvents.add(new LightChangeOnEvent(device.toLight(), oldProperties, newProperties));
+ if(checkChanges(oldProperties.getBrightness(), newProperties.getBrightness())) changeEvents.add(new LightChangeBrightnessEvent(device.toLight(), oldProperties, newProperties));
+ if(checkChanges(oldProperties.getColourX(), newProperties.getColourX()) || checkChanges(oldProperties.getColourY(), newProperties.getColourY()) || checkChanges(oldProperties.getHue(), newProperties.getHue()) || checkChanges(oldProperties.getSaturation(), newProperties.getSaturation())) changeEvents.add(new LightChangeColourEvent(device.toLight(), oldProperties, newProperties));
+ if(checkChanges(oldProperties.getColourTemperature(), newProperties.getColourTemperature())) changeEvents.add(new LightChangeColourTemperatureEvent(device.toLight(), oldProperties, newProperties));
+ if(changeEvents.size() > 0){
+ events.add(new LightChangeEvent(device.toLight(), oldProperties, newProperties));
+ events.addAll(changeEvents);
+ }
+ }else if(device.isPlug()){
+ PlugProperties oldProperties = (PlugProperties) device.getProperties();
+ if(response.getPlugProperties() != null && response.getPlugProperties().length > 0) device.setProperties(response.getPlugProperties()[0]);
+ PlugProperties newProperties = (PlugProperties) device.getProperties();
+ events.add(new PlugEvent(device.toPlug()));
+ if(checkChanges(oldProperties.getOn(), newProperties.getOn())){
+ events.add(new PlugChangeEvent(device.toPlug(), oldProperties, newProperties));
+ events.add(new PlugChangeOnEvent(device.toPlug(), oldProperties, newProperties));
+ }
+ }
+ for(EventHandler eventHandler: device.getEventHandlers()){
+ for(DeviceEvent event: events){
+ if(eventHandler.getEventType().isAssignableFrom(event.getClass()) && !called.contains(eventHandler)){
+ eventHandler.handle(event);
+ called.add(eventHandler);
+ }
+ }
+ }
+ } catch (JsonProcessingException ignored) { }
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/DeviceProperties.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/DeviceProperties.java
new file mode 100644
index 000000000..3faf8abb8
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/DeviceProperties.java
@@ -0,0 +1,42 @@
+package org.openremote.agent.protocol.tradfri.device;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.agent.protocol.tradfri.util.ApiCode;
+
+/**
+ * The class that contains the properties of an IKEA TRÅDFRI device
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class DeviceProperties {
+
+ /**
+ * The instance id of the device
+ */
+ @JsonProperty(ApiCode.INSTANCE_ID)
+ private Integer instanceId;
+
+ /**
+ * Construct the DeviceProperties class
+ */
+ public DeviceProperties(){
+ }
+
+ /**
+ * Get the instance id of the device
+ * @return The instance id of the device
+ */
+ public Integer getInstanceId() {
+ return this.instanceId;
+ }
+
+ /**
+ * Set the instance id of the device
+ * @param instanceId The instance id of the device
+ */
+ public void setInstanceId(Integer instanceId) {
+ this.instanceId = instanceId;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Gateway.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Gateway.java
new file mode 100644
index 000000000..c95315678
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Gateway.java
@@ -0,0 +1,200 @@
+package org.openremote.agent.protocol.tradfri.device;
+
+import org.openremote.agent.protocol.tradfri.device.event.EventHandler;
+import org.openremote.agent.protocol.tradfri.payload.AuthenticateRequest;
+import org.openremote.agent.protocol.tradfri.payload.AuthenticateResponse;
+import org.openremote.agent.protocol.tradfri.payload.DeviceResponse;
+import org.openremote.agent.protocol.tradfri.util.ApiEndpoint;
+import org.openremote.agent.protocol.tradfri.util.CoapClient;
+import org.openremote.agent.protocol.tradfri.util.Credentials;
+import org.apache.commons.lang3.RandomStringUtils;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * The class that is used to communicate with the IKEA TRÅDFRI gateway
+ */
+public class Gateway {
+
+ /**
+ * A CoAP client that can be used to communicate with the IKEA TRÅDFRI gateway
+ */
+ private CoapClient coapClient;
+
+ /**
+ * The observer that observes the IKEA TRÅDFRI gateway to automagically detect changes
+ */
+ private GatewayObserver observer;
+
+ /**
+ * The event handlers registered for the device
+ */
+ private List<EventHandler> eventHandlers;
+
+ /**
+ * Construct the Gateway class
+ * @param ip The IP-address of the IKEA TRÅDFRI gateway
+ */
+ public Gateway(String ip) {
+ ApiEndpoint.setGatewayIp(ip);
+ coapClient = new CoapClient();
+ eventHandlers = new ArrayList<>();
+ }
+
+ /**
+ * Connect and authenticate to the IKEA TRÅDFRI gateway using a security code
+ * @param securityCode The security code of the IKEA TRÅDFRI gateway
+ * @return Credentials that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public Credentials connect(String securityCode) {
+ String identity = RandomStringUtils.randomAlphanumeric(16);
+ AuthenticateRequest request = new AuthenticateRequest();
+ request.setIdentity(identity);
+ setCredentials("Client_identity", securityCode);
+ AuthenticateResponse response = coapClient.post(ApiEndpoint.getUri(ApiEndpoint.AUTHENTICATE), request, AuthenticateResponse.class);
+ if(response == null) return null;
+ Credentials credentials = new Credentials(identity, response.getPresharedKey());
+ setCredentials(credentials);
+ return credentials;
+ }
+
+ /**
+ * Connect and authenticate to the IKEA TRÅDFRI gateway using credentials
+ * @param credentials The credentials that can be used to authenticate to the IKEA TRÅDFRI gateway
+ * @return Credentials that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public Credentials connect(Credentials credentials){
+ setCredentials(credentials);
+ return credentials;
+ }
+
+ /**
+ * Change the credentials used to communicate with the IKEA TRÅDFRI gateway
+ * @param credentials The new credentials that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public void setCredentials(Credentials credentials){
+ coapClient.setCredentials(credentials);
+ }
+
+ /**
+ * Change the credentials used to communicate with the IKEA TRÅDFRI gateway
+ * @param identity The new identity that can be used to authenticate to the IKEA TRÅDFRI gateway
+ * @param key The new key that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public void setCredentials(String identity, String key){
+ Credentials credentials = new Credentials(identity, key);
+ setCredentials(credentials);
+ }
+
+ /**
+ * Get the credentials used to communicate with the IKEA TRÅDFRI gateway
+ * @return The credentials that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public Credentials getCredentials(){
+ return coapClient.getCredentials();
+ }
+
+ /**
+ * Get timeout for connections to the IKEA TRÅDFRI gateway (in milliseconds)
+ * @return The timeout for connections to the IKEA TRÅDFRI gateway (in milliseconds)
+ */
+ public long getTimeout() {
+ return coapClient.getTimeout();
+ }
+
+ /**
+ * Change the timeout for connections to the IKEA TRÅDFRI gateway (in milliseconds)
+ * @param timeout The new timeout for connections to the IKEA TRÅDFRI gateway (in milliseconds)
+ */
+ public void setTimeout(long timeout){
+ coapClient.setTimeout(timeout);
+ }
+
+ /**
+ * Get the ids of the devices registered to the IKEA TRÅDFRI gateway
+ * @return An array of the ids of the devices registered to the IKEA TRÅDFRI gateway
+ */
+ public int[] getDeviceIds(){
+ return coapClient.get(ApiEndpoint.getUri(ApiEndpoint.DEVICES), int[].class);
+ }
+
+ /**
+ * Get the a device registered to the IKEA TRÅDFRI gateway
+ * @param id The id of a device registered to the IKEA TRÅDFRI gateway
+ * @return The device with the provided id
+ */
+ public Device getDevice(int id){
+ DeviceResponse response = coapClient.get(ApiEndpoint.getUri(ApiEndpoint.DEVICES, String.valueOf(id)), DeviceResponse.class);
+ if(response == null){
+ return null;
+ }else if(response.getLightProperties() != null && response.getLightProperties().length > 0){
+ return new Light(response.getName(), response.getCreationDate(), response.getInstanceId(), response.getDeviceInfo(), response.getLightProperties()[0], coapClient);
+ }else if(response.getPlugProperties() != null && response.getPlugProperties().length > 0){
+ return new Plug(response.getName(), response.getCreationDate(), response.getInstanceId(), response.getDeviceInfo(), response.getPlugProperties()[0], coapClient);
+ }else{
+ return new Device(response.getName(), response.getCreationDate(), response.getInstanceId(), response.getDeviceInfo(), coapClient);
+ }
+ }
+
+ /**
+ * Get the devices registered to the IKEA TRÅDFRI gateway
+ * @return An array of the devices registered to the IKEA TRÅDFRI gateway
+ */
+ public Device[] getDevices(){
+ ArrayList<Device> deviceList = new ArrayList<>();
+ int[] deviceIds = getDeviceIds();
+ if(deviceIds == null) return null;
+ for(int deviceId: deviceIds){
+ Device device = getDevice(deviceId);
+ deviceList.add(device);
+ }
+ Device[] devices = new Device[deviceList.size()];
+ deviceList.toArray(devices);
+ return devices;
+ }
+
+ /**
+ * Enable observe to automagically detect changes to the device
+ * @return True if successfully enabled observe, false if not
+ */
+ public boolean enableObserve() {
+ if(observer == null) observer = new GatewayObserver(this, this.coapClient);
+ return observer.start();
+ }
+
+ /**
+ * Disable observe
+ * @return True if successfully disabled observe, false if not
+ */
+ public boolean disableObserve() {
+ if(observer == null) return false;
+ return observer.stop();
+ }
+
+ /**
+ * Get a list of event handlers for the IKEA TRÅDFRI gateway
+ * @return A list of event handlers for the IKEA TRÅDFRI gateway
+ */
+ public List<EventHandler> getEventHandlers(){
+ return eventHandlers;
+ }
+
+ /**
+ * Add an event handler to the IKEA TRÅDFRI gateway
+ * @param eventHandler The event handler to add to the IKEA TRÅDFRI gateway
+ * @since 1.0.0
+ */
+ public void addEventHandler(EventHandler eventHandler){
+ this.eventHandlers.add(eventHandler);
+ }
+
+ /**
+ * Remove an event handler from the IKEA TRÅDFRI gateway
+ * @param eventHandler The event handler to remove from the IKEA TRÅDFRI gateway
+ */
+ public void removeEventHandler(EventHandler eventHandler){
+ this.eventHandlers.remove(eventHandler);
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/GatewayObserver.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/GatewayObserver.java
new file mode 100644
index 000000000..dc446d136
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/GatewayObserver.java
@@ -0,0 +1,80 @@
+package org.openremote.agent.protocol.tradfri.device;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.openremote.agent.protocol.tradfri.device.event.EventHandler;
+import org.openremote.agent.protocol.tradfri.device.event.GatewayEvent;
+import org.openremote.agent.protocol.tradfri.util.ApiEndpoint;
+import org.openremote.agent.protocol.tradfri.util.CoapClient;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+
+/**
+ * The class that observes an IKEA TRÅDFRI gateway to automagically detect changes
+ */
+public class GatewayObserver extends Observer {
+
+ /**
+ * The IKEA TRÅDFRI gateway to observe
+ */
+ private Gateway gateway;
+
+ /**
+ * A cache of the devices registered to the IKEA TRÅDFRI gateway
+ */
+ private HashMap<Integer, Device> devices;
+
+ /**
+ * An object mapper used for mapping JSON responses from the IKEA TRÅDFRI gateway to Java classes
+ */
+ private ObjectMapper objectMapper;
+
+ /**
+ * Construct the GatewayObserver class
+ * @param gateway The IKEA TRÅDFRI gateway to observe
+ * @param coapClient A CoAP client that can be used to communicate with the device using the IKEA TRÅDFRI gateway
+ */
+ public GatewayObserver(Gateway gateway, CoapClient coapClient) {
+ super(ApiEndpoint.getUri(ApiEndpoint.DEVICES), coapClient);
+ this.gateway = gateway;
+ this.objectMapper = new ObjectMapper();
+ }
+
+ /**
+ * Start observing the gateway to automagically detect changes
+ * @return True if successfully started observing, false if not
+ */
+ @Override
+ public boolean start(){
+ Device[] devices = gateway.getDevices();
+ this.devices = new HashMap<>();
+ for(Device device: devices){
+ this.devices.put(device.getInstanceId(), device);
+ }
+ return super.start();
+ }
+
+ /**
+ * Handles a new response from the CoAP client and calls the appropriate event handlers for the IKEA TRÅDFRI gateway
+ * @param payload The payload of the response to the CoAP request
+ */
+ @Override
+ public void callEventHandlers(String payload) {
+ try {
+ int[] deviceIds = objectMapper.readValue(payload, int[].class);
+ ArrayList<EventHandler> called = new ArrayList<>();
+ GatewayEvent event = new GatewayEvent(gateway);
+ for (EventHandler eventHandler : gateway.getEventHandlers()) {
+ if (eventHandler.getEventType().isAssignableFrom(event.getClass()) && !called.contains(eventHandler)) {
+ eventHandler.handle(event);
+ called.add(eventHandler);
+ }
+ }
+ } catch (JsonProcessingException ignored) {
+ }
+ }
+
+
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Light.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Light.java
new file mode 100644
index 000000000..089bb6e44
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Light.java
@@ -0,0 +1,521 @@
+package org.openremote.agent.protocol.tradfri.device;
+
+import org.openremote.agent.protocol.tradfri.payload.DeviceRequest;
+import org.openremote.agent.protocol.tradfri.util.ApiEndpoint;
+import org.openremote.agent.protocol.tradfri.util.CoapClient;
+import org.openremote.agent.protocol.tradfri.util.ColourRGB;
+import org.openremote.agent.protocol.tradfri.util.ColourXY;
+
+/**
+ * The class that represents an IKEA TRÅDFRI light
+ */
+public class Light extends Device {
+
+ /**
+ * The current properties of the light
+ */
+ private LightProperties properties;
+
+ /**
+ * The new properties of the light in the update queue
+ */
+ private LightProperties newProperties;
+
+ /**
+ * Construct the Light class
+ * @param name The name of the light
+ * @param creationDate The creation date of the light
+ * @param instanceId The instance id of the light
+ * @param deviceInfo The information of the device
+ * @param properties The properties of the light
+ * @param coapClient A CoAP client that can be used to communicate with the light using the IKEA TRÅDFRI gateway
+ */
+ public Light(String name, Long creationDate, Integer instanceId, DeviceInfo deviceInfo, LightProperties properties, CoapClient coapClient){
+ super(name, creationDate, instanceId, deviceInfo, coapClient);
+ this.properties = properties;
+ this.newProperties = new LightProperties();
+ }
+
+ /**
+ * Get the properties of the light
+ * @return The properties of the light
+ */
+ @Override
+ public LightProperties getProperties(){
+ return this.properties;
+ }
+
+ /**
+ * Set the properties of the light
+ * @param properties The properties of the light
+ */
+ @Override
+ public void setProperties(DeviceProperties properties){
+ if(properties instanceof LightProperties) this.properties = (LightProperties) properties;
+ }
+
+ /**
+ * Get the on / off state of the light
+ * @return The on / off state of the light (true for on, false for off)
+ */
+ public Boolean getOn() {
+ return properties.getOn();
+ }
+
+ /**
+ * Get the brightness of the light
+ * @return The brightness of the light
+ */
+ public Integer getBrightness() {
+ return properties.getBrightness();
+ }
+
+ /**
+ * Get the colour of the light in hexadecimals
+ * @return The colour of the light in hexadecimals
+ */
+ public String getColourHex() {
+ return properties.getColourHex();
+ }
+
+ /**
+ * Get the hue of the light
+ * @return The hue of the light
+ */
+ public Integer getHue() {
+ return properties.getHue();
+ }
+
+ /**
+ * Get the saturation of the light
+ * @return The saturation of the light
+ */
+ public Integer getSaturation() {
+ return properties.getSaturation();
+ }
+
+ /**
+ * Get the X value of the colour of the light
+ * @return The X value of the colour of the light
+ */
+ public Integer getColourX() {
+ return properties.getColourX();
+ }
+
+ /**
+ * Get the Y value of the colour of the light
+ * @return The Y value of the colour of the light
+ */
+ public Integer getColourY() {
+ return properties.getColourY();
+ }
+
+ /**
+ * Get the XY values of the colour of the light
+ * @return The XY values of the colour of the light
+ */
+ public ColourXY getColourXY() {
+ return new ColourXY(properties.getColourX(), properties.getColourY());
+ }
+
+ /**
+ * Get the RGB values of the colour of the light
+ * @return The RGB values of the colour of the light
+ */
+ public ColourRGB getColourRGB() {
+ return ColourRGB.fromHS(properties.getHue() != null ? properties.getHue() : 0, properties.getSaturation() != null ? properties.getSaturation() : 0);
+ }
+
+ /**
+ * Get the colour temperature of the light
+ * @return The colour temperature of the light
+ */
+ public Integer getColourTemperature() {
+ return properties.getColourTemperature();
+ }
+
+ /**
+ * Update the on / off state of the light in the update queue
+ * @param on The new on / off state for the light (true for on, false for off)
+ */
+ public void updateOn(Boolean on) {
+ newProperties.setOn(on);
+ }
+
+ /**
+ * Update the brightness of the light in the update queue
+ * @param brightness The new brightness for the light
+ */
+ public void updateBrightness(Integer brightness) {
+ newProperties.setBrightness(brightness);
+ }
+
+ /**
+ * Update the colour of the light in the update queue to a predefined hexadecimal colour<br>
+ * Available colours:<br>
+ * <ul>
+ * <li>RGB: {@link org.openremote.agent.protocol.tradfri.util.ColourHex}</li>
+ * <li>Colour temperatures: {@link org.openremote.agent.protocol.tradfri.util.ColourTemperatureHex}</li>
+ * </ul>
+ * @param colourHex The new colour for the light
+ */
+ public void updateColourHex(String colourHex) {
+ newProperties.setColourHex(colourHex);
+ newProperties.setHue(null);
+ newProperties.setSaturation(null);
+ newProperties.setColourX(null);
+ newProperties.setColourY(null);
+ newProperties.setColourTemperature(null);
+ }
+
+ /**
+ * Update the hue of the light in the update queue
+ * @param hue The new hue for the light
+ */
+ public void updateHue(Integer hue) {
+ newProperties.setHue(hue);
+ newProperties.setColourX(null);
+ newProperties.setColourY(null);
+ newProperties.setColourHex(null);
+ newProperties.setColourTemperature(null);
+ }
+
+ /**
+ * Update the saturation of the light in the update queue
+ * @param saturation The new saturation for the light
+ */
+ public void updateSaturation(Integer saturation) {
+ newProperties.setSaturation(saturation);
+ newProperties.setColourX(null);
+ newProperties.setColourY(null);
+ newProperties.setColourHex(null);
+ newProperties.setColourTemperature(null);
+ }
+
+ /**
+ * Update the colour of the light in the update queue
+ * @param colourX The X value of the new colour for the light
+ * @param colourY The Y value of the new colour for the light
+ */
+ public void updateColourXY(Integer colourX, Integer colourY) {
+ newProperties.setColourX(colourX);
+ newProperties.setColourY(colourY);
+ newProperties.setColourHex(null);
+ newProperties.setHue(null);
+ newProperties.setSaturation(null);
+ newProperties.setColourTemperature(null);
+ }
+
+ /**
+ * Update the colour of the light in the update queue
+ * @param colourXY The new colour for the light
+ */
+ public void updateColour(ColourXY colourXY) {
+ newProperties.setColourX(colourXY.getX());
+ newProperties.setColourY(colourXY.getY());
+ newProperties.setColourHex(null);
+ newProperties.setHue(null);
+ newProperties.setSaturation(null);
+ newProperties.setColourTemperature(null);
+ }
+
+ /**
+ * Update the colour of the light in the update queue
+ * @param colourRGB The new colour for the light
+ */
+ public void updateColour(ColourRGB colourRGB) {
+ updateColour(ColourXY.fromRGB(colourRGB));
+ }
+
+ /**
+ * Update the colour of the light in the update queue
+ * @param colourRed The red value of the new colour for the light
+ * @param colourGreen The green value of the new colour for the light
+ * @param colourBlue The blue value of the new colour for the light
+ */
+ public void updateColourRGB(int colourRed, int colourGreen, int colourBlue) {
+ updateColour(new ColourRGB(colourRed, colourGreen, colourBlue));
+ }
+
+ /**
+ * Update the colour temperature of the light in the update queue
+ * @param colourTemperature The new colour temperature for the light
+ */
+ public void updateColourTemperature(Integer colourTemperature) {
+ newProperties.setColourTemperature(colourTemperature);
+ newProperties.setColourHex(null);
+ newProperties.setHue(null);
+ newProperties.setSaturation(null);
+ newProperties.setColourX(null);
+ newProperties.setColourY(null);
+ }
+
+ /**
+ * Update the transition time for updating the light in the update queue
+ * @param transitionTime The new transition time for updating the light
+ */
+ public void updateTransitionTime(Integer transitionTime){
+ newProperties.setTransitionTime(transitionTime);
+ }
+
+ /**
+ * Set the on / off state of the light
+ * @param on The new on / off state for the light (true for on, false for off)
+ * @param transitionTime The transition time for updating the light
+ * @return True if successfully updated the on / off state of the light, false if not
+ */
+ public boolean setOn(Boolean on, Integer transitionTime) {
+ LightProperties newProperties = new LightProperties();
+ newProperties.setOn(on);
+ newProperties.setTransitionTime(transitionTime);
+ return applyUpdate(newProperties);
+ }
+
+ /**
+ * Set the on / off state of the light
+ * @param on The new on / off state for the light (true for on, false for off)
+ * @return True if successfully updated the on / off state of the light, false if not
+ */
+ public boolean setOn(Boolean on){
+ return setOn(on, null);
+ }
+
+ /**
+ * Set the brightness of the light
+ * @param brightness The new brightness for the light
+ * @param transitionTime The transition time for updating the light
+ * @return True if successfully updated the brightness of the light, false if not
+ */
+ public boolean setBrightness(Integer brightness, Integer transitionTime) {
+ LightProperties newProperties = new LightProperties();
+ newProperties.setBrightness(brightness);
+ newProperties.setTransitionTime(transitionTime);
+ return applyUpdate(newProperties);
+ }
+
+ /**
+ * Set the brightness of the light
+ * @param brightness The new brightness for the light
+ * @return True if successfully updated the brightness of the light, false if not
+ */
+ public boolean setBrightness(Integer brightness){
+ return setBrightness(brightness, null);
+ }
+
+ /**
+ * Set the colour of the light to a predefined hexadecimal colour<br>
+ * Available colours:<br>
+ * <ul>
+ * <li>RGB: {@link org.openremote.agent.protocol.tradfri.util.ColourHex}</li>
+ * <li>Colour temperatures: {@link org.openremote.agent.protocol.tradfri.util.ColourTemperatureHex}</li>
+ * </ul>
+ * @param colourHex The new colour for the light
+ * @param transitionTime The transition time for updating the light
+ * @return True if successfully updated the colour of the light, false if not
+ */
+ public boolean setColourHex(String colourHex, Integer transitionTime) {
+ LightProperties newProperties = new LightProperties();
+ newProperties.setColourHex(colourHex);
+ newProperties.setTransitionTime(transitionTime);
+ return applyUpdate(newProperties);
+ }
+
+ /**
+ * Set the colour of the light to a predefined hexadecimal colour<br>
+ * Available colours:<br>
+ * <ul>
+ * <li>RGB: {@link org.openremote.agent.protocol.tradfri.util.ColourHex}</li>
+ * <li>Colour temperatures: {@link org.openremote.agent.protocol.tradfri.util.ColourTemperatureHex}</li>
+ * </ul>
+ * @param colourHex The new colour for the light
+ * @return True if successfully updated the colour of the light, false if not
+ */
+ public boolean setColourHex(String colourHex){
+ return setColourHex(colourHex, null);
+ }
+
+ /**
+ * Set the hue of the light
+ * @param hue The new hue for the light
+ * @param transitionTime The transition time for updating the light
+ * @return True if successfully updated the hue of the light, false if not
+ */
+ public boolean setHue(Integer hue, Integer transitionTime) {
+ LightProperties newProperties = new LightProperties();
+ newProperties.setHue(hue);
+ newProperties.setTransitionTime(transitionTime);
+ return applyUpdate(newProperties);
+ }
+
+ /**
+ * Set the hue of the light
+ * @param hue The new hue for the light
+ * @return True if successfully updated the hue of the light, false if not
+ */
+ public boolean setHue(Integer hue){
+ return setHue(hue, null);
+ }
+
+ /**
+ * Set the saturation of the light
+ * @param saturation The new saturation for the light
+ * @param transitionTime The transition time for updating the light
+ * @return True if successfully updated the saturation of the light, false if not
+ */
+ public boolean setSaturation(Integer saturation, Integer transitionTime) {
+ LightProperties newProperties = new LightProperties();
+ newProperties.setSaturation(saturation);
+ newProperties.setTransitionTime(transitionTime);
+ return applyUpdate(newProperties);
+ }
+
+ /**
+ * Set the saturation of the light
+ * @param saturation The new saturation for the light
+ * @return True if successfully updated the saturation of the light, false if not
+ */
+ public boolean setSaturation(Integer saturation){
+ return setSaturation(saturation, null);
+ }
+
+ /**
+ * Set the colour of the light
+ * @param colourX The X value of the new colour for the light
+ * @param colourY The Y value of the new colour for the light
+ * @param transitionTime The transition time for updating the light
+ * @return True if successfully updated the colour of the light, false if not
+ */
+ public boolean setColourXY(Integer colourX, Integer colourY, Integer transitionTime) {
+ LightProperties newProperties = new LightProperties();
+ newProperties.setColourX(colourX);
+ newProperties.setColourY(colourY);
+ newProperties.setTransitionTime(transitionTime);
+ return applyUpdate(newProperties);
+ }
+
+ /**
+ * Set the colour of the light
+ * @param colourX The X value of the new colour for the light
+ * @param colourY The Y value of the new colour for the light
+ * @return True if successfully updated the colour of the light, false if not
+ */
+ public boolean setColourXY(Integer colourX, Integer colourY){
+ return setColourXY(colourX, colourY, null);
+ }
+
+ /**
+ * Set the colour of the light
+ * @param colourXY The new colour for the light
+ * @param transitionTime The transition time for updating the light
+ * @return True if successfully updated the colour of the light, false if not
+ */
+ public boolean setColour(ColourXY colourXY, Integer transitionTime) {
+ return setColourXY(colourXY.getX(), colourXY.getY(), transitionTime);
+ }
+
+ /**
+ * Set the colour of the light
+ * @param colourXY The new colour for the light
+ * @return True if successfully updated the colour of the light, false if not
+ */
+ public boolean setColour(ColourXY colourXY){
+ return setColour(colourXY, null);
+ }
+
+ /**
+ * Set the colour of the light
+ * @param colourRGB The new colour for the light
+ * @param transitionTime The transition time for updating the light
+ * @return True if successfully updated the colour of the light, false if not
+ */
+ public boolean setColour(ColourRGB colourRGB, Integer transitionTime) {
+ return setColour(ColourXY.fromRGB(colourRGB), transitionTime);
+ }
+
+ /**
+ * Set the colour of the light
+ * @param colourRGB The new colour for the light
+ * @return True if successfully updated the colour of the light, false if not
+ */
+ public boolean setColour(ColourRGB colourRGB){
+ return setColour(colourRGB, null);
+ }
+
+ /**
+ * Set the colour of the light
+ * @param colourRed The red value of the new colour for the light
+ * @param colourGreen The green value of the new colour for the light
+ * @param colourBlue The blue value of the new colour for the light
+ * @param transitionTime The transition time for updating the light
+ * @return True if successfully updated the colour of the light, false if not
+ */
+ public boolean setColourRGB(int colourRed, int colourGreen, int colourBlue, Integer transitionTime) {
+ return setColour(new ColourRGB(colourRed, colourGreen, colourBlue), transitionTime);
+ }
+
+ /**
+ * Set the colour of the light
+ * @param colourRed The red value of the new colour for the light
+ * @param colourGreen The green value of the new colour for the light
+ * @param colourBlue The blue value of the new colour for the light
+ * @return True if successfully updated the colour of the light, false if not
+ */
+ public boolean setColourRGB(int colourRed, int colourGreen, int colourBlue){
+ return setColour(new ColourRGB(colourRed, colourGreen, colourBlue));
+ }
+
+ /**
+ * Set the colour temperature of the light
+ * @param colourTemperature The new colour temperature for the light
+ * @param transitionTime The transition time for updating the light
+ * @return True if successfully updated the colour temperature of the light, false if not
+ */
+ public boolean setColourTemperature(Integer colourTemperature, Integer transitionTime) {
+ LightProperties newProperties = new LightProperties();
+ newProperties.setColourTemperature(colourTemperature);
+ newProperties.setTransitionTime(transitionTime);
+ return applyUpdate(newProperties);
+ }
+
+ /**
+ * Set the colour temperature of the light
+ * @param colourTemperature The new colour temperature for the light
+ * @return True if successfully updated the colour temperature of the light, false if not
+ */
+ public boolean setColourTemperature(Integer colourTemperature){
+ return setColourTemperature(colourTemperature, null);
+ }
+
+ /**
+ * Apply updates to the light
+ * @param newProperties The new properties to apply to the light
+ * @return True if successfully updated the light, false if not
+ */
+ private boolean applyUpdate(LightProperties newProperties) {
+ DeviceRequest request = new DeviceRequest();
+ request.setLightProperties(new LightProperties[]{newProperties});
+ String response = coapClient.put(ApiEndpoint.getUri(ApiEndpoint.DEVICES, String.valueOf(getInstanceId())), request, String.class);
+ return response != null;
+ }
+
+ /**
+ * Apply the updates in the update queue to the light
+ * @return True if successfully updated the light, false if not
+ */
+ public boolean applyUpdates() {
+ boolean success = applyUpdate(newProperties);
+ newProperties = new LightProperties();
+ return success;
+ }
+
+ /**
+ * Apply the updates in the update queue to the light
+ * @param transitionTime The transition time for updating the light
+ * @return True if successfully updated the light, false if not
+ */
+ public boolean applyUpdates(Integer transitionTime) {
+ newProperties.setTransitionTime(transitionTime);
+ return applyUpdates();
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/LightProperties.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/LightProperties.java
new file mode 100644
index 000000000..27f036d08
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/LightProperties.java
@@ -0,0 +1,234 @@
+package org.openremote.agent.protocol.tradfri.device;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.agent.protocol.tradfri.util.ApiCode;
+
+/**
+ * The class that contains the properties of an IKEA TRÅDFRI light
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class LightProperties extends DeviceProperties{
+
+ /**
+ * The on state of the light (true for on, false for off)
+ */
+ @JsonProperty(ApiCode.ON_OFF)
+ @JsonFormat(shape = JsonFormat.Shape.NUMBER)
+ private Boolean on;
+
+ /**
+ * The brightness of the light
+ */
+ @JsonProperty(ApiCode.BRIGHTNESS)
+ private Integer brightness;
+
+ /**
+ * The colour of the light in hexadecimals
+ */
+ @JsonProperty(ApiCode.COLOUR_HEX)
+ private String colourHex;
+
+ /**
+ * The hue of the light
+ */
+ @JsonProperty(ApiCode.HUE)
+ private Integer hue;
+
+ /**
+ * The saturation of the light
+ */
+ @JsonProperty(ApiCode.SATURATION)
+ private Integer saturation;
+
+ /**
+ * The X value of the colour of the light
+ */
+ @JsonProperty(ApiCode.COLOUR_X)
+ private Integer colourX;
+
+ /**
+ * The Y value of the colour of the light
+ */
+ @JsonProperty(ApiCode.COLOUR_Y)
+ private Integer colourY;
+
+ /**
+ * The colour temperature of the light
+ */
+ @JsonProperty(ApiCode.COLOUR_TEMPERATURE)
+ private Integer colourTemperature;
+
+ /**
+ * The transition time for updating the light
+ */
+ @JsonProperty(ApiCode.TRANSITION_TIME)
+ private Integer transitionTime;
+
+ /**
+ * Construct the LightProperties class
+ */
+ public LightProperties(){
+ }
+
+ /**
+ * Get the on state of the light
+ * @return The on state of the light (true for on, false for off)
+ */
+ public Boolean getOn() {
+ return this.on;
+ }
+
+ /**
+ * Get the brightness of the light
+ * @return The brightness of the light
+ */
+ public Integer getBrightness() {
+ return this.brightness;
+ }
+
+ /**
+ * Get the colour of the light in hexadecimals
+ * @return The colour of the light in hexadecimals
+ */
+ public String getColourHex() {
+ return this.colourHex;
+ }
+
+ /**
+ * Get the hue of the light
+ * @return The hue of the light
+ */
+ public Integer getHue() {
+ return this.hue;
+ }
+
+ /**
+ * Get the saturation of the light
+ * @return The saturation of the light
+ */
+ public Integer getSaturation() {
+ return this.saturation;
+ }
+
+ /**
+ * Get the X value of the colour of the light
+ * @return The X value of the colour of the light
+ */
+ public Integer getColourX() {
+ return this.colourX;
+ }
+
+ /**
+ * Get the Y value of the colour of the light
+ * @return The Y value of the colour of the light
+ */
+ public Integer getColourY() {
+ return this.colourY;
+ }
+
+ /**
+ * Get the colour temperature of the light
+ * @return The colour temperature of the light
+ */
+ public Integer getColourTemperature() {
+ return this.colourTemperature;
+ }
+
+ /**
+ * Get the transition time for updating the light
+ * @return The transition time for updating the light
+ */
+ public Integer getTransitionTime() {
+ return this.transitionTime;
+ }
+
+ /**
+ * Set the on state of the light within the LightProperties class<br>
+ * <i>Note: This does not change the actual light</i>
+ * @param on The new on state for the light (true for on, false for off)
+ */
+ public void setOn(Boolean on) {
+ this.on = on;
+ }
+
+ /**
+ * Set the brightness of the light within the LightProperties class<br>
+ * <i>Note: This does not change the actual light</i>
+ * @param brightness The new brightness for the light
+ */
+ public void setBrightness(Integer brightness) {
+ this.brightness = brightness;
+ }
+
+ /**
+ * Set the colour of the light to a predefined hexadecimal colour within the LightProperties class<br>
+ * <i>Note: This does not change the actual light</i>
+ * Available colours:<br>
+ * <ul>
+ * <li>RGB: {@link org.openremote.agent.protocol.tradfri.util.ColourHex}</li>
+ * <li>Colour temperatures: {@link org.openremote.agent.protocol.tradfri.util.ColourTemperatureHex}</li>
+ * </ul>
+ * @param colourHex The new colour for the light
+ */
+ public void setColourHex(String colourHex) {
+ this.colourHex = colourHex;
+ }
+
+ /**
+ * Set the hue of the light within the LightProperties class<br>
+ * <i>Note: This does not change the actual light</i>
+ * @param hue The new hue for the light
+ */
+ public void setHue(Integer hue) {
+ this.hue = hue;
+ }
+
+ /**
+ * Set the saturation of the light within the LightProperties class<br>
+ * <i>Note: This does not change the actual light</i>
+ * @param saturation The new saturation for the light
+ */
+ public void setSaturation(Integer saturation) {
+ this.saturation = saturation;
+ }
+
+ /**
+ * Set the X value of the colour of the light within the LightProperties class<br>
+ * <i>Note: This does not change the actual light</i>
+ * @param colourX The X value of the new colour for the light
+ */
+ public void setColourX(Integer colourX) {
+ this.colourX = colourX;
+ }
+
+ /**
+ * Set the Y value of the colour of the light within the LightProperties class<br>
+ * <i>Note: This does not change the actual light</i>
+ * @param colourY The Y value of the new colour for the light
+ */
+ public void setColourY(Integer colourY) {
+ this.colourY = colourY;
+ }
+
+ /**
+ * Set the colour temperature of the light within the LightProperties class<br>
+ * <i>Note: This does not change the actual light</i>
+ * @param colourTemperature The new colour temperature for the light
+ */
+ public void setColourTemperature(Integer colourTemperature) {
+ this.colourTemperature = colourTemperature;
+ }
+
+ /**
+ * Set the transition time for updating the light within the LightProperties class<br>
+ * <i>Note: This does not change the actual light</i>
+ * @param transitionTime The new transition time for updating the light
+ */
+ public void setTransitionTime(Integer transitionTime) {
+ this.transitionTime = transitionTime;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Observer.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Observer.java
new file mode 100644
index 000000000..29500425a
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Observer.java
@@ -0,0 +1,101 @@
+package org.openremote.agent.protocol.tradfri.device;
+
+import org.eclipse.californium.core.CoapHandler;
+import org.eclipse.californium.core.CoapObserveRelation;
+import org.eclipse.californium.core.CoapResponse;
+import org.openremote.agent.protocol.tradfri.util.CoapClient;
+
+/**
+ * The class that observes a device to automagically detect changes
+ */
+public abstract class Observer implements CoapHandler {
+
+ /**
+ * The endpoint to observe
+ */
+ private String endpoint;
+
+ /**
+ * A CoAP client that can be used to communicate with the IKEA TRÅDFRI gateway
+ */
+ private CoapClient coapClient;
+
+ /**
+ * The observe relation used by CoAP to keep track of the connection to the IKEA TRÅDFRI gateway
+ */
+ private CoapObserveRelation coapObserveRelation;
+
+ /**
+ * Construct the Observer class
+ * @param endpoint The endpoint to observe
+ * @param coapClient A CoAP client that can be used to communicate with the device using the IKEA TRÅDFRI gateway
+ */
+ public Observer(String endpoint, CoapClient coapClient) {
+ this.endpoint = endpoint;
+ this.coapClient = coapClient;
+ }
+
+ /**
+ * Start observing the endpoint to automagically detect changes
+ * @return True if successfully started observing, false if not
+ */
+ public boolean start(){
+ if(coapObserveRelation == null || coapObserveRelation.isCanceled()){
+ coapObserveRelation = coapClient.requestObserve(endpoint, this);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Stop observing the device
+ * @return True if successfully stopped observing, false if not
+ */
+ public boolean stop(){
+ if(coapObserveRelation != null && !coapObserveRelation.isCanceled()){
+ coapObserveRelation.proactiveCancel();
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Check if there is a difference between the old value and the new value
+ * @param oldValue The old value
+ * @param newValue The new value
+ * @return True if there is a difference between the old value and the new value, false if they are the same
+ */
+ protected boolean checkChanges(Object oldValue, Object newValue){
+ return ((oldValue == null && newValue != null) || (newValue == null && oldValue != null) || (oldValue != null && !oldValue.equals(newValue)));
+ }
+
+ /**
+ * Handles a new response from the CoAP client
+ * @param coapResponse The response to the CoAP request
+ */
+ @Override
+ public void onLoad(CoapResponse coapResponse) {
+ if(!coapResponse.isSuccess()) return;
+ new Thread(() -> {
+ try {
+ Thread.sleep(1000);
+ callEventHandlers(coapResponse.getResponseText());
+ } catch (InterruptedException ignored) {
+ }
+ }).start();
+ }
+
+ /**
+ * Handles an error from the CoAP client
+ */
+ @Override
+ public void onError() {
+ }
+
+ /**
+ * Call the appropriate event handlers
+ * @param payload The payload text of the CoAP response
+ */
+ public abstract void callEventHandlers(String payload);
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Plug.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Plug.java
new file mode 100644
index 000000000..b98a9ca20
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/Plug.java
@@ -0,0 +1,104 @@
+package org.openremote.agent.protocol.tradfri.device;
+
+import org.openremote.agent.protocol.tradfri.payload.DeviceRequest;
+import org.openremote.agent.protocol.tradfri.util.ApiEndpoint;
+import org.openremote.agent.protocol.tradfri.util.CoapClient;
+
+/**
+ * The class that represents an IKEA TRÅDFRI plug
+ */
+public class Plug extends Device {
+
+ /**
+ * The current properties of the plug
+ */
+ private PlugProperties properties;
+
+ /**
+ * The new properties of the plug in the update queue
+ */
+ private PlugProperties newProperties;
+
+ /**
+ * Construct the Plug class
+ * @param name The name of the plug
+ * @param creationDate The creation date of the plug
+ * @param instanceId The instance id of the plug
+ * @param deviceInfo The information of the device
+ * @param properties The properties of the plug
+ * @param coapClient A CoAP client that can be used to communicate with the plug using the IKEA TRÅDFRI gateway
+ */
+ public Plug(String name, Long creationDate, Integer instanceId, DeviceInfo deviceInfo, PlugProperties properties, CoapClient coapClient){
+ super(name, creationDate, instanceId, deviceInfo, coapClient);
+ this.properties = properties;
+ this.newProperties = new PlugProperties();
+ }
+
+ /**
+ * Get the properties of the plug
+ * @return The properties of the plug
+ */
+ @Override
+ public PlugProperties getProperties(){
+ return this.properties;
+ }
+
+ /**
+ * Set the properties of the plug
+ * @param properties The properties of the plug
+ */
+ @Override
+ public void setProperties(DeviceProperties properties){
+ if(properties instanceof PlugProperties) this.properties = (PlugProperties) properties;
+ }
+
+ /**
+ * Get the on / off state of the plug
+ * @return The on state of the plug (true for on, false for off)
+ */
+ public Boolean getOn() {
+ return properties.getOn();
+ }
+
+ /**
+ * Update the on / off state of the plug in the update queue
+ * @param on The new on / off state for the plug (true for on, false for off)
+ */
+ public void updateOn(Boolean on) {
+ newProperties.setOn(on);
+ }
+
+ /**
+ * Set the on / off state of the plug
+ * @param on The new on / off state for the plug (true for on, false for off)
+ * @return True if successfully updated the plug, false if not
+ */
+ public boolean setOn(Boolean on) {
+ PlugProperties newProperties = new PlugProperties();
+ newProperties.setOn(on);
+ return applyUpdate(newProperties);
+ }
+
+ /**
+ * Apply updates to the plug
+ * @param newProperties The new properties to apply to the plug
+ * @return True if successfully updated the plug, false if not
+ */
+ private boolean applyUpdate(PlugProperties newProperties) {
+ DeviceRequest request = new DeviceRequest();
+ request.setPlugProperties(new PlugProperties[]{newProperties});
+ String response = coapClient.put(ApiEndpoint.getUri(ApiEndpoint.DEVICES, String.valueOf(getInstanceId())), request, String.class);
+ return response != null;
+ }
+
+ /**
+ * Apply the updates in the update queue to the plug
+ * @return True if successfully updated the plug, false if not
+ */
+ public boolean applyUpdates() {
+ boolean success = applyUpdate(newProperties);
+ newProperties = new PlugProperties();
+ return success;
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/PlugProperties.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/PlugProperties.java
new file mode 100644
index 000000000..64bdb1893
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/PlugProperties.java
@@ -0,0 +1,45 @@
+package org.openremote.agent.protocol.tradfri.device;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.agent.protocol.tradfri.util.ApiCode;
+
+/**
+ * The class that contains the properties of an IKEA TRÅDFRI plug
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class PlugProperties extends DeviceProperties {
+
+ /**
+ * The on state of the plug (true for on, false for off)
+ */
+ @JsonProperty(ApiCode.ON_OFF)
+ @JsonFormat(shape = JsonFormat.Shape.NUMBER)
+ private Boolean on;
+
+ /**
+ * Construct the PlugProperties class
+ */
+ public PlugProperties(){
+ }
+
+ /**
+ * Get the on state of the plug
+ * @return The on state of the plug (true for on, false for off)
+ */
+ public Boolean getOn() {
+ return this.on;
+ }
+
+ /**
+ * Set the on state of the plug within the PlugProperties class<br>
+ * <i>Note: This does not change the actual plug</i>
+ * @param on The new on state for the plug (true for on, false for off)
+ */
+ public void setOn(Boolean on) {
+ this.on = on;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/DeviceEvent.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/DeviceEvent.java
new file mode 100644
index 000000000..0e8c9fc3c
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/DeviceEvent.java
@@ -0,0 +1,31 @@
+package org.openremote.agent.protocol.tradfri.device.event;
+
+import org.openremote.agent.protocol.tradfri.device.Device;
+
+/**
+ * The class that represents a device event that occurred to an IKEA TRÅDFRI device
+ */
+public class DeviceEvent {
+
+ /**
+ * The device for which the event occurred
+ */
+ private Device device;
+
+ /**
+ * Construct the DeviceEvent class
+ * @param device The device for which the event occurred
+ */
+ public DeviceEvent(Device device) {
+ this.device = device;
+ }
+
+ /**
+ * Get the device for which the event occurred
+ * @return The device for which the event occurred
+ */
+ public Device getDevice(){
+ return this.device;
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/EventHandler.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/EventHandler.java
new file mode 100644
index 000000000..ebbed66a6
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/EventHandler.java
@@ -0,0 +1,30 @@
+package org.openremote.agent.protocol.tradfri.device.event;
+
+import java.lang.reflect.ParameterizedType;
+
+/**
+ * The class that handles events for IKEA TRÅDFRI devices
+ */
+public abstract class EventHandler<T> {
+
+ /**
+ * Construct the EventHandler class
+ */
+ public EventHandler(){
+ }
+
+ /**
+ * Handle the event
+ * @param event The event that occurred
+ */
+ public abstract void handle(T event);
+
+ /**
+ * Get the class of the event that this event handler handles
+ * @return The class of the event that this event handler handles
+ */
+ public Class<T> getEventType(){
+ return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/GatewayEvent.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/GatewayEvent.java
new file mode 100644
index 000000000..a0442b9b2
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/GatewayEvent.java
@@ -0,0 +1,31 @@
+package org.openremote.agent.protocol.tradfri.device.event;
+
+import org.openremote.agent.protocol.tradfri.device.Gateway;
+
+/**
+ * The class that represents an event that occurred to an IKEA TRÅDFRI gateway
+ */
+public class GatewayEvent {
+
+ /**
+ * The IKEA TRÅDFRI gateway for which the event occurred
+ */
+ private Gateway gateway;
+
+ /**
+ * Construct the GatewayEvent class
+ * @param gateway The IKEA TRÅDFRI gateway for which the event occurred
+ */
+ public GatewayEvent(Gateway gateway) {
+ this.gateway = gateway;
+ }
+
+ /**
+ * Get the IKEA TRÅDFRI gateway for which the event occurred
+ * @return The IKEA TRÅDFRI gateway for which the event occurred
+ */
+ public Gateway getGateway(){
+ return this.gateway;
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeBrightnessEvent.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeBrightnessEvent.java
new file mode 100644
index 000000000..9def255b1
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeBrightnessEvent.java
@@ -0,0 +1,37 @@
+package org.openremote.agent.protocol.tradfri.device.event;
+
+import org.openremote.agent.protocol.tradfri.device.Light;
+import org.openremote.agent.protocol.tradfri.device.LightProperties;
+
+/**
+ * The class that represents a light brightness changed event that occurred to an IKEA TRÅDFRI light
+ */
+public class LightChangeBrightnessEvent extends LightChangeEvent {
+
+ /**
+ * Construct the LightChangeBrightnessEvent class
+ * @param light The light for which the event occurred
+ * @param oldProperties The old properties of the light (from before the event occurred)
+ * @param newProperties The new properties of the light (from after the event occurred)
+ */
+ public LightChangeBrightnessEvent(Light light, LightProperties oldProperties, LightProperties newProperties) {
+ super(light, oldProperties, newProperties);
+ }
+
+ /**
+ * Get the old brightness of the light (from before the event occurred)
+ * @return The old brightness of the light
+ */
+ public int getOldBrightness(){
+ return getOldProperties().getBrightness();
+ }
+
+ /**
+ * Get the new brightness of the light (from after the event occurred)
+ * @return The new brightness of the light
+ */
+ public int getNewBrightness(){
+ return getNewProperties().getBrightness();
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeColourEvent.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeColourEvent.java
new file mode 100644
index 000000000..7f03caa2c
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeColourEvent.java
@@ -0,0 +1,119 @@
+package org.openremote.agent.protocol.tradfri.device.event;
+
+import org.openremote.agent.protocol.tradfri.device.Light;
+import org.openremote.agent.protocol.tradfri.device.LightProperties;
+import org.openremote.agent.protocol.tradfri.util.ColourRGB;
+import org.openremote.agent.protocol.tradfri.util.ColourXY;
+
+/**
+ * The class that represents a light colour changed event that occurred to an IKEA TRÅDFRI light
+ */
+public class LightChangeColourEvent extends LightChangeEvent {
+
+ /**
+ * Construct the LightChangeColourEvent class
+ * @param light The light for which the event occurred
+ * @param oldProperties The old properties of the light (from before the event occurred)
+ * @param newProperties The new properties of the light (from after the event occurred)
+ */
+ public LightChangeColourEvent(Light light, LightProperties oldProperties, LightProperties newProperties) {
+ super(light, oldProperties, newProperties);
+ }
+
+ /**
+ * Get the old hue of the light (from before the event occurred)
+ * @return The old hue of the light
+ */
+ public int getOldHue(){
+ return getOldProperties().getHue();
+ }
+
+ /**
+ * Get the new hue of the light (from after the event occurred)
+ * @return The new hue of the light
+ */
+ public int getNewHue(){
+ return getNewProperties().getHue();
+ }
+
+ /**
+ * Get the old saturation of the light (from before the event occurred)
+ * @return The old saturation of the light
+ */
+ public int getOldSaturation(){
+ return getOldProperties().getSaturation();
+ }
+
+ /**
+ * Get the new saturation of the light (from after the event occurred)
+ * @return The new saturation of the light
+ */
+ public int getNewSaturation(){
+ return getNewProperties().getSaturation();
+ }
+
+ /**
+ * Get the old X value of the colour of the light (from before the event occurred)
+ * @return The old X value of the colour of the light
+ */
+ public int getOldColourX(){
+ return getOldProperties().getColourX();
+ }
+
+ /**
+ * Get the new X value of the colour of the light (from after the event occurred)
+ * @return The new X value of the colour of the light
+ */
+ public int getNewColourX(){
+ return getNewProperties().getColourX();
+ }
+
+ /**
+ * Get the old Y value of the colour of the light (from before the event occurred)
+ * @return The old Y value of the colour of the light
+ */
+ public int getOldColourY(){
+ return getOldProperties().getColourY();
+ }
+
+ /**
+ * Get the new Y value of the colour of the light (from after the event occurred)
+ * @return The new Y value of the colour of the light
+ */
+ public int getNewColourY(){
+ return getNewProperties().getColourY();
+ }
+
+ /**
+ * Get the old XY colour of the light (from before the event occurred)
+ * @return The old XY colour of the light
+ */
+ public ColourXY getOldColourXY(){
+ return new ColourXY(getOldProperties().getColourX(), getOldProperties().getColourY());
+ }
+
+ /**
+ * Get the new XY colour of the light (from after the event occurred)
+ * @return The new XY colour of the light
+ */
+ public ColourXY getNewColourXY(){
+ return new ColourXY(getNewProperties().getColourX(), getNewProperties().getColourY());
+ }
+
+ /**
+ * Get the old RGB colour of the light (from before the event occurred)
+ * @return The old RGB colour of the light
+ */
+ public ColourRGB getOldColourRGB() {
+ return ColourRGB.fromHS(getOldProperties().getHue() != null ? getOldProperties().getHue() : 0, getOldProperties().getSaturation() != null ? getOldProperties().getSaturation() : 0);
+ }
+
+ /**
+ * Get the new RGB colour of the light (from after the event occurred)
+ * @return The new RGB colour of the light
+ */
+ public ColourRGB getNewColourRGB() {
+ return ColourRGB.fromHS(getNewProperties().getHue() != null ? getNewProperties().getHue() : 0, getNewProperties().getSaturation() != null ? getNewProperties().getSaturation() : 0);
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeColourTemperatureEvent.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeColourTemperatureEvent.java
new file mode 100644
index 000000000..bf7deaeb8
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeColourTemperatureEvent.java
@@ -0,0 +1,37 @@
+package org.openremote.agent.protocol.tradfri.device.event;
+
+import org.openremote.agent.protocol.tradfri.device.Light;
+import org.openremote.agent.protocol.tradfri.device.LightProperties;
+
+/**
+ * The class that represents a light colour temperature changed event that occurred to an IKEA TRÅDFRI light
+ */
+public class LightChangeColourTemperatureEvent extends LightChangeEvent {
+
+ /**
+ * Construct the LightChangeColourTemperatureEvent class
+ * @param light The light for which the event occurred
+ * @param oldProperties The old properties of the light (from before the event occurred)
+ * @param newProperties The new properties of the light (from after the event occurred)
+ */
+ public LightChangeColourTemperatureEvent(Light light, LightProperties oldProperties, LightProperties newProperties) {
+ super(light, oldProperties, newProperties);
+ }
+
+ /**
+ * Get the old colour temperature of the light (from before the event occurred)
+ * @return The old colour temperature of the light
+ */
+ public int getOldColourTemperature(){
+ return getOldProperties().getColourTemperature();
+ }
+
+ /**
+ * Get the new colour temperature of the light (from after the event occurred)
+ * @return The new colour temperature of the light
+ */
+ public int getNewColourTemperature(){
+ return getNewProperties().getColourTemperature();
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeEvent.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeEvent.java
new file mode 100644
index 000000000..00a1b09cb
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeEvent.java
@@ -0,0 +1,49 @@
+package org.openremote.agent.protocol.tradfri.device.event;
+
+import org.openremote.agent.protocol.tradfri.device.Light;
+import org.openremote.agent.protocol.tradfri.device.LightProperties;
+
+/**
+ * The class that represents a light changed event that occurred to an IKEA TRÅDFRI light
+ */
+public class LightChangeEvent extends LightEvent {
+
+ /**
+ * The old properties of the light (from before the event occurred)
+ */
+ private LightProperties oldProperties;
+
+ /**
+ * The new properties of the light (from after the event occurred)
+ */
+ private LightProperties newProperties;
+
+ /**
+ * Construct the LightChangeEvent class
+ * @param light The light for which the event occurred
+ * @param oldProperties The old properties of the light (from before the event occurred)
+ * @param newProperties The new properties of the light (from after the event occurred)
+ */
+ public LightChangeEvent(Light light, LightProperties oldProperties, LightProperties newProperties) {
+ super(light);
+ this.oldProperties = oldProperties;
+ this.newProperties = newProperties;
+ }
+
+ /**
+ * Get the old properties of the light (from before the event occurred)
+ * @return The old properties of the light
+ */
+ public LightProperties getOldProperties(){
+ return oldProperties;
+ }
+
+ /**
+ * Get the new properties of the light (from after the event occurred)
+ * @return The new properties of the light
+ */
+ public LightProperties getNewProperties(){
+ return newProperties;
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeOnEvent.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeOnEvent.java
new file mode 100644
index 000000000..9bab2844b
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightChangeOnEvent.java
@@ -0,0 +1,37 @@
+package org.openremote.agent.protocol.tradfri.device.event;
+
+import org.openremote.agent.protocol.tradfri.device.Light;
+import org.openremote.agent.protocol.tradfri.device.LightProperties;
+
+/**
+ * The class that represents a light on / off state changed event that occurred to an IKEA TRÅDFRI light
+ */
+public class LightChangeOnEvent extends LightChangeEvent {
+
+ /**
+ * Construct the LightChangeOnEvent class
+ * @param light The light for which the event occurred
+ * @param oldProperties The old properties of the light (from before the event occurred)
+ * @param newProperties The new properties of the light (from after the event occurred)
+ */
+ public LightChangeOnEvent(Light light, LightProperties oldProperties, LightProperties newProperties) {
+ super(light, oldProperties, newProperties);
+ }
+
+ /**
+ * Get the old on / off state of the light (from before the event occurred)
+ * @return The old on / off state of the light (true for on, false for off)
+ */
+ public boolean getOldOn(){
+ return getOldProperties().getOn();
+ }
+
+ /**
+ * Get the new on / off state of the light (from after the event occurred)
+ * @return The new on / off state of the light (true for on, false for off)
+ */
+ public boolean getNewOn(){
+ return getNewProperties().getOn();
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightEvent.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightEvent.java
new file mode 100644
index 000000000..5df42e397
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/LightEvent.java
@@ -0,0 +1,26 @@
+package org.openremote.agent.protocol.tradfri.device.event;
+
+import org.openremote.agent.protocol.tradfri.device.Light;
+
+/**
+ * The class that represents a light event that occurred to an IKEA TRÅDFRI light
+ */
+public class LightEvent extends DeviceEvent {
+
+ /**
+ * Construct the LightEvent class
+ * @param light The light for which the event occurred
+ */
+ public LightEvent(Light light) {
+ super(light);
+ }
+
+ /**
+ * Get the light for which the event occurred
+ * @return The light for which the event occurred
+ */
+ public Light getLight(){
+ return (Light) getDevice();
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/PlugChangeEvent.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/PlugChangeEvent.java
new file mode 100644
index 000000000..fbeba024a
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/PlugChangeEvent.java
@@ -0,0 +1,49 @@
+package org.openremote.agent.protocol.tradfri.device.event;
+
+import org.openremote.agent.protocol.tradfri.device.Plug;
+import org.openremote.agent.protocol.tradfri.device.PlugProperties;
+
+/**
+ * The class that represents a change event that occurred to an IKEA TRÅDFRI plug
+ */
+public class PlugChangeEvent extends PlugEvent {
+
+ /**
+ * The old properties of the plug (from before the event occurred)
+ */
+ private PlugProperties oldProperties;
+
+ /**
+ * The new properties of the plug (from after the event occurred)
+ */
+ private PlugProperties newProperties;
+
+ /**
+ * Construct the PlugChangeEvent class
+ * @param plug The plug for which the event occurred
+ * @param oldProperties The old properties of the plug (from before the event occurred)
+ * @param newProperties The new properties of the plug (from after the event occurred)
+ */
+ public PlugChangeEvent(Plug plug, PlugProperties oldProperties, PlugProperties newProperties) {
+ super(plug);
+ this.oldProperties = oldProperties;
+ this.newProperties = newProperties;
+ }
+
+ /**
+ * Get the old properties of the plug (from before the event occurred)
+ * @return The old properties of the plug
+ */
+ public PlugProperties getOldProperties(){
+ return oldProperties;
+ }
+
+ /**
+ * Get the new properties of the plug (from after the event occurred)
+ * @return The new properties of the plug
+ */
+ public PlugProperties getNewProperties(){
+ return newProperties;
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/PlugChangeOnEvent.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/PlugChangeOnEvent.java
new file mode 100644
index 000000000..77dfe26a0
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/PlugChangeOnEvent.java
@@ -0,0 +1,37 @@
+package org.openremote.agent.protocol.tradfri.device.event;
+
+import org.openremote.agent.protocol.tradfri.device.Plug;
+import org.openremote.agent.protocol.tradfri.device.PlugProperties;
+
+/**
+ * The class that represents a plug on / off state changed event that occurred to an IKEA TRÅDFRI plug
+ */
+public class PlugChangeOnEvent extends PlugChangeEvent {
+
+ /**
+ * Construct the PlugChangeOnEvent class
+ * @param plug The plug for which the event occurred
+ * @param oldProperties The old properties of the plug (from before the event occurred)
+ * @param newProperties The new properties of the plug (from after the event occurred)
+ */
+ public PlugChangeOnEvent(Plug plug, PlugProperties oldProperties, PlugProperties newProperties) {
+ super(plug, oldProperties, newProperties);
+ }
+
+ /**
+ * Get the old on / off state of the light (from before the event occurred)
+ * @return The old on / off state of the light (true for on, false for off)
+ */
+ public boolean getOldOn(){
+ return getOldProperties().getOn();
+ }
+
+ /**
+ * Get the new on / off state of the light (from after the event occurred)
+ * @return The new on / off state of the light (true for on, false for off)
+ */
+ public boolean getNewOn(){
+ return getNewProperties().getOn();
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/PlugEvent.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/PlugEvent.java
new file mode 100644
index 000000000..4a9d4b05a
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/device/event/PlugEvent.java
@@ -0,0 +1,26 @@
+package org.openremote.agent.protocol.tradfri.device.event;
+
+import org.openremote.agent.protocol.tradfri.device.Plug;
+
+/**
+ * The class that represents a plug event that occurred to an IKEA TRÅDFRI plug
+ */
+public class PlugEvent extends DeviceEvent {
+
+ /**
+ * Construct the PlugEvent class
+ * @param plug The plug for which the event occurred
+ */
+ public PlugEvent(Plug plug) {
+ super(plug);
+ }
+
+ /**
+ * Get the plug for which the event occurred
+ * @return The plug for which the event occurred
+ */
+ public Plug getPlug(){
+ return (Plug) getDevice();
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/payload/AuthenticateRequest.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/payload/AuthenticateRequest.java
new file mode 100644
index 000000000..831110254
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/payload/AuthenticateRequest.java
@@ -0,0 +1,41 @@
+package org.openremote.agent.protocol.tradfri.payload;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.agent.protocol.tradfri.util.ApiCode;
+
+/**
+ * The class that contains the payload for a request to authenticate to the IKEA TRÅDFRI gateway
+ */
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class AuthenticateRequest {
+
+ /**
+ * The identity of the client to register to the IKEA TRÅDFRI gateway
+ */
+ @JsonProperty(ApiCode.IDENTITY)
+ private String identity;
+
+ /**
+ * Construct the AuthenticateRequest class
+
+ */
+ public AuthenticateRequest(){
+ }
+
+ /**
+ * Get the identity of the client to register to the IKEA TRÅDFRI gateway
+ * @return The identity of the client to register to the IKEA TRÅDFRI gateway
+ */
+ public String getIdentity() {
+ return this.identity;
+ }
+
+ /**
+ * Set the identity of the client to register to the IKEA TRÅDFRI gateway
+ * @param identity The new identity of the client to register to the IKEA TRÅDFRI gateway
+ */
+ public void setIdentity(String identity) {
+ this.identity = identity;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/payload/AuthenticateResponse.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/payload/AuthenticateResponse.java
new file mode 100644
index 000000000..b3006ab71
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/payload/AuthenticateResponse.java
@@ -0,0 +1,62 @@
+package org.openremote.agent.protocol.tradfri.payload;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.agent.protocol.tradfri.util.ApiCode;
+
+/**
+ * The class that contains the payload of a response to the authenticate request from the IKEA TRÅDFRI gateway
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AuthenticateResponse {
+
+ /**
+ * The preshared key that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ @JsonProperty(ApiCode.PRESHARED_KEY)
+ private String presharedKey;
+
+ /**
+ * The firmware version of the IKEA TRÅDFRI gateway
+ */
+ @JsonProperty(ApiCode.GATEWAY_FIRMWARE_VERSION)
+ private String gatewayFirmwareVersion;
+
+ /**
+ * Construct the AuthenticateResponse class
+ */
+ public AuthenticateResponse(){
+ }
+
+ /**
+ * Get the preshared key that can be used to authenticate to the IKEA TRÅDFRI gateway
+ * @return The preshared key that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public String getPresharedKey() {
+ return this.presharedKey;
+ }
+
+ /**
+ * Get the firmware version of the IKEA TRÅDFRI gateway
+ * @return The firmware version of the IKEA TRÅDFRI gateway
+ */
+ public String getGatewayFirmwareVersion() {
+ return this.gatewayFirmwareVersion;
+ }
+
+ /**
+ * Set the preshared key that can be used to authenticate to the IKEA TRÅDFRI gateway
+ * @param presharedKey The new preshared key that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public void setPresharedKey(String presharedKey) {
+ this.presharedKey = presharedKey;
+ }
+
+ /**
+ * Set the firmware version of the IKEA TRÅDFRI gateway
+ * @param gatewayFirmwareVersion The new firmware version of the IKEA TRÅDFRI gateway
+ */
+ public void setGatewayFirmwareVersion(String gatewayFirmwareVersion) {
+ this.gatewayFirmwareVersion = gatewayFirmwareVersion;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/payload/DeviceRequest.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/payload/DeviceRequest.java
new file mode 100644
index 000000000..ab9882ec6
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/payload/DeviceRequest.java
@@ -0,0 +1,64 @@
+package org.openremote.agent.protocol.tradfri.payload;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.agent.protocol.tradfri.device.LightProperties;
+import org.openremote.agent.protocol.tradfri.device.PlugProperties;
+import org.openremote.agent.protocol.tradfri.util.ApiCode;
+
+/**
+ * The class that contains the payload for a request to update a IKEA TRÅDFRI device
+ */
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class DeviceRequest {
+
+ /**
+ * The new properties of the light (if the device is a light)
+ */
+ @JsonProperty(ApiCode.LIGHT)
+ private LightProperties[] lightProperties;
+
+ /**
+ * The new properties of the plug (if the device is a plug)
+ */
+ @JsonProperty(ApiCode.PLUG)
+ private PlugProperties[] plugProperties;
+
+ /**
+ * Construct the DeviceRequest class
+ */
+ public DeviceRequest(){
+ }
+
+ /**
+ * Get the new properties of the light (if the device is a light)
+ * @return The new properties of the light
+ */
+ public LightProperties[] getLightProperties() {
+ return this.lightProperties;
+ }
+
+ /**
+ * Get the new properties of the plug (if the device is a plug)
+ * @return The new properties of the plug
+ */
+ public PlugProperties[] getPlugProperties() {
+ return this.plugProperties;
+ }
+
+ /**
+ * Set the new properties of the light (if the device is a light)
+ * @param lightProperties The new properties of the light
+ */
+ public void setLightProperties(LightProperties[] lightProperties) {
+ this.lightProperties = lightProperties;
+ }
+
+ /**
+ * Set the new properties of the plug (if the device is a plug)
+ * @param plugProperties The new properties of the plug
+ */
+ public void setPlugProperties(PlugProperties[] plugProperties) {
+ this.plugProperties = plugProperties;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/payload/DeviceResponse.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/payload/DeviceResponse.java
new file mode 100644
index 000000000..4fde67b42
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/payload/DeviceResponse.java
@@ -0,0 +1,153 @@
+package org.openremote.agent.protocol.tradfri.payload;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.agent.protocol.tradfri.device.DeviceInfo;
+import org.openremote.agent.protocol.tradfri.device.LightProperties;
+import org.openremote.agent.protocol.tradfri.device.PlugProperties;
+import org.openremote.agent.protocol.tradfri.util.ApiCode;
+
+/**
+ * The class that contains the payload for a response of an IKEA TRÅDFRI device
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class DeviceResponse {
+
+ /**
+ * The name of the device
+ */
+ @JsonProperty(ApiCode.NAME)
+ private String name;
+
+ /**
+ * The creation date of the device
+ */
+ @JsonProperty(ApiCode.CREATION_DATE)
+ private Long creationDate;
+
+ /**
+ * The instance id of the device
+ */
+ @JsonProperty(ApiCode.INSTANCE_ID)
+ private Integer instanceId;
+
+ /**
+ * The information of the device
+ */
+ @JsonProperty(ApiCode.DEVICE_INFORMATION)
+ private DeviceInfo deviceInfo;
+
+ /**
+ * The properties of the light (if the device is a light)
+ */
+ @JsonProperty(ApiCode.LIGHT)
+ private LightProperties[] lightProperties;
+
+ /**
+ * The properties of the plug (if the device is a plug)
+ */
+ @JsonProperty(ApiCode.PLUG)
+ private PlugProperties[] plugProperties;
+
+ /**
+ * Construct the DeviceResponse class
+ */
+ public DeviceResponse(){
+ }
+
+ /**
+ * Get the name of the device
+ * @return The name of the device
+ */
+ public String getName() {
+ return this.name;
+ }
+
+ /**
+ * Get the creation date of the device
+ * @return The creation date of the device
+ */
+ public Long getCreationDate() {
+ return this.creationDate;
+ }
+
+ /**
+ * Get the instance id of the device
+ * @return The instance id of the device
+ */
+ public Integer getInstanceId() {
+ return this.instanceId;
+ }
+
+ /**
+ * Get the information of the device
+ * @return The instance id of the device
+ */
+ public DeviceInfo getDeviceInfo() {
+ return this.deviceInfo;
+ }
+
+ /**
+ * Get the properties of the light (if the device is a light)
+ * @return The properties of the light
+ */
+ public LightProperties[] getLightProperties() {
+ return this.lightProperties;
+ }
+
+ /**
+ * Get the properties of the plug (if the device is a plug)
+ * @return The properties of the plug
+ */
+ public PlugProperties[] getPlugProperties() {
+ return this.plugProperties;
+ }
+
+ /**
+ * Set the name of the device
+ * @param name The name of the device
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Set the creation date of the device
+ * @param creationDate The creation date of the device
+ */
+ public void setCreationDate(Long creationDate) {
+ this.creationDate = creationDate;
+ }
+
+ /**
+ * Set the instance id of the device
+ * @param instanceId The instance id of the device
+ */
+ public void setInstanceId(Integer instanceId) {
+ this.instanceId = instanceId;
+ }
+
+ /**
+ * Set the information of the device
+ * @param deviceInfo The information of the device
+ */
+ public void setDeviceInfo(DeviceInfo deviceInfo) {
+ this.deviceInfo = deviceInfo;
+ }
+
+ /**
+ * Set the properties of the light (if the device is a light)
+ * @param lightProperties The new properties of the light
+ */
+ public void setLightProperties(LightProperties[] lightProperties) {
+ this.lightProperties = lightProperties;
+ }
+
+ /**
+ * Set the properties of the plug (if the device is a plug)
+ * @param plugProperties The new properties of the plug
+ */
+ public void setPlugProperties(PlugProperties[] plugProperties) {
+ this.plugProperties = plugProperties;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/ApiCode.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/ApiCode.java
new file mode 100644
index 000000000..c6cda2e8a
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/ApiCode.java
@@ -0,0 +1,228 @@
+package org.openremote.agent.protocol.tradfri.util;
+
+/**
+ * The class that contains constants to find codes for the properties in the requests and responses for the IKEA TRÅDFRI API
+ */
+public class ApiCode {
+
+ /**
+ * Construct the ApiCode class
+ */
+ private ApiCode() {
+ }
+
+ // General
+
+ /**
+ * The IKEA TRÅDFRI API code for a name property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String NAME = "9001";
+
+ /**
+ * The IKEA TRÅDFRI API code for a creation date property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String CREATION_DATE = "9002";
+
+ /**
+ * The IKEA TRÅDFRI API code for an instance id property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String INSTANCE_ID = "9003";
+
+ /**
+ * The IKEA TRÅDFRI API code for a on / off state property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String ON_OFF = "5850";
+
+ /**
+ * The IKEA TRÅDFRI API code for a brightness property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String BRIGHTNESS = "5851";
+
+ /**
+ * The IKEA TRÅDFRI API code for a transition time property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String TRANSITION_TIME = "5712";
+
+ // Devices
+
+ /**
+ * The IKEA TRÅDFRI API code for a motion sensor property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String MOTION_SENSOR = "3300";
+
+ /**
+ * The IKEA TRÅDFRI API code for a light property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String LIGHT = "3311";
+
+ /**
+ * The IKEA TRÅDFRI API code for a plug property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String PLUG = "3312";
+
+ /**
+ * The IKEA TRÅDFRI API code for a blind property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String BLIND = "15015";
+
+ // Device Information
+
+ /**
+ * The IKEA TRÅDFRI API code for device information<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String DEVICE_INFORMATION = "3";
+
+ /**
+ * The IKEA TRÅDFRI API code for a device manufacturer<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String MANUFACTURER = "0";
+
+ /**
+ * The IKEA TRÅDFRI API code for a device model name<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String MODEL_NAME = "1";
+
+ /**
+ * The IKEA TRÅDFRI API code for a device serial<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String SERIAL = "2";
+
+ /**
+ * The IKEA TRÅDFRI API code for a device firmware version<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String FIRMWARE_VERSION = "3";
+
+ /**
+ * The IKEA TRÅDFRI API code for a device power source<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String POWER_SOURCE = "6";
+
+ /**
+ * The IKEA TRÅDFRI API code for a device manufacturer<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String BATTERY_LEVEL = "9";
+
+ // Lights
+
+ /**
+ * The IKEA TRÅDFRI API code for a hexadecimal colour property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String COLOUR_HEX = "5706";
+
+ /**
+ * The IKEA TRÅDFRI API code for a hue property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String HUE = "5707";
+
+ /**
+ * The IKEA TRÅDFRI API code for a saturation property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String SATURATION = "5708";
+
+ /**
+ * The IKEA TRÅDFRI API code for a X value of a colour property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String COLOUR_X = "5709";
+
+ /**
+ * The IKEA TRÅDFRI API code for a Y value of a colour property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String COLOUR_Y = "5710";
+
+ /**
+ * The IKEA TRÅDFRI API code for a colour temperature property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String COLOUR_TEMPERATURE = "5711";
+
+ // Blinds
+
+ /**
+ * The IKEA TRÅDFRI API code for a blind position property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String POSITION = "5536";
+
+ // Groups
+
+ /**
+ * The IKEA TRÅDFRI API code for a accessory link remote property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String ACCESSORY_LINK_REMOTE = "9018";
+
+ /**
+ * The IKEA TRÅDFRI API code for a scene id property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String SCENE_ID = "9039";
+
+ // Scenes
+
+ /**
+ * The IKEA TRÅDFRI API code for a scene active state property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String SCENE_ACTIVE_STATE = "9058";
+
+ /**
+ * The IKEA TRÅDFRI API code for a device index id property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String DEVICE_INDEX_ID = "9057";
+
+ /**
+ * The IKEA TRÅDFRI API code for a predefined scene property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String IS_SCENE_PREDEFINED = "9068";
+
+ /**
+ * The IKEA TRÅDFRI API code for a light settings property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String LIGHT_SETTINGS = "15013";
+
+ // Gateway
+
+ /**
+ * The IKEA TRÅDFRI API code for an identity property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String IDENTITY = "9090";
+
+ /**
+ * The IKEA TRÅDFRI API code for a preshared key property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String PRESHARED_KEY = "9091";
+
+ /**
+ * The IKEA TRÅDFRI API code for a gateway firmware version property<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String GATEWAY_FIRMWARE_VERSION = "9029";
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/ApiEndpoint.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/ApiEndpoint.java
new file mode 100644
index 000000000..aba9ea21f
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/ApiEndpoint.java
@@ -0,0 +1,116 @@
+package org.openremote.agent.protocol.tradfri.util;
+
+/**
+ * The class that contains helper functions and constants to find CoAP endpoints for the IKEA TRÅDFRI gateway
+ */
+public class ApiEndpoint {
+
+ /**
+ * The IP-address of the IKEA TRÅDFRI gateway
+ */
+ private static String gatewayIp;
+
+ /**
+ * Construct the ApiEndpoint class
+ */
+ private ApiEndpoint() {
+ }
+
+ /**
+ * Get the IP-address of the IKEA TRÅDFRI gateway
+ * @return The IP-address of the IKEA TRÅDFRI gateway
+ */
+ public static String getGatewayIp() {
+ return ApiEndpoint.gatewayIp;
+ }
+
+ /**
+ * Set the IP-address of the IKEA TRÅDFRI gateway
+ * @param ip The IP-address of the IKEA TRÅDFRI gateway
+ */
+ public static void setGatewayIp(String ip){
+ gatewayIp = ip;
+ }
+
+ /**
+ * Get the base URL of the IKEA TRÅDFRI API
+ * @return The base URL of the IKEA TRÅDFRI API
+ */
+ public static String getBaseUrl(){
+ return "coaps://"+gatewayIp+":5684";
+ }
+
+ /**
+ * Get the URI of an endpoint of the IKEA TRÅDFRI API
+ * @param endpoint The endpoint paths
+ * @return The URI of the endpoint of the IKEA TRÅDFRI API
+ */
+ public static String getUri(String... endpoint){
+ return getBaseUrl()+"/"+String.join("/", endpoint);
+ }
+
+ // Gateway
+
+ /**
+ * The endpoint to authenticate a new client to the IKEA TRÅDFRI gateway<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String AUTHENTICATE = "15011/9063";
+
+ /**
+ * The endpoint to reboot the IKEA TRÅDFRI gateway<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String GATEWAY_REBOOT = "15011/9030";
+
+ /**
+ * The endpoint to reset the IKEA TRÅDFRI gateway<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String GATEWAY_RESET = "15011/9031";
+
+ /**
+ * The endpoint to update the firmware of the IKEA TRÅDFRI gateway<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String GATEWAY_UPDATE_FIRMWARE = "15011/9034";
+
+ /**
+ * The endpoint to get the details of the IKEA TRÅDFRI gateway<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String GATEWAY_DETAILS = "15011/15012";
+
+ // Global
+
+ /**
+ * The endpoint for IKEA TRÅDFRI devices<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String DEVICES = "15001";
+
+ /**
+ * The endpoint for IKEA TRÅDFRI groups<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String GROUPS = "15004";
+
+ /**
+ * The endpoint for IKEA TRÅDFRI scenes<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String SCENES = "15005";
+
+ /**
+ * The endpoint for IKEA TRÅDFRI notifications<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String NOTIFICATIONS = "15006";
+
+ /**
+ * The endpoint for IKEA TRÅDFRI smart tasks<br>
+ * <i>Value: {@value}</i>
+ */
+ public static final String SMART_TASKS = "15010";
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/CoapClient.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/CoapClient.java
new file mode 100644
index 000000000..fdf24b611
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/CoapClient.java
@@ -0,0 +1,207 @@
+package org.openremote.agent.protocol.tradfri.util;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.eclipse.californium.core.CoapHandler;
+import org.eclipse.californium.core.CoapObserveRelation;
+import org.eclipse.californium.core.coap.MediaTypeRegistry;
+import org.eclipse.californium.core.coap.Request;
+import org.eclipse.californium.core.coap.Response;
+import org.eclipse.californium.core.network.CoapEndpoint;
+import org.eclipse.californium.core.network.Endpoint;
+import org.eclipse.californium.core.network.EndpointManager;
+import org.eclipse.californium.scandium.DTLSConnector;
+import org.eclipse.californium.scandium.config.DtlsConnectorConfig;
+import org.eclipse.californium.scandium.dtls.pskstore.InMemoryPskStore;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+
+/**
+ * The class that is used to communicate with the IKEA TRÅDFRI gateway using the CoAP protocol
+ */
+public class CoapClient {
+
+ /**
+ * An object mapper used for mapping JSON responses from the IKEA TRÅDFRI gateway to Java classes
+ */
+ private ObjectMapper objectMapper;
+
+ /**
+ * The credentials used to authenticate the CoAP client to the IKEA TRÅDFRI gateway
+ */
+ private Credentials credentials;
+
+ /**
+ * A DTLS endpoint used to secure the connection between the CoAP client and the IKEA TRÅDFRI gateway
+ */
+ private Endpoint dtlsEndpoint;
+
+ /**
+ * The timeout for connections between the CoAP client and the IKEA TRÅDFRI gateway (in milliseconds)
+ * @value 20000
+ */
+ private long timeout = 20000L;
+
+ /**
+ * Construct the CoapClient class
+ */
+ public CoapClient(){
+ objectMapper = new ObjectMapper();
+ }
+
+ /**
+ * Get the credentials used to communicate with the IKEA TRÅDFRI gateway
+ * @return The credentials that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public Credentials getCredentials() {
+ return this.credentials;
+ }
+
+ /**
+ * Change the credentials used to communicate with the IKEA TRÅDFRI gateway
+ * @param credentials The new credentials that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public void setCredentials(Credentials credentials){
+ this.credentials = credentials;
+ try {
+ updateDtlsConnector();
+ } catch (IOException ignored) { }
+ }
+
+ /**
+ * Set up a secure connection between the CoAP client and the IKEA TRÅDFRI gateway
+ * @throws IOException Thrown if a failure to open a connection between the CoAP client and the IKEA TRÅDFRI gateway occurs
+ */
+ private void updateDtlsConnector() throws IOException {
+ if(dtlsEndpoint != null) dtlsEndpoint.destroy();
+ DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder();
+ builder.setAddress(new InetSocketAddress(0));
+ InMemoryPskStore pskStore = new InMemoryPskStore();
+ pskStore.addKnownPeer(new InetSocketAddress(ApiEndpoint.getGatewayIp(), 5684),
+ credentials.getIdentity(),
+ credentials.getKey().getBytes());
+ builder.setPskStore(pskStore);
+
+ DTLSConnector dtlsconnector = new DTLSConnector(builder.build(), null);
+ CoapEndpoint.Builder endpointBuilder = new CoapEndpoint.Builder();
+ endpointBuilder.setConnector(dtlsconnector);
+
+ dtlsEndpoint = endpointBuilder.build();
+ dtlsEndpoint.start();
+ EndpointManager.getEndpointManager().setDefaultEndpoint(dtlsEndpoint);
+ }
+
+ /**
+ * Get timeout for connections between the CoAP client and the IKEA TRÅDFRI gateway (in milliseconds)
+ * @return The timeout for connections between the CoAP client and the IKEA TRÅDFRI gateway (in milliseconds)
+ */
+ public long getTimeout() {
+ return this.timeout;
+ }
+
+ /**
+ * Change the timeout for connections between the CoAP client and the IKEA TRÅDFRI gateway (in milliseconds)
+ * @param timeout The new timeout for connections between the CoAP client and the IKEA TRÅDFRI gateway (in milliseconds)
+ */
+ public void setTimeout(long timeout){
+ this.timeout = timeout;
+ }
+
+ /**
+ * Make a CoAP request to the specified endpoint
+ * @param request The Request object
+ * @param endpoint The endpoint to make a request to
+ * @param responseType The expected type of response
+ * @param <T> The expected type of response
+ * @return The response from the IKEA TRÅDFRI gateway (converted to the expected response type)
+ */
+ private <T> T request(Request request, String endpoint, Class<T> responseType) {
+ try {
+ request.setURI(endpoint);
+ request.send();
+ Response response = request.waitForResponse(timeout);
+ if (response == null) return null;
+ String responsePayload = response.getPayloadString();
+ if (responseType == String.class) return (T) responsePayload;
+ return objectMapper.readValue(responsePayload, responseType);
+ } catch (InterruptedException | JsonProcessingException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Make a CoAP request with a payload to the specified endpoint
+ * @param request The Request object
+ * @param endpoint The endpoint to make a request to
+ * @param payload The payload to send in the request
+ * @param responseType The expected type of response
+ * @param <T> The expected type of response
+ * @return The response from the IKEA TRÅDFRI gateway (converted to the expected response type)
+ */
+ private <T> T requestWithPayload(Request request, String endpoint, Object payload, Class<T> responseType) {
+ try {
+ String requestPayload = objectMapper.writeValueAsString(payload);
+ request.setPayload(requestPayload);
+ request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON);
+ return request(request, endpoint, responseType);
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Make a CoAP observe request to the specified endpoint
+ * @param endpoint The endpoint to make a request to
+ * @param handler The handler to handle the responses from the observe request
+ * @return The observe relation that represents the connection to the IKEA TRÅDFRI gateway
+ */
+ public CoapObserveRelation requestObserve(String endpoint, CoapHandler handler) {
+ org.eclipse.californium.core.CoapClient client = new org.eclipse.californium.core.CoapClient();
+ client.setTimeout(timeout);
+ Request request = Request.newGet();
+ request.setURI(endpoint);
+ request.setObserve();
+ CoapObserveRelation relation = client.observe(request, handler);
+ return relation;
+ }
+
+ /**
+ * Make a CoAP GET request to the specified endpoint
+ * @param endpoint The endpoint to make a request to
+ * @param responseType The expected type of response
+ * @param <T> The expected type of response
+ * @return The response from the IKEA TRÅDFRI gateway (converted to the expected response type)
+ */
+ public <T> T get(String endpoint, Class<T> responseType) {
+ Request request = Request.newGet();
+ return request(request, endpoint, responseType);
+ }
+
+ /**
+ * Make a CoAP POST request with a payload to the specified endpoint
+ * @param endpoint The endpoint to make a request to
+ * @param payload The payload to send in the request
+ * @param responseType The expected type of response
+ * @param <T> The expected type of response
+ * @return The response from the IKEA TRÅDFRI gateway (converted to the expected response type)
+ */
+ public <T> T post(String endpoint, Object payload, Class<T> responseType) {
+ Request request = Request.newPost();
+ return requestWithPayload(request, endpoint, payload, responseType);
+ }
+
+ /**
+ * Make a CoAP PUT request with a payload to the specified endpoint
+ * @param endpoint The endpoint to make a request to
+ * @param payload The payload to send in the request
+ * @param responseType The expected type of response
+ * @param <T> The expected type of response
+ * @return The response from the IKEA TRÅDFRI gateway (converted to the expected response type)
+ */
+ public <T> T put(String endpoint, Object payload, Class<T> responseType) {
+ Request request = Request.newPut();
+ return requestWithPayload(request, endpoint, payload, responseType);
+ }
+
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/ColourRGB.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/ColourRGB.java
new file mode 100644
index 000000000..eac328679
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/ColourRGB.java
@@ -0,0 +1,139 @@
+package org.openremote.agent.protocol.tradfri.util;
+
+import java.awt.*;
+
+/**
+ * The class that contains RGB values that make up a colour
+ */
+public class ColourRGB {
+
+ /**
+ * The red value of the colour
+ */
+ private Integer red;
+
+ /**
+ * The green value of the colour
+ */
+ private Integer green;
+
+ /**
+ * The blue value of the colour
+ */
+ private Integer blue;
+
+ /**
+ * Construct the ColourRGB class
+ * @param red The red value of the colour
+ * @param green The green value of the colour
+ * @param blue The blue value of the colour
+ */
+ public ColourRGB(Integer red, Integer green, Integer blue) {
+ this.red = red;
+ this.green = green;
+ this.blue = blue;
+ }
+
+ /**
+ * Construct the ColourRGB class
+ */
+ public ColourRGB() {
+ }
+
+ /**
+ * Get the red value of the colour
+ * @return The red value of the colour
+ */
+ public Integer getRed() {
+ return this.red;
+ }
+
+ /**
+ * Get the green value of the colour
+ * @return The green value of the colour
+ */
+ public Integer getGreen() {
+ return this.green;
+ }
+
+ /**
+ * Get the blue value of the colour
+ * @return The blue value of the colour
+ */
+ public Integer getBlue() {
+ return this.blue;
+ }
+
+ /**
+ * Set the red value of the colour
+ * @param red The new red value of the colour
+ */
+ public void setRed(Integer red) {
+ this.red = red;
+ }
+
+ /**
+ * Set the green value of the colour
+ * @param green The new green value of the colour
+ */
+ public void setGreen(Integer green) {
+ this.green = green;
+ }
+
+ /**
+ * Set the blue value of the colour
+ * @param blue The new blue value of the colour
+ */
+ public void setBlue(Integer blue) {
+ this.blue = blue;
+ }
+
+ /**
+ * Convert to the {@link ColourXY} class
+ * @return The {@link ColourXY} class
+ */
+ public ColourXY toXY(){
+ double red = Math.max(Math.min(this.red, 255), 0);
+ double green = Math.max(Math.min(this.green, 255), 0);
+ double blue = Math.max(Math.min(this.blue, 255), 0);
+
+ red = red / 255;
+ green = green / 255;
+ blue = blue / 255;
+
+ red = (red > 0.04045) ? Math.pow((red + 0.055) / (1.0 + 0.055), 2.4) : (red / 12.92);
+ green = (green > 0.04045) ? Math.pow((green + 0.055) / (1.0 + 0.055), 2.4) : (green / 12.92);
+ blue = (blue > 0.04045) ? Math.pow((blue + 0.055) / (1.0 + 0.055), 2.4) : (blue / 12.92);
+
+ double X = red * 0.4124564 + green * 0.3575761 + blue * 0.1804375;
+ double Y = red * 0.2126729 + green * 0.7151522 + blue * 0.0721750;
+ double Z = red * 0.0193339 + green * 0.1191920 + blue * 0.9503041;
+ double total = X + Y + Z;
+
+ double x = 0;
+ double y = 0;
+ if(total != 0){
+ x = X / total;
+ y = Y / total;
+ }
+
+ int xNormalised = (int) (x * 65535 + 0.5);
+ int yNormalised = (int) (y * 65535 + 0.5);
+
+ return new ColourXY(xNormalised, yNormalised);
+ }
+
+ /**
+ * Construct the ColourRGB class from the hue and saturation values
+ * @param hue The hue value
+ * @param saturation The saturation value
+ * @return The ColourRGB class
+ */
+ public static ColourRGB fromHS(int hue, int saturation){
+ float hueNormalised = hue/65535f;
+ float saturationNormalised = saturation/65535f;
+ int rgb = Color.HSBtoRGB(hueNormalised, saturationNormalised, 1);
+ Color colour = new Color(rgb);
+ return new ColourRGB(colour.getRed(), colour.getGreen(), colour.getBlue());
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/ColourXY.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/ColourXY.java
new file mode 100644
index 000000000..83b2e7fac
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/ColourXY.java
@@ -0,0 +1,74 @@
+package org.openremote.agent.protocol.tradfri.util;
+
+/**
+ * The class that contains XY values that make up a colour
+ */
+public class ColourXY {
+
+ /**
+ * The X value of the colour
+ */
+ private Integer X;
+
+ /**
+ * The Y value of the colour
+ */
+ private Integer Y;
+
+ /**
+ * Construct the ColourXY class
+ * @param X The X value of the colour
+ * @param Y The Y value of the colour
+ */
+ public ColourXY(Integer X, Integer Y) {
+ this.X = X;
+ this.Y = Y;
+ }
+
+ /**
+ * Construct the ColourXY class
+ */
+ public ColourXY() {
+ }
+
+ /**
+ * Get the X value of the colour
+ * @return The X value of the colour
+ */
+ public Integer getX() {
+ return this.X;
+ }
+
+ /**
+ * Get the Y value of the colour
+ * @return The Y value of the colour
+ */
+ public Integer getY() {
+ return this.Y;
+ }
+
+ /**
+ * Set the X value of the colour
+ * @param X The new X value of the colour
+ */
+ public void setX(Integer X) {
+ this.X = X;
+ }
+
+ /**
+ * Set the Y value of the colour
+ * @param Y The new Y value of the colour
+ */
+ public void setY(Integer Y) {
+ this.Y = Y;
+ }
+
+ /**
+ * Construct the ColourXY class from the {@link ColourRGB} class
+ * @param colourRGB The {@link ColourRGB} class
+ * @return The ColourXY class
+ */
+ public static ColourXY fromRGB(ColourRGB colourRGB){
+ return colourRGB.toXY();
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/Credentials.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/Credentials.java
new file mode 100644
index 000000000..f0f315122
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/util/Credentials.java
@@ -0,0 +1,65 @@
+package org.openremote.agent.protocol.tradfri.util;
+
+/**
+ * The class that contains the credentials used to authenticate to the IKEA TRÅDFRI gateway
+ */
+public class Credentials {
+
+ /**
+ * The identity that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ private String identity;
+
+ /**
+ * The key that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ private String key;
+
+ /**
+ * Construct the Credentials class
+ * @param identity The identity that can be used to authenticate to the IKEA TRÅDFRI gateway
+ * @param key The key that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public Credentials(String identity, String key) {
+ this.identity = identity;
+ this.key = key;
+ }
+
+ /**
+ * Construct the Credentials class
+ */
+ public Credentials() {
+ }
+
+ /**
+ * Get the identity that can be used to authenticate to the IKEA TRÅDFRI gateway
+ * @return The identity that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public String getIdentity() {
+ return this.identity;
+ }
+
+ /**
+ * Get the key that can be used to authenticate to the IKEA TRÅDFRI gateway
+ * @return The key that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public String getKey() {
+ return this.key;
+ }
+
+ /**
+ * Set the identity that can be used to authenticate to the IKEA TRÅDFRI gateway
+ * @param identity The new identity that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public void setIdentity(String identity) {
+ this.identity = identity;
+ }
+
+ /**
+ * Set the key that can be used to authenticate to the IKEA TRÅDFRI gateway
+ * @param key The new key that can be used to authenticate to the IKEA TRÅDFRI gateway
+ */
+ public void setKey(String key) {
+ this.key = key;
+ }
+}
diff --git a/agent/src/main/resources/META-INF/services/org.openremote.container.ContainerService b/agent/src/main/resources/META-INF/services/org.openremote.container.ContainerService
index e71e4baf9..9cefcb7cd 100644
--- a/agent/src/main/resources/META-INF/services/org.openremote.container.ContainerService
+++ b/agent/src/main/resources/META-INF/services/org.openremote.container.ContainerService
@@ -11,3 +11,4 @@ org.openremote.agent.protocol.artnet.ArtnetClientProtocol
org.openremote.agent.protocol.tcp.TcpClientProtocol
org.openremote.agent.protocol.serial.SerialClientProtocol
org.openremote.agent.protocol.event.ClientEventProtocol
+org.openremote.agent.protocol.tradfri.TradfriProtocol
\ No newline at end of file
diff --git a/gradle.properties b/gradle.properties
index 2b90c4e81..2b0b48f4a 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -52,3 +52,5 @@ simpleJavaMailVersion = 5.0.4
jaywayJsonPathVersion = 2.4.0
typescriptGeneratorVersion = 2.13.489
moquetteVersion = 0.13
+californiumCoreVersion = 2.1.0
+californiumScandiumVersion = 2.1.0
diff --git a/profile/deploy.yml b/profile/deploy.yml
index 56d811c69..77aba409a 100644
--- a/profile/deploy.yml
+++ b/profile/deploy.yml
@@ -24,6 +24,9 @@ services:
# Image will be pulled when using the `docker-compose pull` command or `docker-compose up --no-build`
image: openremote/proxy:${DATE_TAG:-latest}
+ # Uncomment to support the IKEA TRÅDFRI protocol. USE AT YOUR OWN RISK.
+ # network_mode: host
+
environment:
# It is important that all services have the same timezone and are time synchronized.
@@ -62,6 +65,9 @@ services:
# Available levels are: emerg, alert, crit, err, warning, notice, info, debug
# PROXY_LOGLEVEL: 'notice'
+ # Uncomment to support the IKEA TRÅDFRI protocol. USE AT YOUR OWN RISK.
+ # PROXY_BACKEND_HOST: 127.0.0.1
+
# Run proxy, obtain and automatically renew SSL certificates if DOMAINNAME is not localhost. Use
# the command 'help' to get a list of all options.
command: run
@@ -90,6 +96,9 @@ services:
# Image will be pulled when using the `docker-compose pull` command or `docker-compose up --no-build`
image: openremote/manager:${DATE_TAG:-latest}
+ # Uncomment to support the IKEA TRÅDFRI protocol. USE AT YOUR OWN RISK.
+ # network_mode: host
+
environment:
# It is important that all services have the same timezone and are time synchronized.
@@ -162,6 +171,12 @@ services:
KEYCLOAK_PORT: 8080
MASTER_REALM_KEYCLOAK_THEME: ${MASTER_REALM_KEYCLOAK_THEME:-openremote}
+ # Uncomment to support the IKEA TRÅDFRI protocol. USE AT YOUR OWN RISK.
+ # Also remove (or comment) the already existing variables with the same name.
+ # KEYCLOAK_HOST: 127.0.0.1
+ # KEYCLOAK_PORT: 8081
+ # DATABASE_CONNECTION_URL: jdbc:postgresql://localhost/openremote
+
# The service-internal webservice interface binding, bind to all interfaces
# when running in container. Default is 127.0.0.1.
WEBSERVER_LISTEN_HOST: 0.0.0.0
@@ -296,6 +311,10 @@ services:
options:
max-size: 10m
+ # Uncomment to support the IKEA TRÅDFRI protocol. USE AT YOUR OWN RISK.
+ # ports:
+ # - "8081:8080"
+
# PostgreSQL DBMS
postgresql:
@@ -330,6 +349,10 @@ services:
options:
max-size: 10m
+ # Uncomment to support the IKEA TRÅDFRI protocol. USE AT YOUR OWN RISK.
+ # ports:
+ # - "5432:5432"
+
# Map tile server for serving raster tiles using mbtiles
map:
build: '../map'