Changing remote branch to PLRG Git server.
[smartapps.git] / official / mood-cube.groovy
1 /**
2  *  Mood Cube
3  *
4  *  Copyright 2014 SmartThings, Inc.
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
7  *  in compliance with the License. You may obtain a copy of the License at:
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
12  *  on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
13  *  for the specific language governing permissions and limitations under the License.
14  *
15  */
16
17 /************
18  * Metadata *
19  ************/
20 definition(
21         name: "Mood Cube",
22         namespace: "smartthings",
23         author: "SmartThings",
24         description: "Set your lighting by rotating a cube containing a SmartSense Multi",
25         category: "SmartThings Labs",
26         iconUrl: "https://s3.amazonaws.com/smartapp-icons/Convenience/App-LightUpMyWorld.png",
27         iconX2Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/App-LightUpMyWorld@2x.png"
28 )
29
30 /**********
31  * Setup  *
32  **********/
33 preferences {
34         page(name: "mainPage", title: "", nextPage: "scenesPage", uninstall: true) {
35                 section("Use the orientation of this cube") {
36                         input "cube", "capability.threeAxis", required: false, title: "SmartSense Multi sensor"
37                 }
38                 section("To control these lights") {
39                         input "lights", "capability.switch", multiple: true, required: false, title: "Lights, switches & dimmers"
40                 }
41                 section([title: " ", mobileOnly:true]) {
42                         label title: "Assign a name", required: false
43                         mode title: "Set for specific mode(s)", required: false
44                 }
45         }
46         page(name: "scenesPage", title: "Scenes", install: true, uninstall: true)
47         page(name: "scenePage", title: "Scene", install: false, uninstall: false, previousPage: "scenesPage")
48         page(name: "devicePage", install: false, uninstall: false, previousPage: "scenePage")
49         page(name: "saveStatesPage", install: false, uninstall: false, previousPage: "scenePage")
50 }
51
52
53 def scenesPage() {
54         log.debug "scenesPage()"
55         def sceneId = getOrientation()
56         dynamicPage(name:"scenesPage") {
57                 section {
58                         for (num in 1..6) {
59                                 href "scenePage", title: "${num}. ${sceneName(num)}${sceneId==num ? ' (current)' : ''}", params: [sceneId:num], description: "", state: sceneIsDefined(num) ? "complete" : "incomplete"
60                         }
61                 }
62                 section {
63                         href "scenesPage", title: "Refresh", description: ""
64                 }
65         }
66 }
67
68 def scenePage(params=[:]) {
69         log.debug "scenePage($params)"
70         def currentSceneId = getOrientation()
71         def sceneId = params.sceneId as Integer ?: state.lastDisplayedSceneId
72         state.lastDisplayedSceneId = sceneId
73         dynamicPage(name:"scenePage", title: "${sceneId}. ${sceneName(sceneId)}") {
74                 section {
75                         input "sceneName${sceneId}", "text", title: "Scene Name", required: false
76                 }
77
78                 section {
79                         href "devicePage", title: "Show Device States", params: [sceneId:sceneId], description: "", state: sceneIsDefined(sceneId) ? "complete" : "incomplete"
80                 }
81
82         section {
83             href "saveStatesPage", title: "Record Current Device States", params: [sceneId:sceneId], description: ""
84         }
85         }
86 }
87
88 def devicePage(params) {
89         log.debug "devicePage($params)"
90
91         getDeviceCapabilities()
92
93         def sceneId = params.sceneId as Integer ?: state.lastDisplayedSceneId
94
95         dynamicPage(name:"devicePage", title: "${sceneId}. ${sceneName(sceneId)} Device States") {
96                 section("Lights") {
97                         lights.each {light ->
98                                 input "onoff_${sceneId}_${light.id}", "boolean", title: light.displayName
99                         }
100                 }
101
102                 section("Dimmers") {
103                         lights.each {light ->
104                                 if (state.lightCapabilities[light.id] in ["level", "color"]) {
105                                         input "level_${sceneId}_${light.id}", "enum", title: light.displayName, options: levels, description: "", required: false
106                                 }
107                         }
108                 }
109
110                 section("Colors (hue/saturation)") {
111                         lights.each {light ->
112                                 if (state.lightCapabilities[light.id] == "color") {
113                                         input "color_${sceneId}_${light.id}", "text", title: light.displayName, description: "", required: false
114                                 }
115                         }
116                 }
117         }
118 }
119
120 def saveStatesPage(params) {
121         saveStates(params)
122         devicePage(params)
123 }
124
125
126 /*************************
127  * Installation & update *
128  *************************/
129 def installed() {
130         log.debug "Installed with settings: ${settings}"
131
132         initialize()
133 }
134
135 def updated() {
136         log.debug "Updated with settings: ${settings}"
137
138         unsubscribe()
139         initialize()
140 }
141
142 def initialize() {
143         subscribe cube, "threeAxis", positionHandler
144 }
145
146
147 /******************
148  * Event handlers *
149  ******************/
150 def positionHandler(evt) {
151
152         def sceneId = getOrientation(evt.xyzValue)
153         log.trace "orientation: $sceneId"
154
155         if (sceneId != state.lastActiveSceneId) {
156                 restoreStates(sceneId)
157         }
158         else {
159                 log.trace "No status change"
160         }
161         state.lastActiveSceneId = sceneId
162 }
163
164
165 /******************
166  * Helper methods *
167  ******************/
168 private Boolean sceneIsDefined(sceneId) {
169         def tgt = "onoff_${sceneId}".toString()
170         settings.find{it.key.startsWith(tgt)} != null
171 }
172
173 private updateSetting(name, value) {
174         app.updateSetting(name, value)
175         settings[name] = value
176 }
177
178 private closestLevel(level) {
179         level ? "${Math.round(level/5) * 5}%" : "0%"
180 }
181
182 private saveStates(params) {
183         log.trace "saveStates($params)"
184         def sceneId = params.sceneId as Integer
185         getDeviceCapabilities()
186
187         lights.each {light ->
188                 def type = state.lightCapabilities[light.id]
189
190                 updateSetting("onoff_${sceneId}_${light.id}", light.currentValue("switch") == "on")
191
192                 if (type == "level") {
193                         updateSetting("level_${sceneId}_${light.id}", closestLevel(light.currentValue('level')))
194                 }
195                 else if (type == "color") {
196                         updateSetting("level_${sceneId}_${light.id}", closestLevel(light.currentValue('level')))
197                         updateSetting("color_${sceneId}_${light.id}", "${light.currentValue("hue")}/${light.currentValue("saturation")}")
198                 }
199         }
200 }
201
202
203 private restoreStates(sceneId) {
204         log.trace "restoreStates($sceneId)"
205         getDeviceCapabilities()
206
207         lights.each {light ->
208                 def type = state.lightCapabilities[light.id]
209
210                 def isOn = settings."onoff_${sceneId}_${light.id}" == "true" ? true : false
211                 log.debug "${light.displayName} is '$isOn'"
212                 if (isOn) {
213                         light.on()
214                 }
215                 else {
216                         light.off()
217                 }
218
219                 if (type != "switch") {
220                         def level = switchLevel(sceneId, light)
221
222                         if (type == "level") {
223                                 log.debug "${light.displayName} level is '$level'"
224                                 if (level != null) {
225                                         light.setLevel(level)
226                                 }
227                         }
228                         else if (type == "color") {
229                                 def segs = settings."color_${sceneId}_${light.id}"?.split("/")
230                                 if (segs?.size() == 2) {
231                                         def hue = segs[0].toInteger()
232                                         def saturation = segs[1].toInteger()
233                                         log.debug "${light.displayName} color is level: $level, hue: $hue, sat: $saturation"
234                                         if (level != null) {
235                                                 light.setColor(level: level, hue: hue, saturation: saturation)
236                                         }
237                                         else {
238                                                 light.setColor(hue: hue, saturation: saturation)
239                                         }
240                                 }
241                                 else {
242                                         log.debug "${light.displayName} level is '$level'"
243                                         if (level != null) {
244                                                 light.setLevel(level)
245                                         }
246                                 }
247                         }
248                         else {
249                                 log.error "Unknown type '$type'"
250                         }
251                 }
252
253
254         }
255 }
256
257 private switchLevel(sceneId, light) {
258         def percent = settings."level_${sceneId}_${light.id}"
259         if (percent) {
260                 percent[0..-2].toInteger()
261         }
262         else {
263                 null
264         }
265 }
266
267 private getDeviceCapabilities() {
268         def caps = [:]
269         lights.each {
270                 if (it.hasCapability("Color Control")) {
271                         caps[it.id] = "color"
272                 }
273                 else if (it.hasCapability("Switch Level")) {
274                         caps[it.id] = "level"
275                 }
276                 else {
277                         caps[it.id] = "switch"
278                 }
279         }
280         state.lightCapabilities = caps
281 }
282
283 private getLevels() {
284         def levels = []
285         for (int i = 0; i <= 100; i += 5) {
286                 levels << "$i%"
287         }
288         levels
289 }
290
291 private getOrientation(xyz=null) {
292         final threshold = 250
293
294         def value = xyz ?: cube.currentValue("threeAxis")
295
296         def x = Math.abs(value.x) > threshold ? (value.x > 0 ? 1 : -1) : 0
297         def y = Math.abs(value.y) > threshold ? (value.y > 0 ? 1 : -1) : 0
298         def z = Math.abs(value.z) > threshold ? (value.z > 0 ? 1 : -1) : 0
299
300         def orientation = 0
301         if (z > 0) {
302                 if (x == 0 && y == 0) {
303                         orientation = 1
304                 }
305         }
306         else if (z < 0) {
307                 if (x == 0 && y == 0) {
308                         orientation = 2
309                 }
310         }
311         else {
312                 if (x > 0) {
313                         if (y == 0) {
314                                 orientation = 3
315                         }
316                 }
317                 else if (x < 0) {
318                         if (y == 0) {
319                                 orientation = 4
320                         }
321                 }
322                 else {
323                         if (y > 0) {
324                                 orientation = 5
325                         }
326                         else if (y < 0) {
327                                 orientation = 6
328                         }
329                 }
330         }
331
332         orientation
333 }
334
335 private sceneName(num) {
336         final names = ["UNDEFINED","One","Two","Three","Four","Five","Six"]
337         settings."sceneName${num}" ?: "Scene ${names[num]}"
338 }
339
340
341