-
Notifications
You must be signed in to change notification settings - Fork 5
/
myLevitonSwitchDimmer
362 lines (303 loc) · 10.4 KB
/
myLevitonSwitchDimmer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*
Copyright 2020 - tomw
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------
Change history:
1.3.0 - dsegall - added support for detecting when a switch disconnects from MyLeviton
1.2.1 - dsegall - bugfix for canSetLevel issue
1.2.0 - tomw + dsegall - Update device statuses from websocket events. No more polling.
1.1.0 - dsegall - Added fadeTo feature and custom command. Added support for duration parameter on setLevel command.
1.0.0 - tomw - Initial release
*/
metadata
{
definition(name: "My Leviton Switch/Dimmer", namespace: "tomw", author: "tomw", importUrl: "")
{
capability "Refresh"
capability "SignalStrength"
capability "Switch"
capability "SwitchLevel"
attribute "commStatus", "string"
attribute "connected", "enum", ["true", "false"]
attribute "fadeOnTime", "number"
attribute "fadeOffTime", "number"
attribute "canSetLevel", "boolean"
command "fadeTo", [[name: "Level", type: "NUMBER"], [name: "In seconds", type: "NUMBER"]]
}
}
preferences
{
section
{
input name: "switch_id", type: "text", title: "Switch ID", required: true
input name: "suppressDupReq", type: "bool", title: "Attempt to suppress duplicate update requests?", defaultValue: false
input name: "logEnable", type: "bool", title: "Enable debug logging", defaultValue: true
}
}
def logDebug(msg)
{
if (logEnable)
{
log.debug(msg)
}
}
def refresh()
{
requestRefresh()
}
def on()
{
lev_update_switch('ON')
}
def off()
{
lev_update_switch('OFF')
}
def setLevel(level)
{
setLevel(level, 0)
}
def setLevel(level, duration)
{
fadeTo(level, duration)
}
def fadeTo(level, duration) {
if (device.currentValue("canSetLevel")?.toBoolean()) {
def currFadeOnTime = device.currentValue("fadeOnTime").toInteger()
def currFadeOffTime = device.currentValue("fadeOffTime").toInteger()
def state = (level == 0 ? 'OFF' : 'ON')
try {
httpExecWithAuthCheck("PUT", genParamsMain("IotSwitches/${switch_id}", [fadeOnTime: duration * 10, fadeOffTime: duration * 10]), true, "fadeStart", [state: state, level: level, currFadeOnTime: currFadeOnTime, currFadeOffTime: currFadeOffTime, duration: duration])
}
catch (Exception e) {
logDebug("fadeTo failed: ${e.message}")
sendEvent(name: "commStatus", value: "error")
}
}
}
def fadeStart(response, data) {
logDebug("fadeStart with status = ${response.getStatus()} from data = ${data}")
if(!response.hasError())
{
updateAttributes(switch_id, response.getJson(), false)
try {
httpExecWithAuthCheck("PUT", genParamsMain("IotSwitches/${switch_id}", data.level == 0 ? [power: data.state] : [power: data.state, brightness: data.level]), true, "fadeDone", data)
}
catch (Exception e) {
logDebug("fadeTo failed: ${e.message}")
sendEvent(name: "commStatus", value: "error")
}
}
}
def fadeDone(response, data) {
logDebug("fadeDone with status = ${response.getStatus()} from data = ${data}")
if(!response.hasError())
{
updateAttributes(switch_id, response.getJson(), false)
def seconds = data.duration.toInteger() * 2
logDebug("Scheduling restoreFadeTime for ${seconds}s with data=${data}")
runIn(seconds, "restoreFadeTime", [data: data])
}
}
def restoreFadeTime(data) {
try {
logDebug("restoreFadeTime with data=${data}")
httpExecWithAuthCheck("PUT", genParamsMain("IotSwitches/${switch_id}", [fadeOnTime: data.currFadeOnTime, fadeOffTime: data.currFadeOffTime]), true)
}
catch (Exception e) {
logDebug("fadeTo failed: ${e.message}")
sendEvent(name: "commStatus", value: "error")
}
}
def lev_update_switch(power, brightness = null)
{
try
{
// only adjust if current values are different than requested values, or if driver option is disabled
if((!suppressDupReq || null == suppressDupReq) || (power == 'ON' ? "on" : "off") != (device.currentValue("switch")) || (brightness != device.currentValue("level")) )
{
httpExecWithAuthCheck("PUT", genParamsMain("IotSwitches/${switch_id}", !brightness ? [power: power] : [power: power, brightness: brightness]), true)
sendEvent(name: "commStatus", value: "good")
}
}
catch (Exception e)
{
logDebug("lev_update_switch failed: ${e.message}")
sendEvent(name: "commStatus", value: "error")
}
return
}
def updateAttributes(id, switchData, fromWebsocket = true, fullRefresh = false)
{
if (fromWebsocket) {
def enabled = device.getDataValue("websocketProcessing")
if (enabled != null && !enabled.toBoolean())
return
}
if(id.toString() != switch_id)
{
device.updateSetting("switch_id", id.toString())
}
def power = switchData.power
def brightness = switchData.brightness
def rssi = switchData.rssi
def fadeOnTime = switchData.fadeOnTime
def fadeOffTime = switchData.fadeOffTime
def canSetLevel = switchData.canSetLevel == null ? null : switchData.canSetLevel.toBoolean()
String connected = switchData.connected
// physical updates always have a single message, with updates to power and/or brightness and chgReason == 1
// digital updates have two messages -- first one with power and/or brightness but no chgReason and then one with chgReason == 3
// ...so, if we're going to update either power or brightness, we only need to check whether chgReason == 1 to know which type
// ...and when we don't know whether a change was physical or digital based on this logic,
// we just assume physical (presumably adjusted outside of Hubitat)
def isPhysical = fullRefresh ? true : (null != switchData.chgReason) ? (1 == switchData.chgReason) : false
if(null != power) { sendEvent(name: "switch", value: (power == 'ON') ? "on" : "off", type: (isPhysical ? "physical" : "digital")) }
if(null != brightness) { sendEvent(name: "level", value: brightness, type: (isPhysical ? "physical" : "digital")) }
if(null != rssi) { sendEvent(name: "rssi", value: rssi.toInteger()) }
if(null != canSetLevel) { sendEvent(name: "canSetLevel", value: canSetLevel) }
if (null != fadeOnTime) {
sendEvent(name: "fadeOnTime", value: fadeOnTime.toInteger())
}
else if (canSetLevel) {
sendEvent(name: "fadeOnTime", value: 0)
}
if (null != fadeOffTime) {
sendEvent(name: "fadeOffTime", value: fadeOffTime.toInteger())
}
else if (canSetLevel) {
sendEvent(name: "fadeOffTime", value: 0)
}
sendEvent(name: "connected", value: connected)
}
def requestRefresh()
{
parent.refreshFromChild()
}
def checkCommStatus()
{
switch(device.currentValue("commStatus"))
{
case "good":
logDebug("checkCommStatus() success")
return true
case "error":
case "unknown":
default:
logDebug("checkCommStatus() failed")
return false
}
}
def getBaseURI()
{
return "https://my.leviton.com/api/"
}
def genParamsMain(suffix, body = null)
{
def params =
[
uri: getBaseURI() + suffix,
headers:
[
'Authorization': parent.getAuth()
],
contentType: 'application/json',
]
if(body)
{
params['body'] = body
}
return params
}
def httpPutExec(params, throwToCaller = false, callback = "httpAsyncCallback", callbackData = null)
{
logDebug("httpPutExec(${params})")
try
{
asynchttpPut(callback, params, callbackData)
}
catch (Exception e)
{
logDebug("httpPutExec() failed: ${e.message}")
if(throwToCaller)
{
throw(e)
}
}
}
def httpAsyncCallback(response, data)
{
logDebug("httpAsyncCallback with status = ${response.getStatus()} from data = ${data}")
try {
if(!response.hasError())
{
def respData = response.getJson()
logDebug("respData = ${respData}")
updateAttributes(switch_id, respData, false)
}
}
finally {
device.removeDataValue("websocketProcessing")
}
}
def httpExec(operation, params, throwToCaller = false, callback = "httpAsyncCallback", callbackData = null)
{
def res
switch(operation)
{
default:
logDebug("unsupported Http operation")
break
case "PUT":
res = httpPutExec(params, throwToCaller, callback, callbackData)
break
}
return res
}
def httpExecWithAuthCheck(operation, params, throwToCaller = false, callback = "httpAsyncCallback", callbackData = null)
{
def res
try
{
res = httpExec(operation, params, true, callback, callbackData)
return res
}
catch (Exception e)
{
if(e.getResponse().getStatus().toInteger() == 401)
{
// 401 Unauthorized
try
{
logDebug("httpExecWithAuthCheck() auth failed. retrying...")
parent.refreshTokens()
// update with new Auth token
params['headers']['Authorization'] = parent.getAuth()
res = httpExec(operation, params, true)
return res
}
catch (Exception e2)
{
logDebug("httpExecWithAuthCheck() failed: ${e2.message}")
if(throwToCaller)
{
throw(e2)
}
}
}
else
{
if(throwToCaller)
{
throw(e)
}
}
}
}