├── .dockerignore ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── pom.xml └── src └── main ├── assembly └── assembly.xml └── java └── uk └── me └── hardill └── TRADFRI2MQTT ├── Main.java └── TradfriConstants.java /.dockerignore: -------------------------------------------------------------------------------- 1 | .git 2 | .gitignore 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | pom.xml.tag 3 | pom.xml.releaseBackup 4 | pom.xml.versionsBackup 5 | pom.xml.next 6 | release.properties 7 | dependency-reduced-pom.xml 8 | buildNumber.properties 9 | .mvn/timing.properties 10 | 11 | !/.mvn/wrapper/maven-wrapper.jar 12 | 13 | Californium.properties 14 | .classpath 15 | .project 16 | .settings 17 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM maven:onbuild-alpine 2 | ENTRYPOINT ["java","-cp","target/*:target/libs/*","uk.me.hardill.TRADFRI2MQTT.Main"] 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Invocation 2 | 3 | java -jar TRADFRI2MQTT-X.X.X-SNAPSHOT.jar -ip {gateway IP} -psk {gateway secret} -broker {MQTT broker URL} [-retained] 4 | 5 | The optional `-retained` configures the MQTT topics as retained. 6 | 7 | e.g. 8 | 9 | `java -jar TRADFRI2MQTT-X.X.X-SNAPSHOT.jar -ip 192.168.1.XXX -psk xxxxxxxxxxxxxxxx -broker tcp://localhost` 10 | 11 | Publishes state messages on topics like this: 12 | 13 | - TRÅDFRI/bulb/Living Room Light/state/on 14 | - TRÅDFRI/bulb/Living Room Light/state/dim 15 | - TRÅDFRI/bulb/Living Room Light/state/temperature 16 | - TRÅDFRI/room/Living Room/state/on 17 | - TRÅDFRI/room/Living Room/state/dim 18 | 19 | Subscribes to control messages on topics like this: 20 | 21 | - TRÅDFRI/bulb/Living Room Light/control/on 22 | - TRÅDFRI/bulb/Living Room Light/control/dim 23 | - TRÅDFRI/bulb/Living Room Light/control/temperature 24 | - TRÅDFRI/room/Living Room/control/on 25 | - TRÅDFRI/room/Living Room/control/dim 26 | - TRÅDFRI/room/Living Room/control/mood 27 | 28 | publish 0/1 to the `on` topic to turn the light off/on respectively 29 | 30 | publish 0-254 to the `dim` topic to change the brightness 31 | 32 | publish "cold" / "normal" / "warm" to the `temperature` topic to change temperatures. 33 | This only works on individual bulbs. 34 | 35 | publish the name of a mood (case-sensitive) to the `mood` topic of a room to adapt that mood. 36 | IKEA predefined moods are internally uppercase-only for some reason: "EVERYDAY" / "FOCUS" / "RELAX". 37 | Your self-defined moods have to be spelled like in the Trådfri App. 38 | At the moment, only control is implemented and state is not. 39 | 40 | # MQTT broker example 41 | An easy-to-use MQTT broker is [mosquitto](https://mosquitto.org/). 42 | 43 | After installation run it locally with `mosquitto`. 44 | 45 | Then submit commands like this: 46 | `mosquitto_pub -t "TRÅDFRI/bulb/LivingRoomBulb1/control/temperature" -m warm` 47 | or subscribe like this: 48 | `mosquitto_sub -t "TRÅDFRI/room/LivingRoom/state/on"` 49 | 50 | # Installation on Docker 51 | 52 | Optionally, TRADFRI2MQTT can be installed and run within a Docker image using the following instructions: 53 | 54 | 1. Clone this GIT repository. 55 | 2. Build the tradfri2mqtt docker image like so: 56 | `docker build -t tradfri2mqtt .` 57 | 3. Run tradfri2mqtt within a docker container: 58 | `docker run -rm tradfri2mqtt -ip [gateway ip] -psk [gateway secret] -broker [mqtt broker url]` 59 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | uk.me.hardill 5 | TRADFRI2MQTT 6 | 0.0.9-SNAPSHOT 7 | jar 8 | 9 | TRADFRI2MQTT 10 | https://github.com/hardillb/TRADFRI2MQTT 11 | 12 | 13 | UTF-8 14 | 15 | 16 | 17 | 18 | 19 | org.apache.maven.plugins 20 | maven-compiler-plugin 21 | 3.2 22 | 23 | 1.8 24 | 1.8 25 | 26 | 27 | 28 | org.apache.maven.plugins 29 | maven-jar-plugin 30 | 3.0.2 31 | 32 | 33 | 34 | true 35 | libs/ 36 | uk.me.hardill.TRADFRI2MQTT.Main 37 | 38 | 39 | 40 | 41 | 42 | org.apache.maven.plugins 43 | maven-dependency-plugin 44 | 3.0.0 45 | 46 | 47 | copy-dependencies 48 | package 49 | 50 | copy-dependencies 51 | 52 | 53 | ${project.build.directory}/libs 54 | 55 | 56 | 57 | 58 | 59 | org.apache.maven.plugins 60 | maven-assembly-plugin 61 | 62 | 63 | src/main/assembly/assembly.xml 64 | 65 | 66 | 67 | 68 | package 69 | 70 | attached 71 | 72 | 73 | 74 | 75 | 76 | org.apache.maven.plugins 77 | maven-release-plugin 78 | 2.2.2 79 | 80 | 81 | org.apache.maven.plugins 82 | maven-scm-plugin 83 | 1.8.1 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | junit 97 | junit 98 | 4.13.1 99 | test 100 | 101 | 102 | org.json 103 | org.json 104 | chargebee-1.0 105 | 106 | 107 | org.eclipse.californium 108 | californium-core 109 | 1.0.5 110 | 111 | 112 | org.eclipse.californium 113 | scandium 114 | 1.0.5 115 | 116 | 117 | org.eclipse.californium 118 | element-connector 119 | 1.0.5 120 | 121 | 122 | org.eclipse.paho 123 | org.eclipse.paho.client.mqttv3 124 | 1.2.1 125 | 126 | 127 | commons-cli 128 | commons-cli 129 | 1.4 130 | 131 | 132 | org.apache.commons 133 | commons-collections4 134 | 4.1 135 | 136 | 137 | 138 | scm:git:git@github.com:hardillb/TRADFRI2MQTT.git 139 | https://github.com/hardillb/TRADFRI2MQTT 140 | scm:git:git@github.com:hardillb/TRADFRI2MQTT.git 141 | 142 | 143 | -------------------------------------------------------------------------------- /src/main/assembly/assembly.xml: -------------------------------------------------------------------------------- 1 | 2 | 1.0 3 | 4 | tar.gz 5 | 6 | false 7 | 12 | 13 | 14 | target 15 | / 16 | 17 | *.jar 18 | 19 | 20 | 21 | target/libs 22 | /libs 23 | 24 | *.jar 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/main/java/uk/me/hardill/TRADFRI2MQTT/Main.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package uk.me.hardill.TRADFRI2MQTT; 5 | 6 | import static uk.me.hardill.TRADFRI2MQTT.TradfriConstants.*; 7 | 8 | import java.net.InetSocketAddress; 9 | import java.net.URI; 10 | import java.net.URISyntaxException; 11 | import java.util.Arrays; 12 | import java.util.HashMap; 13 | import java.util.List; 14 | import java.util.ArrayList; 15 | import java.util.Vector; 16 | import java.util.concurrent.Executors; 17 | import java.util.concurrent.ScheduledExecutorService; 18 | import java.util.concurrent.TimeUnit; 19 | import java.util.stream.Collectors; 20 | 21 | import org.apache.commons.cli.CommandLine; 22 | import org.apache.commons.cli.CommandLineParser; 23 | import org.apache.commons.cli.DefaultParser; 24 | import org.apache.commons.cli.HelpFormatter; 25 | import org.apache.commons.cli.Options; 26 | import org.apache.commons.cli.ParseException; 27 | import org.apache.commons.collections4.BidiMap; 28 | import org.apache.commons.collections4.bidimap.DualHashBidiMap; 29 | import org.eclipse.californium.core.CaliforniumLogger; 30 | import org.eclipse.californium.core.CoapClient; 31 | import org.eclipse.californium.core.CoapHandler; 32 | import org.eclipse.californium.core.CoapObserveRelation; 33 | import org.eclipse.californium.core.CoapResponse; 34 | import org.eclipse.californium.core.coap.MediaTypeRegistry; 35 | import org.eclipse.californium.core.network.CoapEndpoint; 36 | import org.eclipse.californium.core.network.config.NetworkConfig; 37 | import org.eclipse.californium.scandium.DTLSConnector; 38 | import org.eclipse.californium.scandium.ScandiumLogger; 39 | import org.eclipse.californium.scandium.config.DtlsConnectorConfig; 40 | import org.eclipse.californium.scandium.dtls.pskstore.StaticPskStore; 41 | import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; 42 | import org.eclipse.paho.client.mqttv3.MqttCallback; 43 | import org.eclipse.paho.client.mqttv3.MqttClient; 44 | import org.eclipse.paho.client.mqttv3.MqttException; 45 | import org.eclipse.paho.client.mqttv3.MqttMessage; 46 | import org.eclipse.paho.client.mqttv3.MqttPersistenceException; 47 | import org.eclipse.paho.client.mqttv3.MqttConnectOptions; 48 | import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; 49 | import org.json.JSONArray; 50 | import org.json.JSONException; 51 | import org.json.JSONObject; 52 | 53 | /** 54 | * @author hardillb & r41d 55 | * 56 | */ 57 | public class Main { 58 | 59 | static { 60 | CaliforniumLogger.disableLogging(); 61 | ScandiumLogger.disable(); 62 | // ScandiumLogger.initialize(); 63 | // ScandiumLogger.setLevel(Level.FINE); 64 | } 65 | 66 | private DTLSConnector dtlsConnector; 67 | private MqttClient mqttClient; 68 | private CoapEndpoint endPoint; 69 | 70 | private String ip; 71 | private boolean retainedQueues; 72 | 73 | // mapping: device ID -> device names 74 | private BidiMap id2device = new DualHashBidiMap<>(); 75 | // mapping: room ID -> room name 76 | private BidiMap id2room = new DualHashBidiMap<>(); 77 | // mapping room ID -> Mood (ID,Name) 78 | // The outer HashMap must not be a BidiMap because it leads to bugs when more than one empty BidiMap is contained as a value 79 | private HashMap> roomID2moods = new HashMap<>(); 80 | private Vector watching = new Vector<>(); 81 | 82 | Main(String psk, String ip, String broker, boolean retained) { 83 | this.ip = ip; 84 | this.retainedQueues = retained; 85 | DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(new InetSocketAddress(0)); 86 | builder.setPskStore(new StaticPskStore("", psk.getBytes())); 87 | dtlsConnector = new DTLSConnector(builder.build()); 88 | endPoint = new CoapEndpoint(dtlsConnector, NetworkConfig.getStandard()); 89 | 90 | MemoryPersistence persistence = new MemoryPersistence(); 91 | try { 92 | mqttClient = new MqttClient(broker, MqttClient.generateClientId(), persistence); 93 | MqttConnectOptions opts = new MqttConnectOptions(); 94 | opts.setMaxInflight(200); 95 | opts.setAutomaticReconnect(true); 96 | mqttClient.connect(opts); 97 | mqttClient.setCallback(new MqttCallback() { 98 | 99 | @Override 100 | public void messageArrived(String topic, MqttMessage message) throws Exception { 101 | // TODO Auto-generated method stub 102 | System.out.println(topic + " " + message.toString()); 103 | String parts[] = topic.split("/"); 104 | 105 | String entityType = parts[1]; // bulb or room 106 | String entityName = parts[2]; // name of bulb or room 107 | assert parts[3].equals("control"); // something *really* went wrong if this doesn't hold 108 | String command = parts[4]; 109 | 110 | try { 111 | JSONObject json = new JSONObject(); 112 | String payload; 113 | 114 | switch (entityType) { 115 | 116 | case "bulb": // single bulb 117 | JSONObject settings = new JSONObject(); 118 | JSONArray array = new JSONArray(); 119 | array.put(settings); 120 | json.put(LIGHT, array); 121 | 122 | switch (command) { 123 | case "on": 124 | switch (message.toString()) { 125 | case "0": 126 | case "1": 127 | settings.put(ONOFF, Integer.parseInt(message.toString())); 128 | break; 129 | default: 130 | System.err.println("Invalid OnOff value '" + message.toString() + "'for bulb " + entityName); 131 | return; 132 | } 133 | break; 134 | case "dim": 135 | int dimval = Integer.parseInt(message.toString()); 136 | settings.put(DIMMER, Math.min(DIMMER_MAX, Math.max(DIMMER_MIN, dimval))); 137 | settings.put(TRANSITION_TIME, 3); // transition in seconds 138 | break; 139 | case "temperature": 140 | // not sure what the COLOR_X and COLOR_Y values 141 | // do, it works without them... 142 | switch (message.toString()) { 143 | case "cold": 144 | settings.put(COLOR, COLOR_COLD); 145 | break; 146 | case "normal": 147 | settings.put(COLOR, COLOR_NORMAL); 148 | break; 149 | case "warm": 150 | settings.put(COLOR, COLOR_WARM); 151 | break; 152 | default: 153 | System.err.println("Invalid temperature supplied: " + message.toString()); 154 | return; 155 | } 156 | break; 157 | default: 158 | System.err.println("Invalid command supplied: " + command); 159 | return; 160 | } 161 | payload = json.toString(); 162 | Main.this.set("coaps://" + Main.this.ip + "//" + DEVICES + "/" + id2device.getKey(entityName), payload); 163 | break; 164 | 165 | case "room": // whole room 166 | switch (command) { 167 | case "on": 168 | switch (message.toString()) { 169 | case "0": 170 | case "1": 171 | json.put(ONOFF, Integer.parseInt(message.toString())); 172 | break; 173 | default: 174 | System.err.println("Invalid OnOff value '" + message.toString() + "'for room " + entityName); 175 | return; 176 | } 177 | break; 178 | case "dim": 179 | json.put(DIMMER, Integer.parseInt(message.toString())); 180 | json.put(TRANSITION_TIME, 3); 181 | break; 182 | case "mood": 183 | String moodName = message.toString(); 184 | int roomID = id2room.getKey(entityName); 185 | Integer moodID = roomID2moods.get(roomID).getKey(moodName); 186 | if (moodID != null) { 187 | json.put(SCENE_ID, moodID); 188 | } else { 189 | System.err.println("Mood " + moodName + " for room " + entityName + " not found"); 190 | return; 191 | } 192 | break; 193 | default: 194 | System.err.println("Invalid command for room: " + command); 195 | return; 196 | } 197 | payload = json.toString(); 198 | System.err.println(payload); 199 | Main.this.set("coaps://" + Main.this.ip + "//" + GROUPS + "/" + id2room.getKey(entityName), payload); 200 | break; 201 | 202 | default: 203 | System.err.println("Invalid entityType: " + entityType); 204 | return; 205 | } 206 | 207 | } catch (Exception e) { 208 | // TODO Auto-generated catch block 209 | e.printStackTrace(); 210 | } 211 | } 212 | 213 | @Override 214 | public void deliveryComplete(IMqttDeliveryToken token) { 215 | // TODO Auto-generated method stub 216 | } 217 | 218 | @Override 219 | public void connectionLost(Throwable cause) { 220 | // TODO Auto-generated method stub 221 | } 222 | }); 223 | mqttClient.subscribe("TRÅDFRI/bulb/+/control/+"); 224 | mqttClient.subscribe("TRÅDFRI/room/+/control/+"); 225 | } catch (MqttException e) { 226 | // TODO Auto-generated catch block 227 | e.printStackTrace(); 228 | } 229 | 230 | ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); 231 | Runnable command = new Runnable() { 232 | @Override 233 | public void run() { 234 | System.out.println("re-reg"); 235 | for (CoapObserveRelation rel : watching) { 236 | rel.reregister(); 237 | } 238 | } 239 | }; 240 | executor.scheduleAtFixedRate(command, 120, 120, TimeUnit.SECONDS); 241 | } 242 | 243 | private void discover() { 244 | 245 | // Discover Bulbs 246 | try { 247 | URI uri = new URI("coaps://" + ip + "//" + DEVICES); 248 | CoapClient client = new CoapClient(uri); 249 | client.setEndpoint(endPoint); 250 | CoapResponse response = client.get(); 251 | if (response == null) { 252 | System.out.println("Connection to Gateway timed out, please check ip address or increase the ACK_TIMEOUT in the Californium.properties file"); 253 | System.exit(-1); 254 | } 255 | JSONArray devices = new JSONArray(response.getResponseText()); 256 | for (int i = 0; i < devices.length(); i++) { 257 | this.watch(DEVICES, ""+devices.getInt(i)); 258 | } 259 | client.shutdown(); 260 | } catch (URISyntaxException e) { 261 | // TODO Auto-generated catch block 262 | e.printStackTrace(); 263 | } catch (JSONException e) { 264 | // TODO Auto-generated catch block 265 | e.printStackTrace(); 266 | } 267 | 268 | // Discover Rooms/Groups 269 | try { 270 | URI uri = new URI("coaps://" + ip + "//" + GROUPS); 271 | CoapClient client = new CoapClient(uri); 272 | client.setEndpoint(endPoint); 273 | CoapResponse response = client.get(); 274 | if (response == null) { 275 | System.out.println("Connection to Gateway timed out, please check ip address or increase the ACK_TIMEOUT in the Californium.properties file"); 276 | System.exit(-1); 277 | } 278 | JSONArray rooms = new JSONArray(response.getResponseText()); 279 | for (int i = 0; i < rooms.length(); i++) { 280 | this.watch(GROUPS, "" + rooms.getInt(i)); 281 | } 282 | client.shutdown(); 283 | } catch (URISyntaxException e) { 284 | // TODO Auto-generated catch block 285 | e.printStackTrace(); 286 | } catch (JSONException e) { 287 | // TODO Auto-generated catch block 288 | e.printStackTrace(); 289 | } 290 | 291 | // Discover all Moods for all Rooms that were found 292 | // Moods are structured as follows: IP:5684/15005/RoomID/MoodID 293 | try { 294 | URI sceneURI = new URI("coaps://" + ip + "//" + SCENE); 295 | CoapClient client = new CoapClient(sceneURI); 296 | client.setEndpoint(endPoint); 297 | CoapResponse responseRooms = client.get(); 298 | if (responseRooms == null) { 299 | System.out.println("Connection to Gateway timed out, please check ip address or increase the ACK_TIMEOUT in the Californium.properties file"); 300 | System.exit(-1); 301 | } 302 | JSONArray moodRooms = new JSONArray(responseRooms.getResponseText()); 303 | for (int roomIdx = 0; roomIdx < moodRooms.length(); roomIdx++) { 304 | int roomID = moodRooms.getInt(roomIdx); 305 | // prepare Bidirectional Map for storing the moods for the current room 306 | roomID2moods.put(roomID, new DualHashBidiMap()); 307 | 308 | URI moodUri = new URI("coaps://" + ip + "//" + SCENE + "/" + roomID); 309 | client = new CoapClient(moodUri); 310 | client.setEndpoint(endPoint); 311 | CoapResponse responseMoods = client.get(); 312 | if (responseMoods == null) { 313 | System.out.println("Connection to Gateway timed out, please check ip address or increase the ACK_TIMEOUT in the Californium.properties file"); 314 | System.exit(-1); 315 | } 316 | JSONArray moodsIDs = new JSONArray(responseMoods.getResponseText()); 317 | for (int moodIdx = 0; moodIdx < moodsIDs.length(); moodIdx++) { 318 | this.watch(SCENE, "" + roomID, "" + moodsIDs.getInt(moodIdx)); 319 | } 320 | client.shutdown(); 321 | } 322 | } catch (URISyntaxException e) { 323 | // TODO Auto-generated catch block 324 | e.printStackTrace(); 325 | } catch (JSONException e) { 326 | // TODO Auto-generated catch block 327 | e.printStackTrace(); 328 | } 329 | 330 | } 331 | 332 | private void set(String uriString, String payload) { 333 | //System.out.println("payload\n" + payload); 334 | try { 335 | URI uri = new URI(uriString); 336 | CoapClient client = new CoapClient(uri); 337 | client.setEndpoint(endPoint); 338 | CoapResponse response = client.put(payload, MediaTypeRegistry.TEXT_PLAIN); 339 | if (response != null && response.isSuccess()) { 340 | //System.out.println("Yay"); 341 | } else { 342 | System.out.println("Sending payload to " + uriString + " failed!"); 343 | } 344 | client.shutdown(); 345 | } catch (URISyntaxException e) { 346 | // TODO Auto-generated catch block 347 | e.printStackTrace(); 348 | } 349 | } 350 | 351 | private void watch(String realm, final String... path) { 352 | 353 | try { 354 | String uriString = "coaps://" + ip + "//" + realm + "/" + Arrays.asList(path).stream().collect(Collectors.joining("/")); 355 | CoapClient client = new CoapClient(new URI(uriString)); 356 | client.setEndpoint(endPoint); 357 | CoapHandler handler = new CoapHandler() { 358 | 359 | @Override 360 | public void onLoad(CoapResponse response) { 361 | //System.out.println(response.getResponseText()); 362 | //System.out.println(response.getOptions().toString()); 363 | try { 364 | JSONObject json = new JSONObject(response.getResponseText()); 365 | int ID = json.getInt(INSTANCE_ID); 366 | String name = json.getString(NAME); 367 | // TODO change this test to something based on 5750 values 368 | // 2 = light? 369 | // 0 = remote/dimmer? 370 | if (json.has(TYPE) && json.getInt(TYPE) == TYPE_BULB && json.has(LIGHT)) { // single bulb 371 | String socket = ""; 372 | try { 373 | socket = " " + json.getJSONObject("3").getString("1"); 374 | if (socket.startsWith("TRADFRI bulb ")) { 375 | socket = " " + socket.split(" ")[3]; 376 | } 377 | } catch (JSONException e) {} 378 | System.out.println("Processing" + socket + " Bulb " + name + " " + response.getResponseText()); 379 | 380 | id2device.put(ID, name); 381 | 382 | JSONObject light = json.getJSONArray(LIGHT).getJSONObject(0); 383 | 384 | if (!light.has(ONOFF)) { 385 | System.err.println("Bulb '" + name + "' has no On/Off value (probably no power on lightbulb socket)"); 386 | return; // skip this lamp for now 387 | } 388 | int state = light.getInt(ONOFF); 389 | String topicBulbOnOff = "TRÅDFRI/bulb/" + name + "/state/on"; 390 | String topicBulbDim = "TRÅDFRI/bulb/" + name + "/state/dim"; 391 | String topicBulbTemp = "TRÅDFRI/bulb/" + name + "/state/temperature"; 392 | 393 | MqttMessage messageBulbOnOff = new MqttMessage(); 394 | messageBulbOnOff.setPayload(Integer.toString(state).getBytes()); 395 | if (retainedQueues) { 396 | messageBulbOnOff.setRetained(true); 397 | } 398 | mqttClient.publish(topicBulbOnOff, messageBulbOnOff); 399 | 400 | MqttMessage messageBulbDim = null; 401 | if (light.has(DIMMER)) { 402 | messageBulbDim = new MqttMessage(); 403 | int dim = light.getInt(DIMMER); 404 | messageBulbDim.setPayload(Integer.toString(dim).getBytes()); 405 | if (retainedQueues) { 406 | messageBulbDim.setRetained(true); 407 | } 408 | mqttClient.publish(topicBulbDim, messageBulbDim); 409 | } else { 410 | System.err.println("Bulb '" + name + "' has no dimming value (maybe just no power on lightbulb socket)"); 411 | // no dim topic is created for this bulb 412 | } 413 | 414 | MqttMessage messageBulbTemp = null; 415 | if (light.has(COLOR)) { 416 | messageBulbTemp = new MqttMessage(); 417 | String temperature = light.getString(COLOR); 418 | messageBulbTemp.setPayload(temperature.getBytes()); 419 | if (retainedQueues) { 420 | messageBulbTemp.setRetained(true); 421 | } 422 | mqttClient.publish(topicBulbTemp, messageBulbTemp); 423 | } else { // just fyi for the user. maybe add further handling later 424 | System.out.println("Bulb '" + name + "' doesn't support color temperature"); 425 | } 426 | 427 | } else if (json.has(HS_ACCESSORY_LINK)) { // groups have this entry 428 | JSONArray lamps = null; 429 | try { 430 | lamps = json.getJSONObject("9018").getJSONObject("15002").getJSONArray("9003"); 431 | } catch (JSONException e) {} 432 | List lampNames = new ArrayList<>(); 433 | if (lamps != null) 434 | for (int i = 0; i < lamps.length(); i++) 435 | lampNames.add(id2device.get(lamps.getInt(i))); 436 | String ll = " (" + lampNames.stream().collect(Collectors.joining(" ")) + ")"; 437 | System.out.println("Processing Room " + name + ll + " " + response.getResponseText()); 438 | id2room.put(json.getInt(INSTANCE_ID), name); 439 | 440 | String topicRoomOnOff = "TRÅDFRI/room/" + name + "/state/on"; 441 | String topicRoomDim = "TRÅDFRI/room/" + name + "/state/dim"; 442 | 443 | MqttMessage messageRoomOnOff = new MqttMessage(); 444 | int state = json.getInt(ONOFF); 445 | messageRoomOnOff.setPayload(Integer.toString(state).getBytes()); 446 | if (retainedQueues) { 447 | messageRoomOnOff.setRetained(true); 448 | } 449 | mqttClient.publish(topicRoomOnOff, messageRoomOnOff); 450 | 451 | MqttMessage messageRoomDim = new MqttMessage(); 452 | int dim = json.getInt(DIMMER); 453 | messageRoomDim.setPayload(Integer.toString(dim).getBytes()); 454 | if (retainedQueues) { 455 | messageRoomDim.setRetained(true); 456 | } 457 | mqttClient.publish(topicRoomDim, messageRoomDim); 458 | 459 | } else if (json.has(IKEA_MOODS)) { 460 | System.out.println("Processing Mood " + name + " for Room ID " + path[0] + " " + response.getResponseText()); 461 | // Store Mood in database 462 | roomID2moods.get(Integer.parseInt(path[0])).put(ID, name); 463 | } else if (json.has(TYPE) && json.getInt(TYPE) == TYPE_REMOTE) { 464 | System.out.println("Processing Remote " + name + " " + response.getResponseText()); 465 | // save this to device list, even though it's not used yet 466 | id2device.put(json.getInt(INSTANCE_ID), name); 467 | } else { 468 | System.out.println("Got entity '" + name + "' that is neither bulb, group or remote..." + " " + response.getResponseText()); 469 | } 470 | } catch (JSONException e) { 471 | // TODO Auto-generated catch block 472 | e.printStackTrace(); 473 | } catch (MqttPersistenceException e) { 474 | // TODO Auto-generated catch block 475 | e.printStackTrace(); 476 | } catch (MqttException e) { 477 | System.err.println("Publishing failed: " + e.getMessage()); 478 | // TODO Auto-generated catch block 479 | e.printStackTrace(); 480 | } 481 | } 482 | 483 | @Override 484 | public void onError() { 485 | System.out.println("CoAP request timed out or was rejected by the server."); 486 | } 487 | }; 488 | CoapObserveRelation relation = client.observe(handler); 489 | watching.add(relation); 490 | 491 | } catch (URISyntaxException e) { 492 | // TODO Auto-generated catch block 493 | e.printStackTrace(); 494 | } 495 | 496 | } 497 | 498 | /** 499 | * @param args Command line arguments 500 | * @throws InterruptedException 501 | */ 502 | public static void main(String[] args) throws InterruptedException { 503 | Options options = new Options(); 504 | options.addOption("psk", true, "The Secret on the base of the gateway"); 505 | options.addOption("ip", true, "The IP address of the gateway"); 506 | options.addOption("broker", true, "MQTT URL"); 507 | options.addOption("retained", "Topics are retained"); 508 | options.addOption("help", "Shows this usage information"); 509 | 510 | CommandLineParser parser = new DefaultParser(); 511 | CommandLine cmd = null; 512 | try { 513 | cmd = parser.parse(options, args); 514 | } catch (ParseException e) { 515 | // TODO Auto-generated catch block 516 | e.printStackTrace(); 517 | } 518 | 519 | String psk = cmd.getOptionValue("psk"); 520 | String ip = cmd.getOptionValue("ip"); 521 | String broker = cmd.getOptionValue("broker"); 522 | boolean retained = cmd.hasOption("retained"); 523 | boolean help = cmd.hasOption("help"); 524 | 525 | if (help || psk == null || ip == null || broker == null) { 526 | HelpFormatter formatter = new HelpFormatter(); 527 | formatter.printHelp("TRADFRI2MQTT", options); 528 | System.exit(1); 529 | } 530 | 531 | Main m = new Main(psk, ip, broker, retained); 532 | m.discover(); 533 | } 534 | 535 | } 536 | -------------------------------------------------------------------------------- /src/main/java/uk/me/hardill/TRADFRI2MQTT/TradfriConstants.java: -------------------------------------------------------------------------------- 1 | package uk.me.hardill.TRADFRI2MQTT; 2 | 3 | /** 4 | * Partly inspired by "com/ikea/tradfri/lighting/ipso/IPSOObjects.java" 5 | * Some of these values can be found in the official LwM2M registry: 6 | * http://www.openmobilealliance.org/wp/OMNA/LwM2M/LwM2MRegistry.html 7 | * 8 | * @author r41d 9 | */ 10 | public class TradfriConstants { 11 | 12 | // Device types (contained in INSTANCE_ID = "9003" inside of array contained in LIGHT = "3311") 13 | public static final int TYPE_REMOTE = 0; 14 | public static final int TYPE_BULB = 2; 15 | // The others need to be figured out by people who own these 16 | 17 | // Top level navigation 18 | public static final String DEVICES = "15001"; // individual bulbs, remotes, motion sensors, ... 19 | public static final String GROUPS = "15004"; // also called rooms 20 | public static final String SCENE = "15005"; // also called moods 21 | public static final String NOTIFICATIONS = "15006"; // ??? 22 | public static final String TIMERS = "15010"; 23 | 24 | // Values in JSON data 25 | public static final String NAME = "9001"; // used in both devices and groups 26 | public static final String INSTANCE_ID = "9003"; // In devices: device ID. In groups: list of device IDs 27 | public static final String HS_ACCESSORY_LINK = "9018"; // Groups have this entry 28 | public static final String IKEA_MOODS = "9068"; // Moods have this entry 29 | public static final String IKEA_IDENTITY = "9090"; // Request new client PSK 30 | public static final String LIGHT = "3311"; // urn:oma:lwm2m:ext:3311 in LwM2M registry 31 | public static final String TYPE = "5750"; // "Application Type" in LwM2M registry 32 | public static final String ONOFF = "5850"; // "On/Off" in LwM2M registry 33 | public static final String DIMMER = "5851"; // "Dimmer" in LwM2M registry 34 | public static final String SCENE_ID = "9039"; // Property of rooms 35 | public static final String TRANSITION_TIME = "5712"; // not contained in LwM2M registry 36 | 37 | // Color / Temperature related, these are independent of brightness, i.e. do not change if brightness does 38 | public static final String COLOR = "5706"; 39 | public static final String COLOR_X = "5709"; 40 | public static final String COLOR_Y = "5710"; 41 | public static final String COLOR_COLD = "f5faf6"; 42 | public static final String COLOR_COLD_X = "24930"; 43 | public static final String COLOR_COLD_Y = "24694"; 44 | public static final String COLOR_NORMAL = "f1e0b5"; 45 | public static final String COLOR_NORMAL_X = "30140"; 46 | public static final String COLOR_NORMAL_Y = "26909"; 47 | public static final String COLOR_WARM = "efd275"; 48 | public static final String COLOR_WARM_X = "33135"; 49 | public static final String COLOR_WARM_Y = "27211"; 50 | 51 | // Dimmer related 52 | public static final int DIMMER_MIN = 0; 53 | public static final int DIMMER_MAX = 254; 54 | } 55 | --------------------------------------------------------------------------------