├── .gitignore ├── LICENSE.md ├── README.md ├── config ├── default.json └── smartthings_rsa.pub ├── docker-compose.yml ├── lib ├── api │ ├── lifx.js │ ├── st.js │ └── util.js ├── lifecycle │ ├── configuration.js │ ├── crud.js │ ├── event.js │ └── oauth.js └── local │ ├── db.js │ └── log.js ├── package.json └── server.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Node template 3 | # Logs 4 | logs 5 | *.log 6 | npm-debug.log* 7 | yarn-debug.log* 8 | yarn-error.log* 9 | 10 | # Intellij 11 | .idea 12 | *.iml 13 | 14 | # Runtime data 15 | pids 16 | *.pid 17 | *.seed 18 | *.pid.lock 19 | 20 | # Directory for instrumented libs generated by jscoverage/JSCover 21 | lib-cov 22 | 23 | # Coverage directory used by tools like istanbul 24 | coverage 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Typescript v1 declaration files 46 | typings/ 47 | 48 | # Optional npm cache directory 49 | .npm 50 | 51 | # Optional eslint cache 52 | .eslintcache 53 | 54 | # Optional REPL history 55 | .node_repl_history 56 | 57 | # Output of 'npm pack' 58 | *.tgz 59 | 60 | # Yarn Integrity file 61 | .yarn-integrity 62 | 63 | # dotenv environment variables file 64 | .env 65 | 66 | # next.js build output 67 | .next 68 | 69 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2017 Samsung SmartThings 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SmartThings LIFX Connector C2C Endpoint App 2 | 3 | This project is an example webhook C2C device connector app that uses the SmartThings API to import LIFX bulbs 4 | into your SmartThings account. It's written in NodeJS and can either be deployed to an internet accessible server 5 | or run locally with tunneling to the internet provided by a tool such as [ngrok](https://ngrok.com/). 6 | It uses [Redis](https://redis.io/) for storing LIFX API credentials. 7 | 8 | 9 | ## Folder structure 10 | 11 | - config 12 | - default.json -- Keys, IDs, and other instance specific configuration values 13 | - smartthings_rsa.pub -- Public key for validating callback from SmartThings 14 | - lib 15 | - api 16 | - lifx.js -- Methods for communicating to LIFX required by this app 17 | - st.js -- Prototype framework to abstract away some endpoint app implementation details, not specific to this app 18 | - lifecycle 19 | - configuration.js -- CONFIGURATION lifecycle event handling 20 | - crud.js -- INSTALL, UPDATE, and UNINSTALL lifecycle event handling 21 | - event.js -- EVENT lifecycle handling 22 | - oauth.js -- OAUTH lifecycle handling 23 | - local 24 | - db.js -- Simple Redis-based store of state data for this application 25 | - log.js -- Simple wrapper around console.log, not specific to this app 26 | - docker-compose.yml -- Docker file for bringing up Redis data store 27 | - package.json -- Node package file 28 | - server.js -- This application 29 | 30 | ## Prerequisites 31 | 32 | - [Node.js](https://nodejs.org/en/) and [npm](https://www.npmjs.com/) installed. 33 | - [ngrok](https://ngrok.com/) installed to create a secure tunnel to create a globally available URL for fast testing. 34 | - [Docker](https://www.docker.com/) for running Redis. Alternative you can install and run [Redis](https://redis.io/) manually 35 | - A [Samsung ID and SmartThings](https://account.smartthings.com/login) account 36 | - A [SmartThings Developer Workspace](https://devworkspace.developer.samsung.com/smartthingsconsole/iotweb/site/index.html#/home) account 37 | - At least one [LIFX light bulb](https://www.lifx.com/products/lifx) and the LIFX Mobile app (to install the light) 38 | - Either a LIFX _clientId_ and _clientSecret_ (from LIFX) or a [LIFX personal API Token](https://cloud.lifx.com/) (You can generate the personal 39 | API token during the connector installation process) 40 | 41 | ## Setup instructions 42 | 43 | 1. Clone this repository, and open a command prompt or terminal to the `lifx-demo` directory. 44 | 45 | 2. If you have a LIFX clientId and clientSecret copy them into the appropriate fields in `config/default.json`. If 46 | you don't then skip to the next step (Note that LIFX does not allow the general public to register apps and get 47 | client IDs and secrets. You need to contact them for that) 48 | 49 | 3. If you don't have a LIFX client ID and secret then go to the [LIFX Cloud site](https://cloud.lifx.com/) and generate a personal access token 50 | from the Settings menu accessed from the upper right of the page. Save this token for later use (you may want to do 51 | that on your mobile device so that you can copy and paste it) 52 | 53 | 4. Install the dependencies: `npm install`. 54 | 55 | 5. Bring up Redis with `docker-compose up -d` 56 | 57 | 6. Start the server: `npm start`. 58 | 59 | 7. Start ngrok: `ngrok http 3000`. Copy the `https:` URL to your clipboard. 60 | 61 | 8. Log into the SmartThings [Developer Workspace](https://devworkspace.developer.samsung.com/) and go to the 62 | [Cloud-To-Cloud](https://devworkspace.developer.samsung.com/smartthingsconsole/iotweb/site/index.html#/development/smartThingsDevice/cloudToCloud) 63 | devices page. Click _Create_ to start the process of creating a device profile and connector app. 64 | 65 | 01. 01 **Device info.** Enter and save a Service name such as "My LIFX Connector" 66 | 02. 01 **Device info.** Click _Add a device profile_ to create a device profile for your light. Give the device a name 67 | such as "LIFX Color Bulb" a VID such as "lifx-color-bulb" and an optional description. Set the _Device type_ to _Light_. 68 | Click the plus (+) sign to add capabilities and select the _Color Control_, _Color Temperature_, _Switch_ and _Switch Level_ 69 | capabilities and click _ADD_. Finally scroll down and select _Switch: main_ for _main state_ and _Main action_ and click _Save_ 70 | to create the device profile. Then click _Next_. 71 | 03. **02 Connector info** Enter a connector name and description. You can leave _Multi instance_ set to _Single and should leave the 72 | _Connector type_ set to _Webhook endpoint_. 73 | 04. **02 Connector info** Click _Settings_ to define API scopes. Select the _r:devices:*_, _w:devices:*_, _i:deviceprofiles_, _r:schedules_ and _w:schedules_ scopes and click _Set_. 74 | 05. **02 Connector info** Paste the ngrok URL you coppied in step 7 into the _Target URL_ page and click _SAVE AND NEXT_. You should notice 75 | messages in your server log indicating that it received the PING lifecycle event. 76 | 06. **03 Self-publish** Copy the _Public key_ text into the `config/smartthings_rsa.pub` file in your server directory. Also copy 77 | the _Client ID_ and _Client Secret_ values into the `config/default.json` into the corresponding entries under _"connector"_. 78 | 06. **03 Self-publish** Enter a name you will recognize under _Model code_ and click _NEXT_ and then _CLOSE_. 79 | 07. Click on your entry in the list and select the _Device info._ tab and paste the _Device profile ID_ field into 80 | the `config/default.json` file in the `"deviceProfiles": {"color": ""}` entry. 81 | 82 | 9. Stop and restart the server: `CTRL-C`, `npm start`. 83 | 10. On the _Devices_ page of the SmartThings mobile app tap _ADD DEVICES_, tap _ADD DEVICE MANUALLY_ and then select your device from 84 | _My Testing Devices_ at the bottom of the page (you can also install the devices in the ST Classic app from Marketplace -> SmartApps -> My Apps). 85 | 11. If you have configured your server for OAuth with _clientId_ and _clientSecret_ from LIFX, you will be prompted to connect to the LIFX 86 | site to import your devices into SmartThings. In this case the LIFX access token is stored for use by your app without you seeing 87 | it via the standard OAuth process. If your server isn't configured for OAuth (i.e. no _clientId_ and _clientSecret_) then you will be 88 | prompted to manually enter a personal access token. You can get such a token by tapping the _Get a LIFX Personal Access Token >>_ link 89 | at the bottom of the page, logging into LIFX, tapping the _Generate New Token_ button, and copying the token to the clipboard (LIFX won't show 90 | it to you again). Then tap _Done_ and paste the token into the _Enter your LIFX API token_ field. 91 | 12. Whichever method you use to get a token, tap _NEXT_ to go to the next configuration page and tap _Select location_ to select which 92 | LIFX location you want to import into this SmartThings location. Tap _DONE_ to install the connector app and create the devices. 93 | -------------------------------------------------------------------------------- /config/default.json: -------------------------------------------------------------------------------- 1 | { 2 | "connector": { 3 | "appName": "REPLACE WITH THE CONNECTOR APP NAME FROM DEV WORKSPACE", 4 | "clientId": "REPLACE WITH THE CLIENT ID FROM DEV WORKSPACE", 5 | "clientSecret": "REPLACE WITH THE CLIENT SECRET FROM DEV WORKSPACE" 6 | }, 7 | "deviceProfiles": { 8 | "color": "REPLACE WITH YOUR DEVICE PROFILE ID FROM DEV WORKSPACE" 9 | }, 10 | "lifx": { 11 | "apiEndpoint": "https://api.lifx.com/v1", 12 | "oauthEndpoint": "https://cloud.lifx.com/oauth", 13 | "clientId": "", 14 | "clientSecret": "" 15 | }, 16 | "smartThings": { 17 | "apiEndpoint": "https://api.smartthings.com" 18 | }, 19 | "redis": { 20 | "host": "127.0.0.1", 21 | "port": 6379 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /config/smartthings_rsa.pub: -------------------------------------------------------------------------------- 1 | REPLACE THIS TEXT WITH YOUR PUBLIC KEY -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | services: 3 | redis: 4 | image: redis:3.2.8 5 | ports: 6 | - "6379:6379" 7 | -------------------------------------------------------------------------------- /lib/api/lifx.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const qs = require('querystring'); 4 | const rp = require('request-promise'); 5 | const log = require('../local/log'); 6 | const config = require('config'); 7 | const lifxClientId = config.get('lifx.clientId'); 8 | const lifxClientSecret = config.get('lifx.clientSecret'); 9 | const lifxApiEndpoint = config.get('lifx.apiEndpoint'); 10 | const lifxOauthEndpoint = config.get('lifx.oauthEndpoint'); 11 | 12 | /** 13 | * LIFX API calls used by this application 14 | */ 15 | module.exports = { 16 | 17 | /** 18 | * Handles OAuth2 callback from LIFX, making request to exchange the code for access and refresh tokens 19 | * 20 | * @param installedAppId 21 | * @param queryString 22 | * @returns {*} 23 | */ 24 | handleOauthCallback: function(installedAppId, queryString) { 25 | let params = qs.parse(queryString); 26 | let req = { 27 | client_id: lifxClientId, 28 | client_secret: lifxClientSecret, 29 | grant_type: "authorization_code", 30 | code: params.code, 31 | scope: params.scope 32 | }; 33 | let body = JSON.stringify(req); 34 | let options = { 35 | method: 'POST', 36 | uri: `${lifxOauthEndpoint}/token`, 37 | headers: { 38 | "Content-Type": "application/json", 39 | "User-Agent": "SmartThings Integration" 40 | }, 41 | body: body, 42 | transform: function(body) { 43 | log.debug("body=" + body); 44 | return JSON.parse(body) 45 | } 46 | }; 47 | return rp(options); 48 | }, 49 | 50 | /** 51 | * Returns a list of LIFX location id and name pairs 52 | * 53 | * @param token LIFX access token 54 | * @param callback Function called with the location list 55 | * @returns [{"id":"locationid", "name":"location name}...] 56 | */ 57 | getLocations: function(token, callback) { 58 | let options = { 59 | method: 'GET', 60 | uri: `${lifxApiEndpoint}/lights/`, 61 | headers: { 62 | "User-Agent": "SmartThings Integration", 63 | "Authorization": `Bearer ${token}` 64 | }, 65 | transform: function (body) { 66 | return JSON.parse(body) 67 | } 68 | }; 69 | rp(options).then(function(data) { 70 | let locations = []; 71 | data.forEach(function(item) { 72 | locations.push({id: item.location.id, name: item.location.name}); 73 | }); 74 | callback(locations); 75 | }).error(function(err) { 76 | log.error(`$err encountered retrieving locations`) 77 | }); 78 | }, 79 | 80 | /** 81 | * Returns a list of lights in a location 82 | * 83 | * @param token LIFX access token 84 | * @param lifxLocationId LIFX location ID 85 | * @param callback Function called with list of lights 86 | * @see https://api.developer.lifx.com/docs/list-lights 87 | */ 88 | getLights: function(token, lifxLocationId, callback) { 89 | let options = { 90 | method: 'GET', 91 | uri: `${lifxApiEndpoint}/lights/location_id:${lifxLocationId}`, 92 | headers: { 93 | "User-Agent": "SmartThings Integration", 94 | "Authorization": `Bearer ${token}` 95 | }, 96 | transform: function (body) { 97 | return JSON.parse(body) 98 | } 99 | }; 100 | rp(options).then(function(data) { 101 | callback(data); 102 | }); 103 | }, 104 | 105 | /** 106 | * Returns a description of a particular light 107 | * 108 | * @param token 109 | * @param externalId 110 | * @param callback 111 | * @see https://api.developer.lifx.com/docs/list-lights 112 | */ 113 | getLight: function(token, externalId, callback) { 114 | let options = { 115 | method: 'GET', 116 | uri: `${lifxApiEndpoint}/lights/id:${externalId}`, 117 | headers: { 118 | "User-Agent": "SmartThings Integration", 119 | "Authorization": `Bearer ${token}` 120 | }, 121 | transform: function (body) { 122 | return JSON.parse(body) 123 | } 124 | }; 125 | rp(options).then(function(data) { 126 | callback(data); 127 | }); 128 | }, 129 | 130 | /** 131 | * Set the state of a specific light 132 | * 133 | * @param token 134 | * @param externalId 135 | * @param body 136 | * @param callback 137 | * @see https://api.developer.lifx.com/docs/set-state 138 | */ 139 | sendCommand: function(token, externalId, body, callback) { 140 | let options = { 141 | method: 'PUT', 142 | uri: `${lifxApiEndpoint}/lights/id:${externalId}/state`, 143 | headers: { 144 | "User-Agent": "SmartThings Integration", 145 | "Authorization": `Bearer ${token}` 146 | }, 147 | body: JSON.stringify(body), 148 | transform: function(body) { 149 | return JSON.parse(body) 150 | } 151 | }; 152 | log.debug(`authorization=${options.headers.Authorization}`); 153 | log.debug(`uri=${options.uri}`); 154 | rp(options).then(function(data) { 155 | if (data && callback) { 156 | callback(data); 157 | } 158 | }).catch(function(err){ 159 | log.error(`${err} sending commands to ${externalId}`) 160 | }); 161 | }, 162 | 163 | /** 164 | * Given a light state object, returns a list of the events to initialize the state on the SmartThings platform. 165 | * @param light Object returned from getLight or and item from getLights 166 | * @returns List of event objects 167 | */ 168 | allLightEvents(light) { 169 | return fullEventList(light); 170 | }, 171 | 172 | initialLightEvents(light) { 173 | let events = fullEventList(light); 174 | /* 175 | events.push({ 176 | component: "main", 177 | capability: "healthCheck", 178 | attribute: "DeviceWatch-Enroll", 179 | value: '{"protocol": "cloud", "scheme":"untracked"}' 180 | }); 181 | */ 182 | return events; 183 | } 184 | }; 185 | 186 | function fullEventList(light) { 187 | const healthStatus = light.connected ? "online" : "offline"; 188 | return [ 189 | { 190 | component: "main", 191 | capability: "switch", 192 | attribute: "switch", 193 | value: light.power 194 | }, 195 | { 196 | component: "main", 197 | capability: "switchLevel", 198 | attribute: "level", 199 | value: light.brightness * 100 200 | }, 201 | { 202 | component: "main", 203 | capability: "colorTemperature", 204 | attribute: "colorTemperature", 205 | value: light.color.kelvin 206 | }, 207 | { 208 | component: "main", 209 | capability: "colorControl", 210 | attribute: "hue", 211 | value: light.color.hue / 3.6 212 | }, 213 | { 214 | component: "main", 215 | capability: "colorControl", 216 | attribute: "saturation", 217 | value: light.color.saturation * 100 218 | }, 219 | { 220 | component: "main", 221 | capability: "healthCheck", 222 | attribute: "DeviceWatch-DeviceStatus", 223 | value: healthStatus 224 | }, 225 | { 226 | component: "main", 227 | capability: "healthCheck", 228 | attribute: "healthStatus", 229 | value: healthStatus 230 | } 231 | ]; 232 | } 233 | -------------------------------------------------------------------------------- /lib/api/st.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const rp = require('request-promise'); 4 | const log = require('../local/log'); 5 | 6 | const config = require('config'); 7 | const apiEndpoint = config.get('smartThings.apiEndpoint'); 8 | 9 | /** 10 | * SmartThings API calls used by this application 11 | */ 12 | module.exports = { 13 | 14 | /** 15 | * Create a device. The params argument is an object with the following properties: 16 | * 17 | * profileId: ID of the device profile (created outside of this app) 18 | * locationId: ID of the location into which the device should be placed 19 | * installedAppId: ID of the installed instance of this C2C connect endpoint app 20 | */ 21 | createDevice(token, params) { 22 | log.debug(`create(profileId:${params.profileId}, locationId:${params.locationId}, installedAppId:${params.installedAppId})`); 23 | let body = { 24 | label: params.label, 25 | locationId: params.locationId, 26 | app: { 27 | profileId: params.profileId, 28 | installedAppId: params.installedAppId, 29 | externalId: params.externalId 30 | } 31 | }; 32 | let uri = apiEndpoint + "/devices"; 33 | let options = { 34 | method: 'POST', 35 | uri: uri, 36 | headers: { 37 | "Content-Type": "application/json", 38 | "Authorization": "Bearer " + token 39 | }, 40 | body: JSON.stringify(body), 41 | transform: function(body, response, resolveWithFullResponse) { 42 | return JSON.parse(body) 43 | } 44 | }; 45 | return rp(options) 46 | }, 47 | 48 | /** 49 | * Deletes the specified device 50 | */ 51 | deleteDevice(token, deviceId) { 52 | log.debug(`removeDevice(${deviceId})`); 53 | let uri = apiEndpoint + "/devices"; 54 | let options = { 55 | method: 'DELETE', 56 | uri: uri, 57 | headers: { 58 | "Content-Type": "application/json", 59 | "Authorization": "Bearer " + token 60 | } 61 | }; 62 | return rp(options) 63 | }, 64 | 65 | /** 66 | * Creates one or more events for the specified device. The 'events' argument is an array of objects, each of 67 | * which has the following properties: 68 | * 69 | * component: Name of the component. Should be set to 'main' for a device with only one component 70 | * capability: Name of the capability in camel-case form, e.g. 'switchLevel' 71 | * attribute: Name of the event attribute, e.g. 'level' 72 | * value: Value of the event attribute 73 | * unit: (optional), unit of measure of the attribute, e.g. 'F' or 'C' for a temperature 74 | */ 75 | sendEvents(token, deviceId, events) { 76 | let uri = apiEndpoint + "/devices/" + deviceId + "/events"; 77 | log.trace(`uri: ${uri}`); 78 | log.trace(`token: ${token}`); 79 | log.trace("sendEvents (" + deviceId + ", " + JSON.stringify(events) + ")"); 80 | let options = { 81 | method: 'POST', 82 | uri: uri, 83 | headers: { 84 | "Content-Type": "application/json; charset=utf-8", 85 | "Authorization": "Bearer " + token 86 | }, 87 | body: JSON.stringify(events) 88 | }; 89 | return rp(options).catch(function(err) { 90 | log.error(`${err} sending events for device ${deviceId}`) 91 | }) 92 | }, 93 | 94 | 95 | /** 96 | * Returns a list of child devices of the specified connector app instance 97 | * 98 | * @param token 99 | * @param locationId 100 | * @param installedSmartAppId 101 | * @returns {*} 102 | */ 103 | listDevices(token, locationId, installedSmartAppId) { 104 | log.debug(`list(${installedSmartAppId})`); 105 | let isa = installedSmartAppId 106 | let url = `${apiEndpoint}/devices?locationId=${locationId}`; 107 | let opts = { 108 | url: url, 109 | method: 'GET', 110 | json: true, 111 | headers: { 112 | "Content-Type": "application/json; charset=utf-8", 113 | 'Authorization': 'Bearer ' + token 114 | }, 115 | transform: function(body, response, resolveWithFullResponse) { 116 | log.debug(`list=${body}`) 117 | let result = []; 118 | let data = body; //JSON.parse(body) 119 | if (data.items) { 120 | let size = data.items.length; 121 | for (let i=0; i < data.items.length; i++) { 122 | let it = data.items[i]; 123 | if (it.app) { 124 | if (it.app.installedAppId == isa) { 125 | result.push(it); 126 | } 127 | } 128 | } 129 | } 130 | return result; 131 | } 132 | }; 133 | return rp(opts) 134 | }, 135 | 136 | /** 137 | * Schedule periodic event execution 138 | * 139 | * @param token SmartThings access token 140 | * @param installedAppId ID of connector app instance 141 | * @param name Name of this schedule, which will be passed back in the event 142 | * @param cronExpression Cron expression defining when to generate events 143 | */ 144 | createSchedule(token, installedAppId, name, cronExpression) { 145 | log.debug(`createSchedule(${installedAppId}, ${name}, ${cronExpression})`); 146 | let body = { 147 | name: name, 148 | cron: { 149 | expression: cronExpression, 150 | timezone: "GMT" 151 | } 152 | }; 153 | let uri = `${apiEndpoint}/installedapps/${installedAppId}/schedules`; 154 | let options = { 155 | method: 'POST', 156 | uri: uri, 157 | headers: { 158 | "Content-Type": "application/json", 159 | "Authorization": "Bearer " + token 160 | }, 161 | body: JSON.stringify(body), 162 | transform: function(body, response, resolveWithFullResponse) { 163 | return JSON.parse(body) 164 | } 165 | }; 166 | return rp(options) 167 | }, 168 | 169 | /** 170 | * Delete a specific scheduled event 171 | * @param token SmartThings access token 172 | * @param installedAppId ID of connector app instance 173 | * @param name Name of the schedule to delete 174 | */ 175 | deleteSchedule(token, installedAppId, name) { 176 | log.debug(`deleteSchedule(${installedAppId}, ${name})`); 177 | let body = { 178 | name: name, 179 | cron: { 180 | expression: cronExpression, 181 | timezone: "GMT" 182 | } 183 | }; 184 | let uri = `${apiEndpoint}/installedapps/${installedAppId}/schedules/${name}`; 185 | let options = { 186 | method: 'DELETE', 187 | uri: uri, 188 | headers: { 189 | "Content-Type": "application/json", 190 | "Authorization": "Bearer " + token 191 | }, 192 | body: JSON.stringify(body), 193 | transform: function(body, response, resolveWithFullResponse) { 194 | return JSON.parse(body) 195 | } 196 | }; 197 | return rp(options) 198 | }, 199 | 200 | /** 201 | * Delete all scheduled events for an installed app instance 202 | * 203 | * @param token SmartThings access token 204 | * @param installedAppId ID of connector app instance 205 | */ 206 | deleteSchedules(token, installedAppId) { 207 | log.debug(`deleteSchedules(${installedAppId})`); 208 | let body = { 209 | name: name, 210 | cron: { 211 | expression: cronExpression, 212 | timezone: "GMT" 213 | } 214 | }; 215 | let uri = `${apiEndpoint}/installedapps/${installedAppId}/schedules`; 216 | let options = { 217 | method: 'DELETE', 218 | uri: uri, 219 | headers: { 220 | "Content-Type": "application/json", 221 | "Authorization": "Bearer " + token 222 | }, 223 | body: JSON.stringify(body), 224 | transform: function(body, response, resolveWithFullResponse) { 225 | return JSON.parse(body) 226 | } 227 | }; 228 | return rp(options) 229 | } 230 | }; 231 | 232 | -------------------------------------------------------------------------------- /lib/api/util.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const log = require('../local/log'); 4 | const st = require('./st'); 5 | const lifx = require('../api/lifx'); 6 | const config = require('config'); 7 | const deviceProfiles = config.get('deviceProfiles'); 8 | 9 | /** 10 | * Utility methods 11 | */ 12 | module.exports = { 13 | 14 | /** 15 | * Compares device lists from LIFX and SmartThings, creating and deleting devices as necessary 16 | * 17 | * @param token SmartThings access token 18 | * @param locationId SmartThings location ID 19 | * @param lifxDevices List of devices from LIFX 20 | * @param smartThingsDevices List of devices from SmartThings 21 | */ 22 | reconcileDeviceLists: function (token, locationId, installedAppId, lifxDevices, smartThingsDevices) { 23 | // Iterate over lights to see if any are missing from SmartThings and need to be added 24 | lifxDevices.forEach(function (light) { 25 | if (!smartThingsDevices.find(function (device) { return device.app.externalId == light.id; })) { 26 | 27 | // Device from LIFX not found in SmartThings, add it 28 | let map = { 29 | label: light.label, 30 | profileId: deviceProfileId(light), 31 | locationId: locationId, 32 | installedAppId: installedAppId, 33 | externalId: light.id 34 | }; 35 | 36 | st.createDevice(token, map).then(function (data) { 37 | log.debug("created device " + data.deviceId); 38 | st.sendEvents(token, data.deviceId, lifx.allLightEvents(light)).then (function(data) { 39 | log.trace(`RESPONSE: ${JSON.stringify(data, null, 2)}`); 40 | }); 41 | }).catch(function (err) { 42 | log.error(`${err} creating device`); 43 | }); 44 | } 45 | }); 46 | 47 | // Iterate over all lights in SmartThings and delete any that are missing from LIFX 48 | smartThingsDevices.forEach(function(device) { 49 | if (!lifxDevices.find(function(light) { return device.app.externalId == light.id; })) { 50 | 51 | // Device in SmartThings but not LIFX, delete it 52 | st.deleteDevice(token, device.deviceId).then(function(data) { 53 | log.debug(`deleted device ${device.deviceId}`); 54 | }).catch(function (err) { 55 | log.error(`${err} deleting device`); 56 | }); 57 | } 58 | }); 59 | }, 60 | 61 | /** 62 | * Returns LIFX access token, which is in Redis persisted state when using OAuth with clientId and clientSecret 63 | * or in a configuration setting when users enter personal tokens directly 64 | * 65 | * @param state 66 | * @param configuration 67 | */ 68 | lifxAccessToken: function(state, configuration) { 69 | if (state) { 70 | return state.lifxAccessToken; 71 | } 72 | else { 73 | return configuration.lifxAccessToken[0].stringConfig.value; 74 | } 75 | } 76 | }; 77 | 78 | function deviceProfileId(light) { 79 | log.debug(`deviceProfileId(${JSON.stringify(light)})`); 80 | let result = deviceProfiles.white; 81 | if (light.product.capabilities.has_color) { 82 | result = deviceProfiles.color; 83 | } 84 | else if (light.product.capabilities.has_variable_color_temp) { 85 | result = deviceProfiles.colorTemp; 86 | } 87 | log.debug(`profileId=${result}`); 88 | return result; 89 | } -------------------------------------------------------------------------------- /lib/lifecycle/configuration.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const log = require('../local/log'); 4 | const db = require('../local/db'); 5 | const lifx = require('../api/lifx'); 6 | const util = require('../api/util'); 7 | 8 | const config = require('config'); 9 | const appName = config.get('connector.appName'); 10 | const lifxOauthEndpoint = config.get('lifx.oauthEndpoint'); 11 | const lifxClientId = config.get('lifx.clientId'); 12 | 13 | /** 14 | * CONFIGURATION lifecycle event handling 15 | */ 16 | module.exports = { 17 | 18 | /** 19 | * Return scopes and other data about this app 20 | */ 21 | initialize: function(configurationData, response) 22 | { 23 | let config = { 24 | initialize: { 25 | id: appName, 26 | name: 'LIFX Connector', 27 | description: 'Creates LIFX devices in SmartThings', 28 | permissions: ['l:devices', 'i:deviceprofiles', 'w:schedules'], 29 | firstPageId: 'mainPage' 30 | } 31 | }; 32 | log.response(response, {statusCode: 200, configurationData: config}); 33 | }, 34 | 35 | /** 36 | * Return the configuration page for the app, either the link to log into LIFX or, if already authenticated, 37 | * the page to select the LIFX location to import. 38 | */ 39 | page: function(configurationData, response) { 40 | db.get(configurationData.installedAppId, function(state) { 41 | if (lifxClientId) { 42 | if (state && state.lifxAccessToken) { 43 | // Authenticated, display page to select location 44 | locationsPage(configurationData, response) 45 | } 46 | else { 47 | // Not authenticate but with a clientId, display page to connect to LIFX 48 | authPage(configurationData, response); 49 | } 50 | } 51 | else { 52 | if (configurationData.pageId == "locationsPage") { 53 | // Display page to select location with test API key 54 | locationsPage(configurationData, response) 55 | } 56 | else { 57 | // No client ID. Prompt for direct entry of access token 58 | tokenPage(configurationData, response); 59 | } 60 | } 61 | }); 62 | } 63 | }; 64 | 65 | /** 66 | * Page that links to LIFX for login 67 | */ 68 | function authPage(configurationData, response) { 69 | let connectorAppId = configurationData.installedAppId; 70 | //let url = `${lifxOauthEndpoint}/authorize?client_id=${lifxClientId}&state=${connectorAppId}&scope=remote_control:all&response_type=code`; 71 | let url = `${lifxOauthEndpoint}/authorize?client_id=${lifxClientId}&scope=remote_control:all&response_type=code`; 72 | log.debug("AUTH URL="+ url); 73 | let config = { 74 | page: { 75 | pageId: 'mainPage', 76 | name: 'Connect to LIFX', 77 | nextPageId: null, 78 | previousPageId: null, 79 | complete: false, 80 | sections: [ 81 | { 82 | name: "Remote service authorization", 83 | settings: [ 84 | { 85 | type: "OAUTH", 86 | id: "OAuth", 87 | name: "Connect to LIFX", 88 | required: false, 89 | urlTemplate: url 90 | } 91 | ] 92 | } 93 | ] 94 | } 95 | }; 96 | log.response(response, {statusCode: 200, configurationData: config}); 97 | } 98 | 99 | /** 100 | * Page that allows entry of a personal API token for testing purposes (in cases where OAuth client credentials 101 | * are not available. 102 | */ 103 | function tokenPage(configurationData, response) { 104 | let connectorAppId = configurationData.installedAppId; 105 | let url = `${lifxOauthEndpoint}/authorize?client_id=${lifxClientId}&state=${connectorAppId}&scope=remote_control:all&response_type=code`; 106 | log.debug("AUTH URL="+ url); 107 | let config = { 108 | page: { 109 | pageId: 'mainPage', 110 | name: 'Connect to LIFX', 111 | nextPageId: "locationsPage", 112 | previousPageId: null, 113 | complete: false, 114 | sections: [ 115 | { 116 | name: "Remote service authorization", 117 | settings: [ 118 | { 119 | type: "PARAGRAPH", 120 | id: "text", 121 | name: "This app is in test mode. To use it you should enter your test access token from the LIFX developer site. " + 122 | "Test mode provides all features of the app other than OAuth into LIFX. " + 123 | "To test that feature you will need to obtain a client ID and secret from LIFX. You can do that from the " + 124 | "link below.", 125 | }, 126 | { 127 | type: "TEXT", 128 | id: "lifxAccessToken", 129 | name: "Enter your LIFX API token", 130 | description: "From https://cloud.lifx.com/", 131 | required: true 132 | } 133 | ] 134 | }, 135 | { 136 | settings: [ 137 | { 138 | type: "LINK", 139 | id: "href", 140 | name: "Get a LIFX Personal Access Token >>", 141 | required: false, 142 | url: "https://cloud.lifx.com/settings" 143 | } 144 | ] 145 | } 146 | ] 147 | } 148 | }; 149 | log.response(response, {statusCode: 200, configurationData: config}); 150 | } 151 | 152 | /** 153 | * Page that allows a location to be chosen 154 | */ 155 | function locationsPage(configurationData, response) { 156 | db.get(configurationData.installedAppId, function(state) { 157 | let testToken = configurationData.config.lifxAccessToken; 158 | let lifxAccessToken = util.lifxAccessToken(state, configurationData.config); 159 | lifx.getLocations(lifxAccessToken, function(locations) { 160 | let config = { 161 | page: { 162 | pageId: 'locationsPage', 163 | name: 'Select Location', 164 | nextPageId: null, 165 | previousPageId: null, 166 | complete: true, 167 | sections: [ 168 | { 169 | settings: [ 170 | { 171 | type: "ENUM", 172 | id: "lifxLocationId", 173 | name: "Select location", 174 | required: false, 175 | options: locations 176 | } 177 | ] 178 | } 179 | ] 180 | } 181 | }; 182 | log.response(response, {statusCode: 200, configurationData: config}); 183 | }); 184 | }); 185 | } -------------------------------------------------------------------------------- /lib/lifecycle/crud.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const db = require('../local/db'); 4 | const log = require('../local/log'); 5 | const lifx = require('../api/lifx'); 6 | const st = require('../api/st'); 7 | const util = require('../api/util'); 8 | 9 | /** 10 | * INSTALL, UPDATE, and UNINSTALL lifecycle events 11 | */ 12 | module.exports = { 13 | 14 | /** 15 | * Called when the app is first installed after the configuration and permissions page. Creates devices and 16 | * schedules periodic 5 minute polling of device states. 17 | */ 18 | install: function(installData) { 19 | updateDevices(installData, []); 20 | st.createSchedule(installData.authToken, installData.installedApp.installedAppId, 'poll', '* * * * ? *'); 21 | }, 22 | 23 | /** 24 | * Called any time the configuration page is updated. Creates any new devices that may have been added. 25 | * If there is more than one location and the selected location is changed, then existing devices are 26 | * removed and new devices created. 27 | */ 28 | update: function(updateData) { 29 | let token = updateData.authToken; 30 | let locationId = updateData.installedApp.locationId; 31 | let installedAppId = updateData.installedApp.installedAppId; 32 | st.listDevices(token, locationId, installedAppId).then(function(list) { 33 | updateDevices(updateData, list); 34 | }); 35 | }, 36 | 37 | /** 38 | * Called when the connector is uninstalled. Nothing to do here since the system automatically deletes 39 | * the devices. 40 | */ 41 | uninstall: function(uninstallData) { 42 | db.delete(uninstallData.installedApp.installedAppId, function() { 43 | log.debug(`${uninstallData.installedApp.installedAppId} connector deleted`); 44 | }); 45 | } 46 | }; 47 | 48 | /** 49 | * Iterates over device lists from SmartThings and LIFX, creating and deleting devices as necessary. 50 | * 51 | * @param params Either installData or updateData 52 | * @param existingDevices List current SmartThings devices for this connector 53 | */ 54 | function updateDevices(params, existingDevices) { 55 | let installedAppId = params.installedApp.installedAppId; 56 | let locationId = params.installedApp.locationId; 57 | let config = params.installedApp.config; 58 | 59 | if (config && config.lifxLocationId) { 60 | // Get the stored LIFX access token (from OAuth journey) 61 | db.get(installedAppId, function (state) { 62 | 63 | // Query LIFX for list of lights in the selected location 64 | let lifxLocationId = config.lifxLocationId[0].stringConfig.value; 65 | let lifxAccessToken = util.lifxAccessToken(state, config); 66 | lifx.getLights(lifxAccessToken, lifxLocationId, function (lights) { 67 | util.reconcileDeviceLists(params.authToken, locationId, installedAppId, lights, existingDevices); 68 | }); 69 | }); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /lib/lifecycle/event.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const log = require('../local/log'); 4 | const db = require('../local/db'); 5 | const lifx = require('../api/lifx'); 6 | const st = require('../api/st'); 7 | const util = require('../api/util'); 8 | 9 | module.exports = { 10 | 11 | /** 12 | * Handles device command events, calling LIFX to control the bulb and generating the appropriate events 13 | * 14 | * @param eventData 15 | * @param commandsEvent 16 | */ 17 | handleDeviceCommand: function(eventData, commandsEvent) { 18 | let deviceCommandsEvent = commandsEvent.deviceCommandsEvent; 19 | let token = eventData.authToken; 20 | db.get(eventData.installedApp.installedAppId, function(state) { 21 | let lifxAccessToken = util.lifxAccessToken(state, eventData.installedApp.config); 22 | deviceCommandsEvent.commands.forEach(function(cmd) { 23 | switch (cmd.command) { 24 | case "on": { 25 | lifx.sendCommand(lifxAccessToken, deviceCommandsEvent.externalId, {power: "on"}, function (data, resp) { 26 | let body = [ 27 | { 28 | component: "main", 29 | capability: "switch", 30 | attribute: "switch", 31 | value: "on" 32 | } 33 | ]; 34 | st.sendEvents(token, deviceCommandsEvent.deviceId, body); 35 | }); 36 | break; 37 | } 38 | case "off": { 39 | lifx.sendCommand(lifxAccessToken, deviceCommandsEvent.externalId, {power: "off"}, function (data, resp) { 40 | let body = [ 41 | { 42 | component: "main", 43 | capability: "switch", 44 | attribute: "switch", 45 | value: "off" 46 | } 47 | ]; 48 | st.sendEvents(token, deviceCommandsEvent.deviceId, body); 49 | }); 50 | break; 51 | } 52 | case "setLevel": { 53 | let level = cmd.arguments[0]; 54 | let lifxLevel =level / 100.0; 55 | lifx.sendCommand(lifxAccessToken, deviceCommandsEvent.externalId, { 56 | power: "on", 57 | brightness: lifxLevel 58 | }, function (data, resp) { 59 | let body = [ 60 | { 61 | component: "main", 62 | capability: "switch", 63 | attribute: "switch", 64 | value: "on" 65 | }, 66 | { 67 | component: "main", 68 | capability: "switchLevel", 69 | attribute: "level", 70 | value: level 71 | } 72 | ]; 73 | st.sendEvents(token, deviceCommandsEvent.deviceId, body); 74 | }); 75 | break; 76 | } 77 | case "setHue": { 78 | let hue = cmd.arguments[0]; 79 | let lifxHue =hue * 3.6; 80 | lifx.sendCommand(lifxAccessToken, deviceCommandsEvent.externalId, { 81 | power: "on", 82 | color: `hue:${lifxHue}` 83 | }, function (data, resp) { 84 | let body = [ 85 | { 86 | component: "main", 87 | capability: "switch", 88 | attribute: "switch", 89 | value: "on" 90 | }, 91 | { 92 | component: "main", 93 | capability: "colorControl", 94 | attribute: "hue", 95 | value: hue 96 | } 97 | ]; 98 | st.sendEvents(token, deviceCommandsEvent.deviceId, body); 99 | }); 100 | break; 101 | } 102 | case "setSaturation": { 103 | let saturation = cmd.arguments[0]; 104 | let lifxSat = saturation / 100.0; 105 | lifx.sendCommand(lifxAccessToken, deviceCommandsEvent.externalId, { 106 | power: "on", 107 | color: `saturation:${lifxSat}` 108 | }, function (data, resp) { 109 | let body = [ 110 | { 111 | component: "main", 112 | capability: "switch", 113 | attribute: "switch", 114 | value: "on" 115 | }, 116 | { 117 | component: "main", 118 | capability: "colorControl", 119 | attribute: "saturation", 120 | value: saturation 121 | } 122 | ]; 123 | st.sendEvents(token, deviceCommandsEvent.deviceId, body); 124 | }); 125 | break; 126 | } 127 | case "setColorTemperature": { 128 | let kelvin = cmd.arguments[0]; 129 | lifx.sendCommand(lifxAccessToken, deviceCommandsEvent.externalId, { 130 | power: "on", 131 | color: `kelvin:${kelvin}` 132 | }, function (data, resp) { 133 | let body = [ 134 | { 135 | component: "main", 136 | capability: "switch", 137 | attribute: "switch", 138 | value: "on" 139 | }, 140 | { 141 | component: "main", 142 | capability: "colorTemperature", 143 | attribute: "colorTemperature", 144 | value: kelvin 145 | } 146 | ]; 147 | st.sendEvents(token, deviceCommandsEvent.deviceId, body); 148 | }); 149 | break; 150 | } 151 | case "setColor": { 152 | let map = cmd.arguments[0]; 153 | let lifxHue = map.hue * 3.6; 154 | let lifxSat = map.saturation / 100.0; 155 | lifx.sendCommand(lifxAccessToken, deviceCommandsEvent.externalId, { 156 | power: "on", 157 | color: `hue:${lifxHue} saturation:${lifxSat}` 158 | }, function (data, resp) { 159 | let body = [ 160 | { 161 | component: "main", 162 | capability: "switch", 163 | attribute: "switch", 164 | value: "on" 165 | }, 166 | { 167 | component: "main", 168 | capability: "colorControl", 169 | attribute: "hue", 170 | value: map.hue 171 | }, 172 | { 173 | component: "main", 174 | capability: "colorControl", 175 | attribute: "saturation", 176 | value: map.saturation 177 | } 178 | ]; 179 | st.sendEvents(token, deviceCommandsEvent.deviceId, body); 180 | }); 181 | break; 182 | } 183 | } 184 | }); 185 | }); 186 | }, 187 | 188 | /** 189 | * Handles the periodic polling event 190 | * 191 | * @param eventData 192 | * @param scheduleEvent 193 | */ 194 | handleScheduledEvent: function(eventData, scheduleEvent) { 195 | let token = eventData.authToken; 196 | st.listDevices(token, eventData.installedApp.locationId, eventData.installedApp.installedAppId).then(function(devices) { 197 | db.get(eventData.installedApp.installedAppId, function(state) { 198 | let lifxAccessToken = util.lifxAccessToken(state, eventData.installedApp.config); 199 | let lifxLocationId = eventData.installedApp.config.lifxLocationId[0].stringConfig.value; 200 | lifx.getLights(lifxAccessToken, lifxLocationId, function(lights) { 201 | lights.forEach(function(light) { 202 | let device = devices.find(function(d) { return d.app.externalId == light.id; }); 203 | if (device) { 204 | log.debug(`Sending events for ${light.id}`); 205 | st.sendEvents(eventData.authToken, device.deviceId, lifx.allLightEvents(light)) 206 | } 207 | }); 208 | util.reconcileDeviceLists(token, eventData.installedApp.locationId, eventData.installedApp.installedAppId, lights, devices); 209 | }); 210 | }); 211 | }); 212 | } 213 | }; 214 | -------------------------------------------------------------------------------- /lib/lifecycle/oauth.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const db = require('../local/db'); 4 | const log = require('../local/log'); 5 | const lifx = require('../api/lifx'); 6 | const config = require('config'); 7 | 8 | module.exports = { 9 | 10 | /** 11 | * Handles the OAuth callback from LIFX, calling them with the code and receiving the access and refresh tokens, 12 | * which are save in the database. 13 | * 14 | * @param oauthCallbackData 15 | */ 16 | handleOauthCallback: function(oauthCallbackData) { 17 | lifx.handleOauthCallback(oauthCallbackData.installedAppId, oauthCallbackData.urlPath).then(function(data) { 18 | log.debug("RES BODY=" + JSON.stringify(data)); 19 | db.put(oauthCallbackData.installedAppId, {lifxAccessToken: data.access_token, lifxRefreshToken: data.refresh_token}); 20 | }).catch(function(err) { 21 | log.error(`RES ERR =${err}`); 22 | }); 23 | } 24 | 25 | }; -------------------------------------------------------------------------------- /lib/local/db.js: -------------------------------------------------------------------------------- 1 | "use strict" 2 | 3 | const redis = require("redis"); 4 | const config = require('config'); 5 | const redisClient = redis.createClient({host: config.get('redis.host'), port: config.get('redis.port')}); 6 | 7 | function key(installedAppId) { 8 | return "lifx:" + installedAppId; 9 | } 10 | 11 | /** 12 | * Redis-based storage and retrival of account data 13 | */ 14 | module.exports = { 15 | 16 | /** 17 | * Saves data map associated with an installed instance of the app 18 | */ 19 | put: function(installedAppId, map, callback) { 20 | let args = [key(installedAppId)]; 21 | for (let key in map) { 22 | if (map.hasOwnProperty(key)) { 23 | args.push(key); 24 | args.push(map[key]); 25 | } 26 | } 27 | redisClient.hmset(args, function(err, reply) { 28 | if (err) { 29 | console.log("REDIS ERROR " + JSON.stringify(err)); 30 | } 31 | else if (callback) { 32 | callback(reply); 33 | } 34 | }); 35 | }, 36 | 37 | /** 38 | * Delete the entry 39 | */ 40 | delete: function(installedAppId, callback) { 41 | redisClient.del(key(installedAppId), function(err, reply) { 42 | if (err) { 43 | console.log("REDIS ERROR " + JSON.stringify(err)); 44 | } 45 | else if (callback) { 46 | callback(reply); 47 | } 48 | }); 49 | }, 50 | 51 | /** 52 | * Gets the entry for an installed app instance 53 | */ 54 | get: function(installedAppId, callback) { 55 | redisClient.hgetall(key(installedAppId), function(err, reply) { 56 | if (err) { 57 | console.log("REDIS ERROR " + JSON.stringify(err)); 58 | } 59 | else if (callback) { 60 | callback(reply); 61 | } 62 | }); 63 | } 64 | }; 65 | -------------------------------------------------------------------------------- /lib/local/log.js: -------------------------------------------------------------------------------- 1 | "use strict" 2 | 3 | /** 4 | * Simple wrapper around the console for logging various kinds of information 5 | */ 6 | module.exports = { 7 | trace: function(msg) { 8 | console.log("TRACE - " + msg); 9 | }, 10 | debug: function(msg) { 11 | console.log("DEBUG - " + msg); 12 | }, 13 | info: function(msg) { 14 | console.log("INFO - " + msg); 15 | }, 16 | warn: function(msg) { 17 | console.log("WARN - " + msg); 18 | }, 19 | error: function(msg) { 20 | console.log("ERROR - " + msg); 21 | }, 22 | response: function(response, data) { 23 | console.log(`RESPONSE: ${JSON.stringify(data, null, 2)}`); 24 | response.json(data); 25 | } 26 | }; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "smartthings-lifx-demo", 3 | "version": "1.0.0", 4 | "description": "SmartThings/LIFX device integration", 5 | "main": "server.js", 6 | "author": "SmartThings", 7 | "license": "ISC", 8 | "dependencies": { 9 | "bluebird": "^3.5.0", 10 | "body-parser": "^1.17.2", 11 | "config": "^1.26.2", 12 | "express": "^4.15.4", 13 | "fs": "0.0.1-security", 14 | "http-signature": "^1.1.1", 15 | "request": "^2.81.0", 16 | "request-promise": "^4.2.1", 17 | "redis":"^2.8.0", 18 | "form-urlencoded":"^2.0.4" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const express = require('express'); 4 | const bodyParser = require('body-parser'); 5 | const config = require('config'); 6 | const fs = require('fs'); 7 | 8 | const db = require('./lib/local/db'); 9 | const log = require('./lib/local/log'); 10 | const publicKey = fs.readFileSync('./config/smartthings_rsa.pub', 'utf8'); 11 | const httpSignature = require('http-signature'); 12 | 13 | const configurationLifecycle = require('./lib/lifecycle/configuration'); 14 | const oauthLifecycle = require('./lib/lifecycle/oauth'); 15 | const crudLifecycle = require('./lib/lifecycle/crud'); 16 | const eventLifecycle = require('./lib/lifecycle/event'); 17 | 18 | 19 | const app = module.exports = express(); 20 | app.use(bodyParser.json()); 21 | app.post('/', function(req, response) { 22 | callbackHandler(req, response) 23 | }); 24 | 25 | function callbackHandler(req, response) { 26 | if (req.body && req.body.lifecycle === "PING" || signatureIsVerified(req)) { 27 | handleCallback(req, response); 28 | } else { 29 | log.error("Unauthorized"); 30 | response.status(401).send("Forbidden"); 31 | } 32 | } 33 | 34 | function signatureIsVerified(req) { 35 | try { 36 | let parsed = httpSignature.parseRequest(req); 37 | if (!httpSignature.verifySignature(parsed, publicKey)) { 38 | log.error('forbidden - failed verifySignature'); 39 | return false; 40 | } 41 | } catch (err) { 42 | log.error(err); 43 | return false; 44 | } 45 | return true; 46 | } 47 | 48 | function handleCallback(req, response) { 49 | let evt = req.body; 50 | switch (evt.lifecycle) { 51 | 52 | // PING happens during app creation. Respond with challenge to verify app 53 | case 'PING': { 54 | log.trace(`${evt.lifecycle}\nREQUEST: ${JSON.stringify(evt, null, 2)}`); 55 | log.response(response, {statusCode: 200, pingData: {challenge: evt.pingData.challenge}}); 56 | break; 57 | } 58 | 59 | // CONFIGURATION is once with INITIALIZE and then for each PAGE 60 | case 'CONFIGURATION': { 61 | let configurationData = evt.configurationData; 62 | switch (configurationData.phase) { 63 | case 'INITIALIZE': 64 | log.trace(`${evt.lifecycle}/${configurationData.phase}\nREQUEST: ${JSON.stringify(evt, null, 2)}`); 65 | configurationLifecycle.initialize(configurationData, response); 66 | break; 67 | case 'PAGE': 68 | log.trace(`${evt.lifecycle}/${configurationData.phase}/${configurationData.pageId}\nREQUEST: ${JSON.stringify(evt, null, 2)}`); 69 | configurationLifecycle.page(configurationData, response); 70 | break; 71 | default: 72 | throw new Error(`Unsupported config phase: ${configurationData.phase}`); 73 | } 74 | break; 75 | } 76 | 77 | case 'OAUTH_CALLBACK': { 78 | log.trace(`${evt.lifecycle}\nREQUEST: ${JSON.stringify(evt, null, 2)}`); 79 | log.debug(JSON.stringify(evt)); 80 | oauthLifecycle.handleOauthCallback(evt.oauthCallbackData); 81 | log.trace(`RESPONSE: ${JSON.stringify(evt, null, 2)}`); 82 | log.response(response, {statusCode: 200, oAuthCallbackData: {}}); 83 | break; 84 | } 85 | 86 | case 'INSTALL': { 87 | log.trace(`${evt.lifecycle}\nREQUEST: ${JSON.stringify(evt, null, 2)}`); 88 | crudLifecycle.install(evt.installData); 89 | log.trace(`RESPONSE: ${JSON.stringify(evt, null, 2)}`); 90 | log.response(response, {statusCode: 200, installData: {}}); 91 | break; 92 | } 93 | 94 | case 'UPDATE': { 95 | log.trace(`${evt.lifecycle}\nREQUEST: ${JSON.stringify(evt, null, 2)}`); 96 | crudLifecycle.update(evt.updateData); 97 | log.trace(`RESPONSE: ${JSON.stringify(evt, null, 2)}`); 98 | log.response(response, {statusCode: 200, updateData: {}}); 99 | break; 100 | } 101 | 102 | case 'UNINSTALL': { 103 | log.trace(`${evt.lifecycle}\nREQUEST: ${JSON.stringify(evt, null, 2)}`); 104 | crudLifecycle.uninstall(evt.uninstallData); 105 | log.trace(`RESPONSE: ${JSON.stringify(evt, null, 2)}`); 106 | log.response(response, {statusCode: 200, uninstallData: {}}); 107 | break; 108 | } 109 | 110 | case 'EVENT': { 111 | log.trace(`${evt.lifecycle}\nREQUEST: ${JSON.stringify(evt, null, 2)}`); 112 | evt.eventData.events.forEach(function(event) { 113 | switch (event.eventType) { 114 | case "DEVICE_EVENT": { 115 | break; 116 | } 117 | case "TIMER_EVENT": { 118 | eventLifecycle.handleScheduledEvent(evt.eventData, event); 119 | break; 120 | } 121 | case "DEVICE_COMMANDS_EVENT": { 122 | eventLifecycle.handleDeviceCommand(evt.eventData, event); 123 | break; 124 | } 125 | default: { 126 | console.warn(`Unhandled event of type ${event.eventType}`) 127 | } 128 | } 129 | }); 130 | log.response(response, {statusCode: 200, eventData: {}}); 131 | break; 132 | } 133 | 134 | case 'EXECUTE': { 135 | log.trace(`${evt.lifecycle}\nREQUEST: ${JSON.stringify(evt, null, 2)}`); 136 | break; 137 | } 138 | 139 | 140 | default: { 141 | console.log(`Lifecycle ${evt.lifecycle} not supported`); 142 | } 143 | } 144 | } 145 | 146 | app.listen(3003); 147 | log.info('Open: http://127.0.0.1:3003'); 148 | --------------------------------------------------------------------------------