-
Notifications
You must be signed in to change notification settings - Fork 2
/
Hue-Sync-Box.groovy
581 lines (528 loc) · 20.1 KB
/
Hue-Sync-Box.groovy
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
/*****************************************************************************************************************
* Copyright Daniel Terryn
*
* Name: Driver to communicate with Hue Sync Box....
*
* Date: 2021-03-02
*
* Version: 1.33
*
* Author: Daniel Terryn
*
* Description: A driver to retrieve to control the Hue Sync Box....
*
* License:
* 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:
*
* Date Who What
* ---- --- ----
* 2020-02-07 Daniel Terryn Original Creation
* 2020-02-26 Daniel Terryn Added reboot command, fixed Input 4
* 2020-04-17 Mike Neir Added powersave mode, added mode select for on/off actions, more complete switch state detection
* 2021-02-21 Daniel Terryn added setBrightness
* 2021-03-01 Jason A. Diegmueller Fixed spelling errors preventing Hubitat custom action from working (Itensity vs Intensity)
* 2021-03-02 Jason A. Diegmueller Fixed logging text issue in setBrightness (logged "setIntensity" vs "setBrightness")
* 2021-03-02 Jason A. Diegmueller Doubled value passed to setBrightness, Sync Box was halving the value passed
* 2023_01-19 Tino Added ability to use 2 Entertainment Areas.
*. 2023_01-19 Tino Changed variable names and added attribute for group
*/
metadata {
definition (name: "Hue Sync Box", author: "dan.t", namespace: "dan.t", importUrl: "https://raw.githubusercontent.com/danTapps/Hubitat/master/Drivers/Hue%20Sync%20Box/hue_sync_box.groovy") {
capability "Refresh"
capability "Switch"
capability "Initialize"
capability "Presence Sensor"
command "setMode", [[name:"Set Mode*", type: "ENUM", description: "Set Mode", constraints: ["powersave", "passthrough", "video", "music", "game"] ] ]
command "setInput", [[name:"Set Input*", type: "ENUM", description: "Set Input", constraints: ["input1", "input2", "input3", "input4"] ] ]
command "setIntensity", [[name:"Mode*", type: "ENUM", description: "Mode", constraints: ["video", "music", "game"] ],[name:"Intensity*", type: "ENUM", description: "Intensity", constraints: ["subtle", "moderate", "high", "intense"] ] ]
//command "toggleMode"
command "checkForUpdates"
command "reboot"
command "registerHueSyncBox"
command "setBrightness", ["brightness"]
command "sethueTarget", [[name:"Use Entertainment Area by UUID set below", type: "ENUM", description: "Set Entertainment Area", constraints: ["favGroupOne", "favGroupTwo"] ] ]
attribute "brightness", "number"
attribute "mode", "string"
attribute "hdmiSource", "string"
attribute "lastSyncMode", "string"
attribute "firmwareVersion", "string"
attribute "lastCheckedUpdate", "string"
attribute "updateAvailable", "string"
attribute "intensity", "string"
attribute "hueTarget", "string"
attribute "groups", "string"
}
preferences {
input ( name: "ip", type: "text", title: "HUE Sync Box IP Address", description: "IP Address in form 192.168.1.226", required: true, displayDuringSetup: true )
input ( name: "api_key", type: "text", title: "API Key", required: false, displayDuringSetup: true )
input ( name: "favGroupOne", type: "text", title: "Your First Favorite Entertainment Area UUID", required: false, displayDuringSetup: true )
input ( name: "favGroupTwo", type: "text", title: "Your Second Favorite Entertainment Area UUID", required: false, displayDuringSetup: true )
input ( name: 'pollInterval', type: 'enum', title: 'Update interval (in seconds)', options: ['10', '30', '60', '300'], required: true, displayDuringSetup: true, defaultValue: "60" )
input ( name: 'onActionMode', type: 'enum', title: 'Mode to activate when turned "on"', options: ['passthrough', 'video', 'game', 'music'], required: true, displayDuringSetup: true, defaultValue: "video" )
input ( name: 'offActionMode', type: 'enum', title: 'Mode to activate when turned "off"', options: ['passthrough', 'powersave'], required: true, displayDuringSetup: true, defaultValue: "passthrough" )
input ( name: "configLoggingLevelIDE", title: "IDE Live Logging Level:\nMessages with this level and higher will be logged to the IDE.", type: "enum",
options: [
"0" : "None",
"1" : "Error",
"2" : "Warning",
"3" : "Info",
"4" : "Debug",
"5" : "Trace"
],
defaultValue: "3", displayDuringSetup: true, required: false )
}
}
def installed() {
logger("Executing 'installed()'", "info")
initialize()
}
def initialize() {
logger("Executing 'initialize()'", "debug")
updated()
}
def updated() {
logger("Executing 'updated()'", "debug")
configure()
state.authTryCount = 0
}
def configure() {
logger("Executing 'configure()'", "info")
state.loggingLevelIDE = (settings.configLoggingLevelIDE) ? settings.configLoggingLevelIDE.toInteger() : 3
unschedule()
def pollInt = settings["pollInterval"]?.toInteger()
// If change polling options in UI, may need to modify some of these cases:
switch (pollInt ?: 0) {
case 0:
logger("Polling disabled; not scheduling")
break
case 1..59:
logger("Scheduling polling every ${pollInt} seconds")
schedule("${Math.round(Math.random() * pollInt)}/${pollInt} * * ? * * *", "refresh")
break
case 60..259:
logger("Scheduling polling every 1 minute")
runEvery1Minute("refresh")
break
case 300..1800:
logger("Schedulig polling every 5 minutes")
runEvery5Minutes("refresh")
break
default:
logger("Scheduling polling every hour")
runEvery1Hour("refresh")
}
refresh()
}
def registerHueSyncBox()
{
if (settings.api_key != null) {
log.error "Hue Sync Box is already regsitered, please clear the API key setting to re-register your sync box"
return
}
if (settings.ip == null) {
log.error "Hue Sync Box IP has to be set"
return
}
if (state.authTryCount > 19) {
log.debug "I tried 20 times to register, I quit now. Check your settings."
return
}
log.debug "Running registration, press the power button for 2 seconds on the Hue Sync Box and make sure the TV is on, attempt ${state.authTryCount+1}"
unschedule()
def body = [:]
body.appName = "HueSyncBoxDriver"
body.instanceName = "HueSyncBoxDriver"
body.appSecret = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="
def requestParams =
[
uri: "https://${settings["ip"]}/api/v1/registrations",
contentType: "application/json",
ignoreSSLIssues: true,
body : toJson(body)
]
try{
httpPost(requestParams)
{
response ->
if (response?.status == 200)
{
if (response?.data?.accessToken) {
device.updateSetting("api_key", [value:response?.data?.accessToken, type:"text"])
configure()
}
else {
log.error("Unknown error adding Hue Sync Box ${response?.data}")
runIn(10, "registerHueSyncBox")
state.authTryCount = state.authTryCount + 1
}
}
else
{
log.error "Error in registration Response ${response?.status}"
runIn(10, "registerHueSyncBox")
state.authTryCount = state.authTryCount + 1
}
}
} catch (groovyx.net.http.HttpResponseException hre) {
log.error "Error:${hre.getResponse()?.getData()}"
runIn(10, "registerHueSyncBox")
state.authTryCount = state.authTryCount + 1
} catch (Exception e) {
log.error "Something went wrong when posting: ${e}"
runIn(10, "registerHueSyncBox")
state.authTryCount = state.authTryCount + 1
}
}
private sendUsernameRequest() {
def userDesc = "HueSyncBox"
def body = [:]
body.appName = userDesc
body.instanceName = userDesc
body.appSecret = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="
def requestParams =
[
uri: "https://${settings["syncBoxIP"]}/api/v1/registrations",
contentType: "application/json",
ignoreSSLIssues: true,
body : toJson(body)
]
//asynchttpPost("parseUsernameResponse", requestParams)
log.debug "${requestParams}"
try{
httpPost(requestParams)
{
response ->
if (response?.status == 200)
{
if (response?.data?.accessToken) {
state["accessToken"] = response?.data?.accessToken
state["syncBoxAuthorized"] = true
}
else {
log.error("Unknown error adding Hue Sync Box ${response?.data}")
}
}
else
{
log.error "Error in registration Response ${response?.status}"
}
}
} catch (groovyx.net.http.HttpResponseException hre) {
log.error "Error:${hre.getResponse()?.getData()}"
} catch (Exception e) {
log.error "Something went wrong when posting: ${e}"
}
}
def refresh() {
if (settings.api_key == null) {
log.error "Hue Sync Box is not registered, please register the Hue Sync Box with the registration flow"
return
}
if (settings.ip == null) {
log.error "Hue Sync Box IP is not set, please updated your setting"
return
}
logger("Executing 'refresh()'", "debug")
try{
def data = sendAsyncHttpGet("")
def switchState = "off"
def syncIntensity = ""
if (data?.execution?.mode)
switchState = isHueSyncOnOrOff(data?.execution?.mode)
if (data?.execution?.syncActive == true)
if (data?.execution[data?.execution?.mode]?.intensity)
syncIntensity = data?.execution[data?.execution?.mode]?.intensity
valueChangeEvent("intensity", syncIntensity, "")
valueChangeEvent("switch", switchState, "")
if (data?.execution?.brightness)
valueChangeEvent("brightness", data?.execution?.brightness, "")
if (data?.execution?.hueTarget)
valueChangeEvent("hueTarget", data?.execution?.hueTarget, "")
if (data?.hue?.groups)
valueChangeEvent("groups", data?.hue?.groups, "")
if (data?.execution?.mode)
valueChangeEvent("mode", data?.execution?.mode, "")
if (data?.execution?.hdmiSource)
valueChangeEvent("hdmiSource", data?.execution?.hdmiSource, "")
if (data?.execution?.lastSyncMode)
valueChangeEvent("lastSyncMode", data?.execution?.lastSyncMode, "")
if (data?.device?.firmwareVersion)
valueChangeEvent("firmwareVersion", data?.device?.firmwareVersion, "")
if (data?.device?.lastCheckedUpdate)
valueChangeEvent("lastCheckedUpdate", data?.device?.lastCheckedUpdate, "")
if (data?.device?.updatableFirmwareVersion)
valueChangeEvent("updateAvailable", "true", "")
else
valueChangeEvent("updateAvailable", "false", "")
valueChangeEvent("presence", "present", "")
} catch (Exception e){
logger("refresh() exception ${e}", "error")
valueChangeEvent("presence", "not present", "")
}
}
def toggleMode()
{
try{
def currentMode = state?.data_points["mode"]
setMode(state?.data_points["lastSyncMode"])
valueChangeEvent("lastSyncMode", currentMode, "")
} catch (Exception e){
logger("toggleMode() exception ${e}", "error")
}
}
def checkForUpdates()
{
try{
sendAsyncHttpPut("/device", "{\"action\": \"checkForFirmwareUpdates\" }")
} catch (Exception e){
logger("checkForUpdates() exception ${e}", "error")
}
}
def reboot()
{
runActionCmd("doSoftwareRestart")
}
def setInput(input)
{
logger("Receive \"setInput(\"${input}\")\" command", "info")
try{
sendAsyncHttpPut("/execution", "{\"hdmiSource\":\"${input}\"}")
valueChangeEvent("hdmiSource", input, "")
} catch (Exception e){
logger("setInput() exception ${e}", "error")
}
}
def isHueSyncOnOrOff(mode)
{
def switchState
switch (mode) {
case "powersave":
switchState = "off"
break
case "passthrough":
if (settings.offActionMode == "passthrough")
switchState = "off"
else
switchState = "on"
break
case "game":
switchState = "on"
break
case "music":
switchState = "on"
break
case "video":
switchState = "on"
break
default:
switchState = "off"
}
return switchState;
}
def setMode(mode)
{
logger("Receive \"setMode(\"${mode}\")\" command", "info")
try{
sendAsyncHttpPut("/execution", "{\"mode\": \"${mode}\"}")
valueChangeEvent("mode", mode, "")
if (mode == "passthrough")
valueChangeEvent("intensity", "", "")
valueChangeEvent("switch", isHueSyncOnOrOff(mode), "")
} catch (Exception e){
logger("setMode() exception ${e}", "error")
}
}
def setIntensity(mode, intensity)
{
logger("Receive \"setIntensity(\"${mode}\", \"${intensity}\")\" command", "info")
try{
sendAsyncHttpPut("/execution", "{\"${mode}\":{ \"intensity\": \"${intensity}\"}}")
valueChangeEvent("intensity", intensity, "")
} catch (Exception e){
logger("setIntensity() exception ${e}", "error")
}
}
def setBrightness(brightness)
{
brightness = ( brightness.toInteger() * 2 )
logger("Receive \"setBrightness(\"${brightness}\")\" command", "info")
try{
sendAsyncHttpPut("/execution", "{\"brightness\": ${brightness}}")
valueChangeEvent("brightness", brightness, "")
} catch (Exception e){
logger("setBrightness() exception ${e}", "error")
}
}
def sethueTarget(selTarget)
{
logger("Receive \"hueTarget(\"${selTarget}\")\" command", "info")
log.debug selPreset
try{
if (selTarget == "favGroupOne")
sendAsyncHttpPut("/execution", "{\"hueTarget\": \"${settings.favGroupOne}\"}")
valueChangeEvent("hueTarget", settings.favGroupOne, "")
if (selTarget == "favGroupTwo")
sendAsyncHttpPut("/execution", "{\"hueTarget\": \"${settings.favGroupTwo}\"}")
valueChangeEvent("hueTarget", settings.favGroupTwo, "")
} catch (Exception e){
logger("setPreset() exception ${e}", "error")
}
}
def on() {
logger("Receive \"on()\" command", "info")
try{
setMode(settings.onActionMode)
valueChangeEvent("switch", "on", "")
} catch (Exception e){
logger("on() exception ${e}", "error")
}
}
def off() {
logger("Receive \"off()\" command", "info")
try{
setMode(settings.offActionMode)
valueChangeEvent("switch", "off", "")
} catch (Exception e){
logger("off() exception ${e}", "error")
}
}
def valueChangeEvent(def deviceAttribute, def newValue, def newUnit = "")
{
def success = false
def oldValue = null
if (newValue == null)
return false
if (state?.data_points)
{
if (state?.data_points["${deviceAttribute}"])
{
oldValue = state?.data_points["${deviceAttribute}"]
if (state?.data_points["${deviceAttribute}"] == newValue)
return false
else if (state?.data_points["${deviceAttribute}"].toString().equals(newValue.toString()))
return false
}
}
else
state.data_points = [:]
state.data_points["${deviceAttribute}"] = newValue
logger("Send new ${deviceAttribute} state, old: ${oldValue}, new: ${newValue}", "info")
def descriptionText = "${device.displayName} ${deviceAttribute} is ${newValue}"
sendEvent(name: deviceAttribute, value: newValue, unit: newUnit, descriptionText: descriptionText)
return true;
}
def sendAsyncHttpPut(message, body)
{
def requestParams =
[
uri: "https://${settings.ip}/api/v1"+message,
contentType: "application/json",
headers: ["Authorization": "Bearer ${settings.api_key}"],
timeout: 200,
ignoreSSLIssues: true,
body : body
]
logger("sendAsyncHttpPut: ${requestParams}", "debug")
try{
httpPut(requestParams) //change to httpGet for the get test.
{
response ->
if (response?.status == 200)
{
logger(response.data, "debug")
return response.data
}
else
{
logger("httpPut ${response?.status}", "warn")
}
}
} catch (org.apache.http.conn.HttpHostConnectException e) {
logger("httpPut HttpHostConnectException ${e}", "error")
valueChangeEvent("presence", "not present", "")
} catch (org.apache.http.NoHttpResponseException e) {
logger("httpPut NoHttpResponseException ${e}", "error")
valueChangeEvent("presence", "not present", "")
} catch (Exception e){
logger("httpPut Exception ${e}", "error")
valueChangeEvent("presence", "not present", "")
}
}
def sendAsyncHttpGet(message)
{
def result = null
def requestParams =
[
uri: "https://${settings.ip}/api/v1"+message,
contentType: "application/json",
headers: ["Authorization": "Bearer ${settings.api_key}"],
timeout: 200,
ignoreSSLIssues: true
]
logger("sendAsyncHttpGet: ${requestParams}", "debug")
try{
httpGet(requestParams) //change to httpGet for the get test.
{
response ->
if (response?.status == 200)
{
logger(response.data, "debug")
result = response.data
}
else
{
log.warn "${response?.status}"
}
}
} catch (org.apache.http.conn.HttpHostConnectException e) {
logger("httpGet HttpHostConnectException ${e}", "error")
valueChangeEvent("presence", "not present", "")
} catch (org.apache.http.NoHttpResponseException e) {
logger("httpGet NoHttpResponseException ${e}", "error")
valueChangeEvent("presence", "not present", "")
} catch (Exception e){
logger("httpGet Exception ${e}", "error")
valueChangeEvent("presence", "not present", "")
}
return result
}
/**
* logger()
*
* Wrapper function for all logging.
**/
private logger(msg, level = "debug") {
switch(level) {
case "error":
if (state.loggingLevelIDE >= 1) log.error msg
break
case "warn":
if (state.loggingLevelIDE >= 2) log.warn msg
break
case "info":
if (state.loggingLevelIDE >= 3) log.info msg
break
case "debug":
if (state.loggingLevelIDE >= 4) log.debug msg
break
case "trace":
if (state.loggingLevelIDE >= 5) log.trace msg
break
default:
log.debug msg
break
}
}
def toJson(Map m)
{
return new groovy.json.JsonBuilder(m).toString()
}