├── .jshintrc ├── DIST.sh ├── Gruntfile.js ├── LICENSE.txt ├── README.md ├── images ├── ST1.png ├── ST2.png └── ST3.png ├── package.json ├── smartthings.groovy ├── smartthings.js ├── smartthings.py └── smartthingslib.js /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "curly": true, 3 | "eqeqeq": true, 4 | "immed": true, 5 | "latedef": "nofunc", 6 | "newcap": false, 7 | "noarg": true, 8 | "sub": true, 9 | "undef": true, 10 | "unused": "var", 11 | "boss": true, 12 | "eqnull": true, 13 | "node": true, 14 | "-W086": true 15 | } 16 | -------------------------------------------------------------------------------- /DIST.sh: -------------------------------------------------------------------------------- 1 | # 2 | # DIST.sh 3 | # 4 | # David Janes 5 | # IOTDB 6 | # 2015-02-10 7 | # 8 | 9 | PACKAGE=iotdb-smartthings 10 | DIST_ROOT=/var/tmp/.dist.$$ 11 | 12 | if [ ! -d "$DIST_ROOT" ] 13 | then 14 | mkdir "$DIST_ROOT" 15 | fi 16 | 17 | echo "==================" 18 | echo "NPM Packge: $PACKAGE" 19 | echo "==================" 20 | ( 21 | NPM_DST="$DIST_ROOT/$PACKAGE" 22 | echo "NPM_DST=$NPM_DST" 23 | 24 | if [ -d ${NPM_DST} ] 25 | then 26 | rm -rf "${NPM_DST}" 27 | fi 28 | mkdir "${NPM_DST}" || exit 1 29 | 30 | update-package --increment-version|| exit 1 31 | 32 | tar cf - \ 33 | README.md \ 34 | LICENSE.txt \ 35 | package.json smartthings.js smartthingslib.js \ 36 | | 37 | ( cd "${NPM_DST}" && tar xvf - && npm publish ) || exit 1 38 | git commit -m "new release" package.json || exit 1 39 | git push || exit 1 40 | 41 | echo "end" 42 | ) 43 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = function (grunt) { 4 | // Show elapsed time at the end 5 | // require('time-grunt')(grunt); 6 | // Load all grunt tasks 7 | require('load-grunt-tasks')(grunt); 8 | 9 | // Project configuration. 10 | grunt.initConfig({ 11 | nodeunit: { 12 | files: [] 13 | }, 14 | jshint: { 15 | options: { 16 | jshintrc: '.jshintrc', 17 | reporter: require('jshint-stylish') 18 | }, 19 | gruntfile: { 20 | src: 'Gruntfile.js' 21 | }, 22 | lib: { 23 | src: [ 24 | '*.js' 25 | ] 26 | }, 27 | test: { 28 | src: [] 29 | } 30 | }, 31 | watch: { 32 | gruntfile: { 33 | files: '<%= jshint.gruntfile.src %>', 34 | tasks: ['jshint:gruntfile'] 35 | }, 36 | lib: { 37 | files: '<%= jshint.lib.src %>', 38 | tasks: ['jshint:lib', 'nodeunit'] 39 | }, 40 | test: { 41 | files: '<%= jshint.test.src %>', 42 | tasks: ['jshint:test', 'nodeunit'] 43 | } 44 | }, 45 | jsbeautifier: { 46 | files: [ 47 | '*.js' 48 | ], 49 | options: { 50 | js: { 51 | jslint_happy: true, 52 | indentChar: ' ', 53 | indentSize: 4 54 | } 55 | }, 56 | } 57 | }); 58 | 59 | // Default task. 60 | // grunt.registerTask('default', ['jsbeautifier', 'jshint', 'nodeunit']); 61 | grunt.registerTask('default', ['jsbeautifier', 'jshint']); 62 | 63 | }; 64 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | iotdb-smartthings 2 | ================= 3 | 4 | Well-documented code to: 5 | 6 | * Demo how to write using the SmartThings API 7 | * Control / Monitor SmartThings from Python 8 | * Control / Monitor SmartThings from Node-JS 9 | * Broadcast SmartThings events to MQTT 10 | 11 | Courtesy of IOTDB. Follow us on Twitter: 12 | * @iotdb 13 | * @dpjanes 14 | 15 | ## Important Notes 16 | 17 | The SmartThings code broadcasts everything you do 18 | to MQTT. It's anonymous enough but you may find it 19 | creepy and it's easily turned off by editing 20 | smartthings.groovy. 21 | 22 | ## Shards 23 | 24 | If you are having trouble connecting to SmartThings, you may have to change your shard. 25 | Add to `smartthings.json` 26 | 27 | "api_location": "" 28 | 29 | You can find out your shard following the instructions here: 30 | [https://community.smartthings.com/t/faq-how-to-find-out-what-shard-cloud-slice-ide-url-your-account-location-is-on/53923](https://community.smartthings.com/t/faq-how-to-find-out-what-shard-cloud-slice-ide-url-your-account-location-is-on/53923) 31 | 32 | 33 | ## Installation 34 | 35 | This is somewhat developer-y. At some point 36 | we'll make a more general user friendly version of this. 37 | 38 | ### Clone this project into a local directory 39 | 40 | git clone https://github.com/dpjanes/iotdb-smartthings.git 41 | 42 | ### Log into SmartThings 43 | 44 | https://graph.api.smartthings.com/ 45 | 46 | If necessary, do what it takes to become a Developer 47 | 48 | ### Create New App 49 | 50 | Go to: 51 | 52 | https://graph.api.smartthings.com/ide/apps 53 | 54 | Click on "+ New SmartApp" 55 | 56 | 57 | 58 | ### Fill in the App Details 59 | 60 | Make sure to "Enable OAuth" and to copy the two values produced. You'll need them them later. Press the *Create* (or *Update* maybe) button. Authorize access to as much as your comfortable with, you can always change this later from your iPhone or Android app. 61 | 62 | 63 | 64 | ### Add the code 65 | 66 | * Press the *Code* button 67 | * Copy the code from smartthings.groovy and paste 68 | * Press *Save* 69 | * Press *Publish* 70 | 71 | 72 | 73 | ## Authorize 74 | 75 | To access the API key, you need an access\_token. 76 | Normally this is a real pain in the arse to generate, but we've 77 | done the hard work. 78 | 79 | You'll need the OAuth Client ID and OAuth Client Secret, 80 | which you copied from the last major step. If you didn't, you can go back 81 | and get them now. 82 | 83 | * Go to this page: https://iotdb.org/playground/oauthorize/smartthings 84 | * Fill in the form 85 | * Press *Submit* 86 | * You'll be brought to the SmartThings website, where you'll allow access to your stuff 87 | * When that's done, you'll be brought back to IOTDB OAuthorize 88 | * copy the JSON data displayed and save it in a file called smartthings.json 89 | in the same directory 90 | 91 | Keep that file to yourself. If you need to turn off access to your things, you can 92 | just go generate new OAuth keys in SmartThings. 93 | 94 | If you add new devices to your SmartThings setup, you can give the API access using 95 | your SmartThings phone app. 96 | 97 | ## API Access 98 | ### Python 99 | #### List all the motion detectors 100 | 101 | $ python smartthings.py --type motion 102 | [ 103 | { 104 | "id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 105 | "label": "Motion LivingRoom", 106 | "type": "motion", 107 | "url": "http://graph.api.smartthings.com/api/smartapps/installations/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/motion/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 108 | "value": { 109 | "motion": false, 110 | "timestamp": "2014-02-03T13:30:31.361Z" 111 | } 112 | } 113 | ] 114 | 115 | #### Turn off a switch 116 | 117 | $ python smartthings.py --type switch --id "My Z-Wave Switch" --request switch=0 118 | 119 | #### Toggle a switch 120 | 121 | $ python smartthings.py --type switch --id "My Z-Wave Switch" --request switch=-1 122 | 123 | ### Node 124 | 125 | A work in progress. The code is solid, but there's no command line argument parsing 126 | -------------------------------------------------------------------------------- /images/ST1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dpjanes/iotdb-smartthings/407fb412186c7d73fe4fc349c3e31d2b12efb9be/images/ST1.png -------------------------------------------------------------------------------- /images/ST2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dpjanes/iotdb-smartthings/407fb412186c7d73fe4fc349c3e31d2b12efb9be/images/ST2.png -------------------------------------------------------------------------------- /images/ST3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dpjanes/iotdb-smartthings/407fb412186c7d73fe4fc349c3e31d2b12efb9be/images/ST3.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "David P. Janes (https://iotdb.org)", 3 | "bin": { 4 | "smartthings": "./smartthingslib.js" 5 | }, 6 | "bugs": { 7 | "url": "https://github.com/dpjanes/iotdb-smartthings/issues" 8 | }, 9 | "dependencies": { 10 | "minimist": "~1.2.0", 11 | "unirest": "~0.5.1" 12 | }, 13 | "description": "Node.JS SmartThings Library", 14 | "devDependencies": { 15 | "grunt": "~1.0.2", 16 | "grunt-contrib-jshint": "~1.1.0", 17 | "grunt-contrib-nodeunit": "~1.0.0", 18 | "grunt-contrib-uglify": "~1.0.1", 19 | "grunt-contrib-watch": "~1.0.1", 20 | "grunt-jsbeautifier": "~0.2.13", 21 | "jshint-stylish": "~2.2.1", 22 | "load-grunt-tasks": "~3.4.1", 23 | "request": "~2.85.0" 24 | }, 25 | "homepage": "https://github.com/dpjanes/node-iotdb", 26 | "homestar": {}, 27 | "license": "Apache-2.0", 28 | "main": "smartthingslib.js", 29 | "name": "iotdb-smartthings", 30 | "private": false, 31 | "repository": { 32 | "type": "git", 33 | "url": "https://github.com/dpjanes/iotdb-models" 34 | }, 35 | "scripts": { 36 | "test": "grunt" 37 | }, 38 | "version": "0.0.10" 39 | } -------------------------------------------------------------------------------- /smartthings.groovy: -------------------------------------------------------------------------------- 1 | /** 2 | * smartthings.groovy 3 | * 4 | * David Janes 5 | * IOTDB.org 6 | * 2014-02-01 7 | * 8 | * Allow control of your SmartThings via an API; 9 | * Allow monitoring of your SmartThings using 10 | * MQTT through the IOTDB MQTT Bridge. 11 | * 12 | * Follow us on Twitter: 13 | * - @iotdb 14 | * - @dpjanes 15 | * 16 | * A work in progress! 17 | * 18 | * This is for SmartThing's benefit. There's no need to 19 | * change this unless you really want to 20 | */ 21 | 22 | definition( 23 | name: "IOTDB.bridge", 24 | namespace: "", 25 | author: "David Janes", 26 | description: "Bridge to/from JSON/MQTT.", 27 | category: "My Apps", 28 | iconUrl: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience.png", 29 | iconX2Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience%402x.png", 30 | oauth: true) 31 | 32 | /* --- IOTDB section --- */ 33 | /* 34 | * IOTDB MQTT Bridge 35 | * - this works for now 36 | * - your life is private 37 | * - just set to empty values to turn off MQTT 38 | * 39 | * The values below can be copied from this page 40 | * - https://iotdb.org/playground/mqtt/bridge 41 | * 42 | * Make sure you are logged into IOTDB first 43 | */ 44 | def _settings() 45 | { 46 | [ 47 | iotdb_api_username: "", 48 | iotdb_api_key: "" 49 | ] 50 | } 51 | 52 | 53 | 54 | /* --- setup section --- */ 55 | /* 56 | * The user 57 | * Make sure that if you change anything related to this in the code 58 | * that you update the preferences in your installed apps. 59 | * 60 | * Note that there's a SmartThings magic that's _required_ here, 61 | * in that you cannot access a device unless you have it listed 62 | * in the preferences. Access to those devices is given through 63 | * the name used here (i.e. d_*) 64 | */ 65 | preferences { 66 | section("Allow IOTDB to Control & Access These Things...") { 67 | input "d_switch", "capability.switch", title: "Switch", required: false, multiple: true 68 | input "d_motion", "capability.motionSensor", title: "Motion", required: false, multiple: true 69 | input "d_temperature", "capability.temperatureMeasurement", title: "Temperature", required: false, multiple: true 70 | input "d_contact", "capability.contactSensor", title: "Contact", required: false, multiple: true 71 | input "d_acceleration", "capability.accelerationSensor", title: "Acceleration", required: false, multiple: true 72 | input "d_presence", "capability.presenceSensor", title: "Presence", required: false, multiple: true 73 | input "d_battery", "capability.battery", title: "Battery", required: false, multiple: true 74 | input "d_threeAxis", "capability.threeAxis", title: "3 Axis", required: false, multiple: true 75 | input "d_relativeHumidityMeasurement", "capability.relativeHumidityMeasurement", title: "relativeHumidityMeasurement", required: false, multiple: true 76 | 77 | } 78 | } 79 | 80 | /* 81 | input "d_alarm", "capability.alarm", title: "alarm", multiple: true 82 | input "d_configuration", "capability.configuration", title: "configuration", multiple: true 83 | input "d_illuminanceMeasurement", "capability.illuminanceMeasurement", title: "illuminanceMeasurement", multiple: true 84 | input "d_polling", "capability.polling", title: "polling", multiple: true 85 | input "d_thermostatCoolingSetpoint", "capability.thermostatCoolingSetpoint", title: "thermostatCoolingSetpoint", multiple: true 86 | input "d_thermostatFanMode", "capability.thermostatFanMode", title: "thermostatFanMode", multiple: true 87 | input "d_thermostatHeatingSetpoint", "capability.thermostatHeatingSetpoint", title: "thermostatHeatingSetpoint", multiple: true 88 | input "d_thermostatMode", "capability.thermostatMode", title: "thermostatMode", multiple: true 89 | input "d_thermostatSetpoint", "capability.thermostatSetpoint", title: "thermostatSetpoint", multiple: true 90 | input "d_threeAxisMeasurement", "capability.threeAxisMeasurement", title: "threeAxisMeasurement", multiple: true 91 | input "d_waterSensor", "capability.waterSensor", title: "waterSensor", multiple: true 92 | 93 | lqi: 100 % 94 | acceleration: inactive 95 | threeAxis: -38,55,1021 96 | battery: 88 % 97 | temperature: 65 F 98 | */ 99 | 100 | /* 101 | * The API 102 | * - ideally the command/update bit would actually 103 | * be a PUT call on the ID to make this restful 104 | */ 105 | mappings { 106 | path("/:type") { 107 | action: [ 108 | GET: "_api_list" 109 | ] 110 | } 111 | path("/:type/:id") { 112 | action: [ 113 | GET: "_api_get", 114 | PUT: "_api_put" 115 | ] 116 | } 117 | } 118 | 119 | /* 120 | * This function is called once when the app is installed 121 | */ 122 | def installed() { 123 | _event_subscribe() 124 | } 125 | 126 | /* 127 | * This function is called every time the user changes 128 | * their preferences 129 | */ 130 | def updated() 131 | { 132 | log.debug "updated" 133 | unsubscribe() 134 | _event_subscribe() 135 | } 136 | 137 | /* --- event section --- */ 138 | 139 | /* 140 | * What events are we interested in. This needs 141 | * to be in it's own function because both 142 | * updated() and installed() are interested in it. 143 | */ 144 | def _event_subscribe() 145 | { 146 | subscribe(d_switch, "switch", "_on_event") 147 | subscribe(d_motion, "motion", "_on_event") 148 | subscribe(d_temperature, "temperature", "_on_event") 149 | subscribe(d_contact, "contact", "_on_event") 150 | subscribe(d_acceleration, "acceleration", "_on_event") 151 | subscribe(d_presence, "presence", "_on_event") 152 | subscribe(d_battery, "battery", "_on_event") 153 | subscribe(d_threeAxis, "threeAxis", "_on_event") 154 | } 155 | 156 | /* 157 | * This function is called whenever something changes. 158 | * Right now it just 159 | */ 160 | def _on_event(evt) 161 | { 162 | // log.debug "_on_event XXX event.id=${evt?.id} event.deviceId=${evt?.deviceId} event.isStateChange=${evt?.isStateChange} event.name=${evt?.name}" 163 | 164 | def dt = _device_and_type_for_event(evt) 165 | if (!dt) { 166 | log.debug "_on_event deviceId=${evt.deviceId} not found?" 167 | return; 168 | } 169 | 170 | def jd = _device_to_json(dt.device, dt.type) 171 | log.debug "_on_event deviceId=${jd}" 172 | 173 | _send_mqtt(dt.device, dt.type, jd) 174 | 175 | } 176 | 177 | /* --- API section --- */ 178 | def _api_list() 179 | { 180 | _devices_for_type(params.type).collect{ 181 | _device_to_json(it, params.type) 182 | } 183 | } 184 | 185 | def _api_put() 186 | { 187 | def devices = _devices_for_type(params.type) 188 | def device = devices.find { it.id == params.id } 189 | if (!device) { 190 | httpError(404, "Device not found") 191 | } else { 192 | _device_command(device, params.type, request.JSON) 193 | } 194 | } 195 | 196 | def _api_get() 197 | { 198 | def devices = _devices_for_type(params.type) 199 | def device = devices.find { it.id == params.id } 200 | if (!device) { 201 | httpError(404, "Device not found") 202 | } else { 203 | _device_to_json(device, params.type) 204 | } 205 | } 206 | 207 | void _api_update() 208 | { 209 | _do_update(_devices_for_type(params.type), params.type) 210 | } 211 | 212 | /* 213 | * I don't know what this does but it seems to be needed 214 | */ 215 | def deviceHandler(evt) { 216 | } 217 | 218 | /* --- communication section: not done --- */ 219 | 220 | /* 221 | * An example of how to get PushingBox.com to send a message 222 | */ 223 | def _send_pushingbox() { 224 | log.debug "_send_pushingbox called"; 225 | 226 | def devid = "XXXX" 227 | def messageText = "Hello_World" 228 | 229 | httpGet("http://api.pushingbox.com/pushingbox?devid=${devid}&message=xxx_xxx") 230 | } 231 | 232 | /* 233 | * Send information the the IOTDB MQTT Bridge 234 | * See https://iotdb.org/playground/mqtt/bridge for documentation 235 | */ 236 | def _send_mqtt(device, device_type, deviced) { 237 | def settings = _settings() 238 | // log.debug "_send_mqtt: iotdb_api_username=${settings.iotdb_api_username},iotdb_api_key=${settings.iotdb_api_key}" 239 | 240 | if (!settings.iotdb_api_username || !settings.iotdb_api_key) { 241 | return 242 | } 243 | 244 | log.debug "_send_mqtt called"; 245 | 246 | def now = Calendar.instance 247 | def date = now.time 248 | def millis = date.time 249 | def sequence = millis 250 | def isodatetime = deviced?.value?.timestamp 251 | 252 | def digest = "${settings.iotdb_api_key}/${settings.iotdb_api_username}/${isodatetime}/${sequence}".toString(); 253 | def hash = digest.encodeAsMD5(); 254 | 255 | def topic = "st/${device_type}/${deviced.id}".toString() 256 | 257 | def uri = "https://iotdb.org/playground/mqtt/bridge" 258 | def headers = [:] 259 | def body = [ 260 | "topic": topic, 261 | "payloadd": deviced?.value, 262 | "timestamp": isodatetime, 263 | "sequence": sequence, 264 | "signed": hash, 265 | "username": settings.iotdb_api_username 266 | ] 267 | 268 | def params = [ 269 | uri: uri, 270 | headers: headers, 271 | body: body 272 | ] 273 | 274 | log.debug "_send_mqtt: params=${params}" 275 | httpPutJson(params) { log.debug "_send_mqtt: response=${response}" } 276 | } 277 | 278 | 279 | 280 | /* --- internals --- */ 281 | /* 282 | * Devices and Types Dictionary 283 | */ 284 | def _dtd() 285 | { 286 | [ 287 | switch: d_switch, 288 | motion: d_motion, 289 | temperature: d_temperature, 290 | contact: d_contact, 291 | acceleration: d_acceleration, 292 | presence: d_presence, 293 | battery: d_battery, 294 | threeAxis: d_threeAxis, 295 | humidity: d_relativeHumidityMeasurement 296 | 297 | ] 298 | } 299 | 300 | def _devices_for_type(type) 301 | { 302 | _dtd()[type] 303 | } 304 | 305 | def _device_and_type_for_event(evt) 306 | { 307 | def dtd = _dtd() 308 | 309 | for (dt in _dtd()) { 310 | if (dt.key != evt.name) { 311 | continue 312 | } 313 | 314 | def devices = dt.value 315 | for (device in devices) { 316 | if (device.id == evt.deviceId) { 317 | return [ device: device, type: dt.key ] 318 | } 319 | } 320 | } 321 | } 322 | 323 | /** 324 | * Do a device command 325 | */ 326 | private _device_command(device, type, jsond) { 327 | if (!device) { 328 | return; 329 | } 330 | if (!jsond) { 331 | return; 332 | } 333 | 334 | if (type == "switch") { 335 | def n = jsond['switch'] 336 | if (n == -1) { 337 | def o = device.currentState('switch')?.value 338 | n = ( o != 'on' ) 339 | } 340 | if (n) { 341 | device.on() 342 | } else { 343 | device.off() 344 | } 345 | } else { 346 | log.debug "_device_command: device type=${type} doesn't take commands" 347 | } 348 | } 349 | 350 | /* 351 | * Convert a single device into a JSONable object 352 | */ 353 | private _device_to_json(device, type) { 354 | if (!device) { 355 | return; 356 | } 357 | 358 | def vd = [:] 359 | def jd = [id: device.id, label: device.label, type: type, value: vd, hub: device.hub?.name]; 360 | 361 | if (type == "switch") { 362 | def s = device.currentState('switch') 363 | vd['timestamp'] = s?.isoDate 364 | vd['switch'] = s?.value == "on" 365 | } else if (type == "motion") { 366 | def s = device.currentState('motion') 367 | vd['timestamp'] = s?.isoDate 368 | vd['motion'] = s?.value == "active" 369 | } else if (type == "temperature") { 370 | def s = device.currentState('temperature') 371 | vd['timestamp'] = s?.isoDate 372 | vd['temperature'] = s?.value.toFloat() 373 | } else if (type == "contact") { 374 | def s = device.currentState('contact') 375 | vd['timestamp'] = s?.isoDate 376 | vd['contact'] = s?.value == "closed" 377 | } else if (type == "acceleration") { 378 | def s = device.currentState('acceleration') 379 | vd['timestamp'] = s?.isoDate 380 | vd['acceleration'] = s?.value == "active" 381 | } else if (type == "presence") { 382 | def s = device.currentState('presence') 383 | vd['timestamp'] = s?.isoDate 384 | vd['presence'] = s?.value == "present" 385 | } else if (type == "battery") { 386 | def s = device.currentState('battery') 387 | vd['timestamp'] = s?.isoDate 388 | vd['battery'] = s?.value.toFloat() / 100.0 389 | } else if (type == "humidity") { 390 | def s = device.currentState('humidity') 391 | vd['timestamp'] = s?.isoDate 392 | vd['humidity'] = s?.value.toFloat() / 100.0 393 | } else if (type == "threeAxis") { 394 | def s = device.currentState('threeAxis') 395 | vd['timestamp'] = s?.isoDate 396 | vd['x'] = s?.xyzValue?.x 397 | vd['y'] = s?.xyzValue?.y 398 | vd['z'] = s?.xyzValue?.z 399 | } 400 | 401 | def settings = _settings() 402 | jd['mqtt'] = "tcp://mqtt.iotdb.org/u/${settings.iotdb_api_username}/st/${type}/${device.id}" 403 | 404 | return jd 405 | } 406 | -------------------------------------------------------------------------------- /smartthings.js: -------------------------------------------------------------------------------- 1 | /* 2 | * smartthings.js 3 | * 4 | * David Janes 5 | * IOTDB.org 6 | * 2014-02-01 7 | * 8 | * Demonstrate how to use the SmartThings API from Node 9 | * 10 | * See also: 11 | * Example App explanation: 12 | * http://build.smartthings.com/blog/tutorial-creating-a-custom-rest-smartapp-endpoint/ 13 | * 14 | * Example PHP code: 15 | * https://www.dropbox.com/s/7m7gmlr9q3u7rmk/exampleOauth.php 16 | * 17 | * Example "Groovy"/SMART code (this is the app we tap into) 18 | * https://www.dropbox.com/s/lohzziy2wjlrppb/endpointExample.groovy 19 | */ 20 | 21 | "use strict"; 22 | 23 | var unirest = require('unirest'); 24 | 25 | var fs = require('fs'); 26 | var util = require('util'); 27 | var events = require('events'); 28 | var minimist = require('minimist'); 29 | 30 | var SmartThings = require("./smartthingslib").SmartThings; 31 | 32 | var ad = require('minimist')(process.argv.slice(2), { 33 | boolean: ["poll"] 34 | }); 35 | 36 | var sm = new SmartThings(); 37 | sm.on("endpoint", function () { 38 | sm.request_devices(ad.type); 39 | }); 40 | sm.on("devices", function (device_type, devices) { 41 | var di; 42 | var device; 43 | 44 | if (ad.device_id) { 45 | var ds = []; 46 | for (di in devices) { 47 | device = devices[di]; 48 | if ((device.id === ad.device_id) || (device.label === ad.device_id)) { 49 | ds.push(device); 50 | } 51 | } 52 | devices = ds; 53 | } 54 | 55 | if (ad.request) { 56 | for (di in devices) { 57 | device = devices[di]; 58 | sm.device_request(device, ad.request); 59 | } 60 | } else if (ad.poll && ad.device_id) { 61 | var _on_state = function (error, _deviced, _stated) { 62 | console.log(JSON.stringify(_stated, null, 2)); 63 | }; 64 | for (di in devices) { 65 | device = devices[di]; 66 | sm.device_poll(device, _on_state); 67 | } 68 | } else { 69 | console.log(JSON.stringify(devices, null, 2)); 70 | } 71 | 72 | }); 73 | 74 | var help = function () { 75 | console.log("usage:", process.argv[1], "[arguments...]"); 76 | console.log(""); 77 | console.log("--type "); 78 | console.log(" the device type (required), one of switch, motion, presence, acceleration, …"); 79 | console.log(" …contact, temperature, battery, threeAxis"); 80 | console.log(""); 81 | console.log("--device_id "); 82 | console.log(" the ID or Name of the device to manipulate"); 83 | console.log(""); 84 | console.log("--request "); 85 | console.log(" something to do, e.g. 'switch=1', 'switch=0'"); 86 | console.log(""); 87 | console.log("--poll"); 88 | console.log(" request the device's state (must be paired with device_id"); 89 | 90 | }; 91 | 92 | if (Object.keys(ad).length === 1) { 93 | help(); 94 | process.exit(1); 95 | } 96 | if (!ad.type) { 97 | console.log("error:"); 98 | console.log(" --type is required"); 99 | console.log(""); 100 | help(); 101 | process.exit(1); 102 | } 103 | if (ad.request) { 104 | var parts = ad.request.split("=", 2); 105 | if (parts.length !== 2) { 106 | console.log("error:"); 107 | console.log(" --request requires an argument like 'switch=1'"); 108 | console.log(""); 109 | help(); 110 | process.exit(1); 111 | } 112 | ad.request = {}; 113 | ad.request[parts[0]] = parseInt(parts[1]); 114 | } 115 | 116 | sm.load_settings(); 117 | sm.request_endpoint(); 118 | -------------------------------------------------------------------------------- /smartthings.py: -------------------------------------------------------------------------------- 1 | # 2 | # smartthings.py 3 | # 4 | # David Janes 5 | # IOTDB.org 6 | # 2014-01-31 7 | # 8 | # Demonstrate how to use the SmartThings API from Python. 9 | # 10 | # See also: 11 | # Example App explanation: 12 | # http://build.smartthings.com/blog/tutorial-creating-a-custom-rest-smartapp-endpoint/ 13 | # 14 | # Example PHP code: 15 | # https://www.dropbox.com/s/7m7gmlr9q3u7rmk/exampleOauth.php 16 | # 17 | # Example "Groovy"/SMART code (this is the app we tap into) 18 | # https://www.dropbox.com/s/lohzziy2wjlrppb/endpointExample.groovy 19 | # 20 | 21 | import sys 22 | import requests 23 | import pprint 24 | import json 25 | 26 | ## import httplib 27 | ## httplib.HTTPConnection.debuglevel = 1 28 | 29 | from optparse import OptionParser 30 | 31 | try: 32 | import iotdb_log 33 | except: 34 | class iotdb_log(object): 35 | @staticmethod 36 | def log(**ad): 37 | pprint.pprint(ad) 38 | 39 | class SmartThings(object): 40 | 41 | @staticmethod 42 | def raise_request_errors(response): 43 | if not response.ok: 44 | raise Exception("HTTP error " + str(response.status_code) + ": " + response.url) 45 | 46 | @staticmethod 47 | def raise_api_errors(json_response): 48 | if "error" in json_response: 49 | if type(json_response["error"]) == bool: 50 | error_type = json_response.get("type", "Unknown Error") 51 | else: 52 | error_type = json_response["error"] 53 | error_message = json_response.get("message", "") + \ 54 | json_response.get("error_description", "") 55 | raise Exception(error_type + ": " + error_message) 56 | 57 | def __init__(self, verbose=True): 58 | self.verbose = verbose 59 | self.std = {} 60 | self.endpointd = {} 61 | self.deviceds = {} 62 | 63 | def load_settings(self, filename="smartthings.json"): 64 | """Load the JSON Settings file. 65 | 66 | See the documentation, but briefly you can 67 | get it from here: 68 | https://iotdb.org/playground/oauthorize 69 | """ 70 | 71 | with open(filename) as fin: 72 | self.std = json.load(fin) 73 | 74 | def request_endpoints(self): 75 | """Get the endpoints exposed by the SmartThings App 76 | 77 | The first command you need to call 78 | """ 79 | 80 | endpoints_url = self.std["api"] 81 | endpoints_paramd = { 82 | "access_token": self.std["access_token"] 83 | } 84 | 85 | endpoints_response = requests.get(url=endpoints_url, params=endpoints_paramd) 86 | 87 | try: 88 | endpoints = endpoints_response.json() 89 | except ValueError: 90 | SmartThings.raise_request_errors(endpoints_response) 91 | raise Exception("Received invalid JSON response") 92 | 93 | SmartThings.raise_api_errors(endpoints) 94 | self.endpointd = endpoints[0] 95 | if self.verbose: iotdb_log.log( 96 | "endpoints", 97 | endpoints_url=endpoints_url, 98 | endpoints_paramd=endpoints_paramd, 99 | resultds=self.endpointd, 100 | ) 101 | 102 | def request_devices(self, device_type): 103 | """List the devices""" 104 | 105 | devices_url = "https://%s%s/%s" % ( self.std.get("api_location", "graph.api.smartthings.com"), self.endpointd["url"], device_type, ) 106 | devices_paramd = { 107 | } 108 | devices_headerd = { 109 | "Authorization": "Bearer %s" % self.std["access_token"], 110 | } 111 | 112 | devices_response = requests.get(url=devices_url, params=devices_paramd, headers=devices_headerd) 113 | 114 | try: 115 | self.deviceds = devices_response.json() 116 | except ValueError: 117 | SmartThings.raise_request_errors(devices_response) 118 | raise Exception("Received invalid JSON response") 119 | SmartThings.raise_api_errors(self.deviceds) 120 | 121 | for switchd in self.deviceds: 122 | switchd['url'] = "%s/%s" % ( devices_url, switchd['id'], ) 123 | 124 | if self.verbose: iotdb_log.log( 125 | "devices", 126 | url=devices_url, 127 | paramd=devices_paramd, 128 | deviceds=self.deviceds, 129 | ) 130 | 131 | return self.deviceds 132 | 133 | def device_request(self, deviced, requestd): 134 | """Send a request the named device""" 135 | 136 | command_url = deviced['url'] 137 | command_paramd = { 138 | "access_token": self.std["access_token"] 139 | } 140 | command_headerd = {} 141 | 142 | command_response = requests.put( 143 | url=command_url, 144 | params=command_paramd, 145 | headers=command_headerd, 146 | data=json.dumps(requestd) 147 | ) 148 | 149 | command_api_response = {} 150 | try: 151 | command_api_response = command_response.json() 152 | except ValueError: 153 | SmartThings.raise_request_errors(command_response) 154 | SmartThings.raise_api_errors(command_api_response) 155 | 156 | def device_types(self): 157 | return dtypes 158 | 159 | dtypes = [ 160 | "switch", "motion", "presence", "acceleration", "contact", 161 | "temperature", "battery", "acceleration", "threeAxis", "humidity" 162 | ] 163 | 164 | if __name__ == '__main__': 165 | 166 | parser = OptionParser() 167 | parser.add_option( 168 | "", "--debug", 169 | default = False, 170 | action = "store_true", 171 | dest = "debug", 172 | help = "", 173 | ) 174 | parser.add_option( 175 | "", "--verbose", 176 | default = False, 177 | action = "store_true", 178 | dest = "verbose", 179 | help = "", 180 | ) 181 | parser.add_option( 182 | "", "--type", 183 | dest = "device_type", 184 | help = "The device type (required), one of %s" % ", ".join(dtypes) 185 | ) 186 | parser.add_option( 187 | "", "--id", 188 | dest = "device_id", 189 | help = "The ID or Name of the device to manipulate" 190 | ) 191 | parser.add_option( 192 | "", "--request", 193 | dest = "request", 194 | help = "Something to do, e.g. 'switch=1', 'switch=0'" 195 | ) 196 | 197 | (options, args) = parser.parse_args() 198 | 199 | if not options.device_type: 200 | print >> sys.stderr, "%s: --type <%s>" % ( sys.argv[0], "|".join(dtypes)) 201 | parser.print_help(sys.stderr) 202 | sys.exit(1) 203 | 204 | 205 | st = SmartThings(verbose=options.verbose) 206 | st.load_settings() 207 | st.request_endpoints() 208 | 209 | ds = st.request_devices(options.device_type) 210 | 211 | if options.device_id: 212 | ds = filter(lambda d: options.device_id in [ d.get("id"), d.get("label"), ], ds) 213 | 214 | if options.request: 215 | key, value = options.request.split('=', 2) 216 | try: 217 | value = int(value) 218 | except ValueError: 219 | pass 220 | 221 | requestd = { 222 | key: value 223 | } 224 | 225 | for d in ds: 226 | iotdb_log.log(device=d, request=requestd) 227 | st.device_request(d, requestd) 228 | 229 | else: 230 | print json.dumps(ds, indent=2, sort_keys=True) 231 | -------------------------------------------------------------------------------- /smartthingslib.js: -------------------------------------------------------------------------------- 1 | /* 2 | * smartthingslib.js 3 | * 4 | * David Janes 5 | * IOTDB.org 6 | * 2014-02-01 7 | * 8 | * Library for interfacing with smartthings 9 | */ 10 | 11 | "use strict"; 12 | 13 | var unirest = require('unirest'); 14 | 15 | var fs = require('fs'); 16 | var util = require('util'); 17 | var events = require('events'); 18 | 19 | var SmartThings = function () { 20 | var self = this; 21 | 22 | events.EventEmitter.call(self); 23 | 24 | self.std = {}; 25 | self.endpointd = {}; 26 | }; 27 | util.inherits(SmartThings, events.EventEmitter); 28 | 29 | /** 30 | * Explicitly make the settings 31 | */ 32 | SmartThings.prototype.configure = function (paramd) { 33 | var self = this; 34 | 35 | paramd = paramd || {}; 36 | 37 | self.std = {}; 38 | self.std.client_id = paramd.client_id || ""; 39 | self.std.access_token = paramd.access_token || ""; 40 | self.std.api = paramd.api || "https://graph.api.smartthings.com/api/smartapps/endpoints/" + self.std.client_id; 41 | self.std.api_location = paramd.api_location || "graph.api.smartthings.com"; 42 | }; 43 | 44 | /** 45 | * Load the JSON Settings file. 46 | * 47 | *

48 | * See the documentation, but briefly you can get it from here: 49 | * {@link https://iotdb.org/playground/oauthorize} 50 | */ 51 | SmartThings.prototype.load_settings = function (filename) { 52 | var self = this; 53 | 54 | if (!filename) { 55 | filename = "smartthings.json"; 56 | } 57 | 58 | var data = fs.readFileSync(filename, 'utf8'); 59 | self.std = JSON.parse(data); 60 | }; 61 | 62 | /** 63 | * Get the endpoints exposed by the SmartThings App. 64 | * 65 | *

66 | * When the endpoints are found, we emit an 'endpoint' event. 67 | * The endpoint itself will be stored in the SmartThings object 68 | * 69 | *

70 | * The first command you need to call 71 | */ 72 | SmartThings.prototype.request_endpoint = function () { 73 | var self = this; 74 | 75 | var endpoints_url = self.std["api"]; 76 | var endpoints_paramd = { 77 | "access_token": self.std["access_token"] 78 | }; 79 | 80 | unirest 81 | .get(endpoints_url) 82 | .query(endpoints_paramd) 83 | .end(function (result) { 84 | if (!result.ok) { 85 | console.log("SmartThings.request_endpoints", "something went wrong", result); 86 | return; 87 | } 88 | 89 | self.endpointd = result.body[0]; 90 | self.emit("endpoint", self); 91 | }); 92 | }; 93 | 94 | /** 95 | * Get devices. 96 | *

97 | * When devices are found, we emit a "devices" event 98 | * 99 | * @param {string} device_type 100 | * The type of device to request, i.e. 101 | * switch, motion, acceleration, contact, presence 102 | */ 103 | SmartThings.prototype.request_devices = function (device_type) { 104 | var self = this; 105 | 106 | if (!self.endpointd.url) { 107 | console.log("SmartThings.request_devices: no endpoint? Perhaps .request_endpoint has not been called"); 108 | return; 109 | } 110 | 111 | var devices_url = "https://graph.api.smartthings.com" + self.endpointd.url + "/" + device_type; 112 | var devices_paramd = {}; 113 | var devices_headerd = { 114 | "Authorization": "Bearer " + self.std["access_token"] 115 | }; 116 | 117 | unirest 118 | .get(devices_url) 119 | .query(devices_paramd) 120 | .headers(devices_headerd) 121 | .end(function (result) { 122 | if (!result.ok) { 123 | console.log("SmartThings.request_devices", "something went wrong", 124 | "\n url=", devices_url, 125 | "\n error=", result.error, 126 | "\n body=", result.body 127 | ); 128 | return; 129 | } 130 | 131 | self.emit("devices", device_type, result.body); 132 | }); 133 | }; 134 | 135 | /** 136 | * Send a request to a device 137 | * 138 | * @param {dictionary} device 139 | * A device dictionary, as found by {@link request_devices} 140 | * 141 | * @param {dictionary} requestd 142 | * A request dictinary, for example something like 143 | * { switch: 1 } 144 | */ 145 | SmartThings.prototype.device_request = function (deviced, requestd, callback) { 146 | var self = this; 147 | 148 | if (!callback) { 149 | callback = function () {}; 150 | } 151 | 152 | if (!self.endpointd.url) { 153 | console.log("SmartThings.device_request: no endpoint? Perhaps .request_endpoint has not been called"); 154 | return; 155 | } 156 | 157 | var devices_url = "https://graph.api.smartthings.com" + self.endpointd.url + "/" + deviced.type + "/" + deviced.id; 158 | var devices_headerd = { 159 | "Authorization": "Bearer " + self.std["access_token"] 160 | }; 161 | 162 | unirest 163 | .put(devices_url) 164 | .type('json') 165 | .send(requestd) 166 | .headers(devices_headerd) 167 | .end(function (result) { 168 | if (!result.ok) { 169 | callback(result.error, deviced, null); 170 | 171 | console.log("SmartThings.device_request", "something went wrong", 172 | "\n url=", devices_url, 173 | "\n error=", result.error, 174 | "\n body=", result.body 175 | ); 176 | return; 177 | } 178 | 179 | self.emit("request", deviced); 180 | callback(null, deviced, result.body); 181 | 182 | }); 183 | }; 184 | 185 | /** 186 | * Request device's state 187 | * 188 | * @param {dictionary} device 189 | * A device dictionary, as found by {@link request_devices} 190 | */ 191 | SmartThings.prototype.device_poll = function (deviced, callback) { 192 | var self = this; 193 | 194 | if (!self.endpointd.url) { 195 | console.log("SmartThings.device_request: no endpoint? Perhaps .request_endpoint has not been called"); 196 | return; 197 | } 198 | 199 | var devices_url = "https://graph.api.smartthings.com" + self.endpointd.url + "/" + deviced.type + "/" + deviced.id; 200 | var devices_headerd = { 201 | "Authorization": "Bearer " + self.std["access_token"] 202 | }; 203 | 204 | unirest 205 | .get(devices_url) 206 | .type('json') 207 | .headers(devices_headerd) 208 | .end(function (result) { 209 | if (!result.ok) { 210 | callback(result.error, deviced, null); 211 | 212 | console.log("SmartThings.device_request", "something went wrong", 213 | "\n url=", devices_url, 214 | "\n error=", result.error, 215 | "\n body=", result.body 216 | ); 217 | return; 218 | } 219 | 220 | self.emit("device", result.body); 221 | callback(null, deviced, result.body); 222 | }); 223 | }; 224 | 225 | exports.SmartThings = SmartThings; 226 | exports.device_types = [ 227 | "switch", 228 | "motion", 229 | "presence", 230 | "acceleration", 231 | "contact", 232 | "temperature", 233 | "battery", 234 | "threeAxis", 235 | ]; 236 | --------------------------------------------------------------------------------