-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathhue-bridge-integration.groovy
2702 lines (2294 loc) · 92.7 KB
/
hue-bridge-integration.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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Advanced Philips Hue Bridge Integration application
* Version 1.6.0
* Download: https://github.com/apwelsh/hubitat
* Description:
* This is a parent application for locating your Philips Hue Bridges, and installing
* the Advanced Hue Bridge Controller application
*-------------------------------------------------------------------------------------------------------------------
* Copyright 2020 Armand Peter Welsh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the 'Software'), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*-------------------------------------------------------------------------------------------------------------------
**/
import groovy.transform.Field
import java.util.concurrent.ConcurrentHashMap
import java.math.RoundingMode
import hubitat.helper.ColorUtils
import groovy.json.JsonOutput
definition(
name:'Advanced Hue Bridge Integration',
namespace: 'apwelsh',
author: 'Armand Welsh',
description: 'Find and install your Philips Hue Bridge systems',
category: 'Convenience',
//importUrl: 'https://raw.githubusercontent.com/apwelsh/hubitat/master/hue/app/hue-bridge-integration.groovy', // Commented out because the import URL is not needed for this version
iconUrl: '',
iconX2Url: '',
iconX3Url: ''
)
@Field static final Integer PAGE_REFRESH_TIMEOUT = 10
@Field static final String PAGE_MAINPAGE = 'mainPage'
@Field static final String PAGE_BRIDGE_DISCOVERY = 'bridgeDiscovery'
@Field static final String PAGE_ADD_DEVICE = 'addDevice'
@Field static final String PAGE_BRIDGE_LINKING = 'bridgeLinking'
@Field static final String PAGE_UNLINK = 'unlink'
@Field static final String PAGE_FIND_LIGHTS = 'findLights'
@Field static final String PAGE_ADD_LIGHTS = 'addLights'
@Field static final String PAGE_FIND_GROUPS = 'findGroups'
@Field static final String PAGE_ADD_GROUPS = 'addGroups'
@Field static final String PAGE_FIND_SCENES = 'findScenes'
@Field static final String PAGE_ADD_SCENES = 'addScenes'
@Field static final String PAGE_FIND_SENSORS = 'findSensors'
@Field static final String PAGE_ADD_SENSORS = 'addSensors'
@Field static Map atomicStateByDeviceId = new ConcurrentHashMap()
@Field static Map atomicQueueByDeviceId = new ConcurrentHashMap()
@Field static Map refreshQueue = new ConcurrentHashMap()
preferences {
page(name: PAGE_MAINPAGE)
page(name: PAGE_BRIDGE_DISCOVERY, title: 'Device Discovery', refreshTimeout:PAGE_REFRESH_TIMEOUT)
page(name: PAGE_ADD_DEVICE, title: 'Add Hue Bridge')
page(name: PAGE_UNLINK, title: 'Unlink your Hue')
page(name: PAGE_BRIDGE_LINKING, title: 'Linking with your Hue', refreshTimeout:5)
page(name: PAGE_FIND_LIGHTS, title: 'Light Discovery Started!', refreshTimeout:PAGE_REFRESH_TIMEOUT)
page(name: PAGE_ADD_LIGHTS, title: 'Add Light')
page(name: PAGE_FIND_GROUPS, title: 'Group Discovery Started!', refreshTimeout:PAGE_REFRESH_TIMEOUT)
page(name: PAGE_ADD_GROUPS, title: 'Add Group')
page(name: PAGE_FIND_SCENES, title: 'Scene Discovery Started!', refreshTimeout:PAGE_REFRESH_TIMEOUT)
page(name: PAGE_ADD_SCENES, title: 'Add Scene')
page(name: PAGE_FIND_SENSORS, title: 'Sensor Discovery Started!', refreshTimeout:PAGE_REFRESH_TIMEOUT)
page(name: PAGE_ADD_SENSORS, title: 'Add Sensor')
}
synchronized Map getAtomicState(def device) {
Integer deviceId = device.deviceId ?: device.device.deviceId
Map result = atomicStateByDeviceId.get(deviceId)
if (result == null) {
result = new ConcurrentHashMap()
atomicStateByDeviceId[deviceId] = result
}
return result
}
synchronized Map getAtomicQueue(def device) {
Integer deviceId = device.deviceId ?: device.device.deviceId
Map result = atomicQueueByDeviceId.get(deviceId)
if (result == null) {
result = new ConcurrentHashMap()
atomicQueueByDeviceId[deviceId] = result
}
return result
}
synchronized Map getRefreshQueue() {
Integer appId = app.getId()
Map result = refreshQueue.get(appId)
if (result == null) {
result = new ConcurrentHashMap()
refreshQueue[appId] = result
}
return result
}
public String getBridgeHost() {
if (!settings.bridgeHost) {
if (state.bridgeHost) {
setBridgeHost(state.bridgeHost)
state.remove('bridgeHost')
} else {
return null;
}
}
String host = settings.bridgeHost
if (host?.endsWith(':80')) {
host = "${host.substring(0,host.size()-3)}:443"
setBridgeHost(host)
}
return host
}
public void setBridgeHost(String host) {
if (!host) {
app.removeSetting('bridgeHost')
return
} else {
if (host?.endsWith(':80')) {
host = "${host.substring(0,host.size()-3)}:443"
}
app.updateSetting("bridgeHost", [type: "text", value: host])
}
}
def mainPage(Map params=[:]) {
if (app.installationState == 'INCOMPLETE') {
return dynamicPage(name: PAGE_MAINPAGE, title: '', nextPage: null, uninstall: true, install: true) {
section (getFormat("title", "Advanced Hue Bridge")) {
paragraph getFormat("subtitle", "Installing new Hue Bridge Integration")
paragraph getFormat("line")
paragraph 'Click the Done button to install the Hue Bridge Integration.'
paragraph 'Re-open the app to setup your device'
}
}
}
if (!selectedDevice) {
return bridgeDiscovery()
}
if (params.nextPage==PAGE_BRIDGE_LINKING) {
return bridgeLinking()
}
String title
if (selectedDevice) {
discoveredHubs()[selectedDevice]
title=discoveredHubs()[selectedDevice]
if (!getHubForMac(selectedDevice)) {
ssdpSubscribe()
ssdpDiscover()
} else {
ssdpUnsubscribe()
}
} else {
title='Find Bridge'
}
Boolean uninstall = getBridgeHost() ? false : true
return dynamicPage(name: PAGE_MAINPAGE, title: '', nextPage: null, uninstall: uninstall, install: true) {
section (getFormat("title", "Advanced Hue Bridge")) {
paragraph getFormat("subtitle", "Manage your linked Hue Bridge")
paragraph getFormat("line")
}
if (selectedDevice == null) {
section('Setup'){
paragraph 'To begin, select Find Bridge to start searching for your Hue Bride.'
href PAGE_BRIDGE_DISCOVERY, title:'Find Bridge', description:''//, params: [pbutton: i]
}
} else {
section('Configure'){
href PAGE_FIND_LIGHTS, title:'Find Lights', description:''
href PAGE_FIND_GROUPS, title:'Find Groups', description:''
href PAGE_FIND_SCENES, title:'Find Scenes', description:''
href PAGE_FIND_SENSORS, title:'Find Sensors', description:''
href selectedDevice ? PAGE_BRIDGE_LINKING : PAGE_BRIDGE_DISCOVERY, title:title, description:'', state:selectedDevice? 'complete' : null //, params: [nextPage: PAGE_BRIDGE_LINKING]
}
section('Options') {
input name: 'logEnable', type: 'bool', defaultValue: true, title: 'Enable informational logging'
input name: 'dbgEnable', type: 'bool', defaultValue: false, title: 'Enable debug logging'
input name: 'newEnable', type: 'bool', defaultValue: false, title: 'Enable detection, and logging of new device types'
input name: 'autorename', type: 'bool', defaultValue: false, title: 'Automatically track, and rename installed devices to match Hue defined names'
href PAGE_UNLINK, title: 'Unlink hub', description:'Use this to unlink your hub and force a new hub link'
}
section() {
paragraph getFormat("line")
paragraph '''<div style='color:#1A77C9;text-align:center'>Advanced Hue Bridge
|
|<a href='https://www.paypal.com/donate?hosted_button_id=XZXSPZWAABU8J' target='_blank'><img src='https://img.shields.io/badge/donate-PayPal-blue.svg?logo=paypal&style=plastic' border='0' alt='Donate'></a>
|
|Please consider donating. This app took a lot of work to make.
|Any donations received will be used to purchase additional Hue products to further the development of new device support
|</div>'''.stripMargin()
}
}
}
}
def getFormat(type, myText="") { // Borrowed from @dcmeglio HPM code
if(type == "line") return "<hr style='background-color:#1A77C9; height: 1px; border: 0;'>"
if(type == "title") return "<h2 style='color:#1A77C9;font-weight: bold'>${myText}</h2>"
if(type == "subtitle") return "<h3 style='color:#1A77C9;font-weight: normal'>${myText}</h3>"
}
@Field static final Integer DEVICE_REFRESH_DISCOVER_INTERVAL = 3
@Field static final Integer DEVICE_REFRESH_MAX_COUNT = 30
def bridgeDiscovery(Map params=[:]) {
if (selectedDevice) {
}
if (logEnable) { log.debug 'Searching for Hub additions and updates' }
Map hubs = discoveredHubs() // pull app state for known hubs
Integer deviceRefreshCount = Integer.valueOf(state.deviceRefreshCount ?: 0)
state.deviceRefreshCount = deviceRefreshCount + 1
Integer refreshInterval = PAGE_REFRESH_TIMEOUT
Map options = hubs ?: [:]
Integer numFound = options.size()
if (!options && state.deviceRefreshCount > DEVICE_REFRESH_MAX_COUNT) {
/* groovylint-disable-next-line DuplicateNumberLiteral */
state.deviceRefreshCount = 0
ssdpSubscribe()
}
//bridge discovery request every 5th refresh, retry discovery
if (!(deviceRefreshCount % DEVICE_REFRESH_DISCOVER_INTERVAL)) {
ssdpDiscover()
}
Boolean uninstall = getBridgeHost() ? false : true
String nextPage = selectedDevice ? PAGE_BRIDGE_LINKING : null
return dynamicPage(name:PAGE_BRIDGE_DISCOVERY, title:'Discovery Started!', nextPage:nextPage, refreshInterval:refreshInterval, uninstall:uninstall) {
section('Please wait while we discover your Hue Bridge. Note that you must first configure your Hue Bridge and Lights using the Philips Hue application. Discovery can take five minutes or more, so sit back and relax, the page will reload automatically! Select your Hue Bridge below once discovered.') {
input 'selectedDevice', 'enum', required:false, title:"Select Hue Bridge (${numFound} found)", multiple:false, options:options, submitOnChange: true
}
}
}
def unlink() {
state.remove('hub')
state.remove('username')
state.remove('clientkey')
app.removeSetting('bridgeHost')
if (selectedDevice) {
def hub = getHubForMac(selectedDevice)
hub.remove('username')
hub.remove('clientkey')
}
selectedDevice = ''
return dynamicPage(name:PAGE_UNLINK, title:'Unlink bridge', nextPage:null, uninstall: false) {
section('') {
paragraph "Your hub has been unlinked. Use hub linking to re-link your hub."
}
}
}
def bridgeLinking() {
String nextPage = ''
String title = 'Linking with your Hue'
Integer refreshInterval = 2
String paragraphText
// If bridge IP is undefined, wait for IP discovery before starting linking.
if (selectedDevice && !getBridgeHost()) {
ssdpSubscribeUpdate()
ssdpDiscover()
paragraphText = 'Looking for hub on network.'
} else {
ssdpUnsubscribe() // force-stop all SSDP discovery, to reduce network chatter
/* groovylint-disable-next-line DuplicateNumberLiteral */
Integer linkRefreshcount = state.linkRefreshcount ?: 0
state.linkRefreshcount = linkRefreshcount + 1
if (selectedDevice) {
paragraphText = 'Press the button on your Hue Bridge to setup a link. '
def hub = getHubForMac(selectedDevice)
if (hub?.username && hub?.clientkey) { //if discovery worked
if (logEnable) { log.debug "Hub linking completed for ${hub.name}" }
return addDevice(hub)
}
if (hub?.networkAddress) {
setBridgeHost(hub.networkAddress)
}
if (hub) {
if((linkRefreshcount % 2) == 0 && (!state.username || !state.clientkey)) {
requestHubAccess(selectedDevice)
}
}
} else {
paragraphText = 'You haven\'t selected a Hue Bridge, please Press \'Done\' and select one before clicking next.'
}
}
def uninstall = getBridgeHost() ? false : true
return dynamicPage(name:PAGE_BRIDGE_LINKING, title:title, nextPage:nextPage, refreshInterval:refreshInterval, uninstall: uninstall) {
section('') {
paragraph "${paragraphText}"
}
}
}
def addDevice(device) {
String sectionText = 'Linking to your hub was a success! Please click \'Next\'!\r\n'
String title = 'Success'
String dni = deviceNetworkId(device?.mac)
if (logEnable) { log.info "Adding Bridge device with DNI: ${dni}" }
def d
if (device) {
d = childDevices?.find { dev -> dev.deviceNetworkId == dni }
setBridgeHost("${device.networkAddress}:${device.deviceAddress}")
state.username = "${device.username}"
state.clientkey = "${device.clientkey}"
refreshHubStatus()
}
if (!d && device != null) {
if (logEnable) { log.debug "Creating Hue Bridge device with dni: ${dni}" }
try {
addChildDevice('apwelsh', 'AdvancedHueBridge', dni, null, ['label': device.name])
} catch (ex) {
if (ex.message =~ 'A device with the same device network ID exists.*') {
sectionText = 'Cannot add hub. A device with the same device network ID already exists.'
title = 'Problem detected'
app.removeSetting('bridgeHost')
}
}
}
return dynamicPage(name:PAGE_ADD_DEVICE, title:title, nextPage:PAGE_MAINPAGE) {
section() {
paragraph sectionText
}
}
}
def findLights() {
enumerateLights()
enumerateDevices()
enumerateLightsV2()
List installed = getInstalledLights().collect { it.label ?: it.name }
List dnilist = getInstalledLights().collect { it.deviceNetworkId }
// TODO:
Map options = [:]
Map lights = state.lights
if (lights) {
lights.each {key, value ->
// def lights = value.lights ?: []
// if ( lights.size() == 0 ) { return }
if ( dnilist.find { dni -> dni == networkIdForLight(key) }) { return }
options["${key}"] = "${value.name} (${value.type})"
}
}
Integer numFound = options.size()
Integer refreshInterval = numFound == 0 ? 30 : 120
String nextPage = selectedLights ? PAGE_ADD_LIGHTS : null
return dynamicPage(name:PAGE_FIND_LIGHTS, title:'Light Discovery Started!', nextPage:nextPage, refreshInterval:refreshInterval) {
section('Let\'s find some lights.') {
input 'selectedLights', 'enum', required:false, title:"Select additional lights to add (${numFound} available)", multiple:true, options:options, submitOnChange: true
}
if (selectedLights) {
section {
paragraph "Click the Next button to add the selected light${selectedLights.size() > 1 ? 's' : ''} to your Hubitat hub."
}
} else if (installed) {
section('Installed lights') {
installedLights.each { child -> buttonLink child }
}
}
}
}
def addLights(Map params=[:]) {
if (!selectedLights) {
return findLights()
}
String subject = selectedLights.size == 1 ? 'Light' : 'Lights'
String title = ''
String sectionText = ''
List lights = selectedLights.collect { it }
selectedLights.each { lightId ->
String name = state.lights[lightId].name
String dni = networkIdForLight(lightId)
String type = bulbTypeForLight(lightId)
try {
def child = addChildDevice('hubitat', "Generic Component ${type}", "${dni}",
[label: "${name}", isComponent: false, name: 'AdvancedHueBulb'])
child.updateSetting('txtEnable', false)
lights.remove(lightId)
child.refresh()
} catch (ex) {
if (ex.message =~ 'A device with the same device network ID exists.*') {
sectionText += "\nA device with the same device network ID (${dni}) already exists; cannot add Light [${name}]"
} else {
sectionText += "\nFailed to add light [${name}]; see logs for details"
log.error "${ex}"
}
}
if (lights.size() == 0) {
app.removeSetting('selectedLights')
}
if (!sectionText) {
title = "Adding ${subject} to Hubitat"
sectionText = "Added ${subject}"
} else {
title = "Failed to add ${subject}"
}
return dynamicPage(name:PAGE_ADD_LIGHTS, title:title, nextPage:null) {
section() {
paragraph sectionText
}
}
}
}
def findGroups(params){
enumerateGroups()
enumerateDevices()
enumerateGroupsV2()
def installed = getInstalledGroups().collect { it.label ?: it.name }
def dnilist = getInstalledGroups().collect { it.deviceNetworkId }
Map options = [:]
def groups = state.groups
if (groups) {
groups.each {key, value ->
List lights = value.lights ?: []
if ( !lights ) { return }
if ( dnilist.find { dni -> dni == networkIdForGroup(key) }) { return }
options["${key}"] = "${value.name} (${value.type})"
}
}
def numFound = options.size()
def refreshInterval = numFound == 0 ? 30 : 120
def nextPage = selectedGroups ? PAGE_ADD_GROUPS : null
return dynamicPage(name:PAGE_FIND_GROUPS, title:'Group Discovery Started!', nextPage:nextPage, refreshInterval:refreshInterval) {
section('Let\'s find some groups.') {
input 'selectedGroups', 'enum', required:false, title:"Select additional rooms / zones to add (${numFound} available)", multiple:true, options:options, submitOnChange: true
}
if (selectedGroups) {
section {
paragraph "Click the Next button to add the selected group${selectedGroups.size() > 1 ? 's' : ''} to your Hubitat hub."
}
} else if (installed) {
section('Installed groups') {
installedGroups.each { child -> buttonLink child }
}
}
}
}
def addGroups(params){
if (!selectedGroups) { return findGroups() }
def subject = selectedGroups.size == 1 ? 'Group' : 'Groups'
def title = ''
def sectionText = ''
def groups = selectedGroups.collect { it }
selectedGroups.each { groupId ->
String name = state.groups[groupId].name
String dni = networkIdForGroup(groupId)
try {
def child = addChildDevice('apwelsh', 'AdvancedHueGroup', dni, null, ['label': "${name}"])
groups.remove(groupId)
child.refresh()
} catch (ex) {
if (ex.message =~ 'A device with the same device network ID exists.*') {
sectionText = "\nA device with the same device network ID (${dni}) already exists; cannot add Group [${name}]"
} else {
sectionText += "\nFailed to add group [${name}]; see logs for details"
log.error "${ex}"
}
}
}
if (groups.size() == 0) { app.removeSetting('selectedGroups') }
if (!sectionText) {
title = "Adding ${subject} to Hubitat"
sectionText = 'Added Groups'
} else {
title = 'Failed to add Group'
}
return dynamicPage(name:PAGE_ADD_GROUPS, title:title, nextPage:null) {
section() {
paragraph sectionText
}
}
}
Map scenesForGroupId(groupNetworkId) {
def groupId = deviceIdNode(groupNetworkId)
state.scenes?.findAll { it.value.type == 'GroupScene' && it.value.group == groupId }
}
def findScenes(params){
enumerateScenes()
enumerateDevices()
// enumerateScenesV2()
Map groupOptions = [:]
getInstalledGroups().each { groupOptions[deviceIdNode(it.deviceNetworkId)] = it.label ?: it.name }
Map options = [:]
Map scenes
def group
List installed
List dnilist
if (selectedGroup) {
group = getChildDevice(networkIdForGroup(selectedGroup))
if (group) {
installed = group.getChildDevices()?.collect { it.label ?: it.name }
dnilist = group.getChildDevices()?.collect { it.deviceNetworkId }
}
scenes = scenesForGroupId(selectedGroup)
}
if (scenes) {
scenes.each {key, value ->
def groupName = groupOptions."${selectedGroup}"
def lights = value.lights ?: []
if ( lights.size() == 0 ) { return }
if ( dnilist.find { dni -> dni == networkIdForScene(selectedGroup, key) } ) { return }
options["${key}"] = "${value.name} (${value.type} [${groupName}])"
}
}
def numFound = options.size()
def refreshInterval = numFound == 0 ? 30 : 120
def nextPage = selectedGroup && selectedScenes ? PAGE_ADD_SCENES : null
return dynamicPage(name:PAGE_FIND_SCENES, title:'Scene Discovery Started!', nextPage:nextPage, refreshInterval:refreshInterval) {
section('Let\'s find some scenes. Please click the \'Refresh Scene Discovery\' Button if you aren\'t seeing your Scenes.') {
input 'selectedGroup', 'enum', required:true, title:"Select the group to add scenes to (${groupOptions.size()} installed)", multiple:false, options:groupOptions, submitOnChange: true
if (selectedGroup) {
input 'selectedScenes', 'enum', required:false, title:"Select additional scenes to add (${numFound} available)", multiple:true, options:options, submitOnChange: true
}
}
if (selectedScenes) {
section {
paragraph "Click the Next button to add the selected Scene${selectedScenes.size() > 1 ? 's' : ''} to your Hubitat hub."
}
} else if (installed && selectedGroup) {
section('Installed scenes') {
group.getChildDevices().each { child -> buttonLink child }
}
}
}
}
def addScenes(params){
if (!selectedScenes) { return findScenes() }
def group = getChildDevice(networkIdForGroup(selectedGroup))
def subject = selectedScenes.size == 1 ? 'Scene' : 'Scenes'
def title = ''
def sectionText = ''
def scenes = selectedScenes.collect { it }
selectedScenes.each { sceneId ->
String name = "${group.label ?: group.name} - ${state.scenes[sceneId].name}"
String dni = networkIdForScene(selectedGroup, sceneId)
try {
def child = group.addChildDevice('hubitat', 'Generic Component Switch', "${dni}",
[label: "${name}", isComponent: false, name: 'AdvancedHueScene'])
child.updateSetting('txtEnable', false)
scenes.remove(sceneId)
child.refresh()
} catch (ex) {
if (ex.message =~ 'A device with the same device network ID exists.*') {
sectionText = "\nA device with the same device network ID (${dni}) already exists; cannot add Scene [${name}]"
} else {
sectionText += "\nFailed to add scene [${name}]; see logs for details"
log.error "${ex}"
}
}
}
if (scenes.size() == 0) { app.removeSetting('selectedScenes') }
if (!sectionText) {
title = "Adding ${subject} to Hubitat"
sectionText = 'Added Scenes'
} else {
title = 'Failed to add Scene'
}
return dynamicPage(name:PAGE_ADD_SCENES, title:title, nextPage:null) {
section() {
paragraph sectionText
}
}
}
def findSensors(){
enumerateSensors()
enumerateDevices()
List installed = getInstalledSensors().collect { it.label ?: it.name }
List dnilist = getInstalledSensors().collect { it.deviceNetworkId }
// TODO:
Map options = [:]
Map sensors = state.sensors
if (sensors) {
sensors.each {key, value ->
// def sensors = value.sensors ?: []
// if ( sensors.size() == 0 ) { return }
if ( dnilist.find { dni -> dni == networkIdForSensor(key) }) { return }
options["${key}"] = "${value.name} (${value.productname})"
}
}
Integer numFound = options.size()
Integer refreshInterval = numFound == 0 ? 30 : 120
String nextPage = selectedSensors ? PAGE_ADD_SENSORS : null
return dynamicPage(name:PAGE_FIND_SENSORS, title:'Sensor Discovery Started!', nextPage:nextPage, refreshInterval:refreshInterval) {
section('Let\'s find some sensors.') {
input 'selectedSensors', 'enum', required:false, title:"Select additional sensors to add (${numFound} available)", multiple:true, options:options, submitOnChange: true
}
if (selectedSensors) {
section {
paragraph "Click the Next button to add the selected sensor${selectedSensors.size() > 1 ? 's' : ''} to your Hubitat hub."
}
} else if (!installed.isEmpty()) {
section('Installed sensors') {
installedSensors.each { child -> buttonLink child }
}
}
}
}
private buttonLink(child) {
Map map = stateForNetworkId(child.device.deviceNetworkId)
Boolean ena = map?.config?.on ?: map?.state?.reachable
paragraph """<button type="button" class="btn btn-default btn-lg btn-block hrefElem ${ena ? 'btn-state-complete' : '' } mdl-button--raised mdl-shadow--2dp" style="text-align:left;width:100%" onclick="window.location.href='/device/edit/${child.device.id}'">
<span style="text-align:left;white-space:pre-wrap">${child.label ?: child.name} (${child.name})</span>
</button>"""
}
def addSensors(Map params=[:]){
if (!selectedSensors) {
return findSensors()
}
String subject = selectedSensors.size == 1 ? 'Sensor' : 'Sensors'
String title = ''
String sectionText = ''
List sensors = selectedSensors.collect { it }
selectedSensors.each { sensorId ->
String name = state.sensors[sensorId].name
String dni = networkIdForSensor(sensorId)
String type = driverTypeForSensor(sensorId)
String model = state.sensors[sensorId].productname ?: "Advanced Hue ${type} Sensor"
if (!type) {
sectionText = "\nCannot install sensor ${name}; a compatible driver is not available.\n"
sectionText += "\nTo request support for the sensor, open a support ticket on GitHub, and include the following device details:\n\n${state.sensors[sensorId]}"
log.error "Failed to add sensor [${name}]; not supported"
} else {
try {
def child = addChildDevice('apwelsh', "AdvancedHue${type}Sensor", "${dni}",
[label: "${name}", isComponent: false, name: "${model}"])
sensors.remove(sensorId)
child.refresh()
} catch (ex) {
if (ex.message =~ 'A device with the same device network ID exists.*') {
sectionText = "\nA device with the same device network ID (${dni}) already exists; cannot add sensor [${name}]"
} else {
sectionText += "\nFailed to add sensor [${name}]; see logs for details"
log.error "${ex}"
}
}
}
}
if (sensors.size() == 0) {
app.removeSetting('selectedSensors')
}
if (!sectionText) {
title = "Adding ${subject} to Hubitat"
sectionText = "Added ${subject}"
} else {
title = "Failed to add ${subject}"
}
return dynamicPage(name:PAGE_ADD_SENSORS, title:title, nextPage:null) {
section() {
paragraph sectionText
}
}
}
// Life Cycle Functions
def installed() {
app.updateSetting('logEnable', true)
app.updateSetting('dbgEnable', false)
ssdpSubscribe()
ssdpDiscover()
}
def uninstalled() {
unsubscribe()
unschedule()
childDevices.each {
deleteChildDevice(it.deviceNetworkId)
}
}
def updated() {
if (debug) { app.updateSetting('dbgEnable', debug) } // temporary cleanup code
if (logNew) { app.updateSetting('newEnable', logNew) } // temporary cleanup code
app.removeSetting('debug') // temporary cleanup code
app.removeSetting('logNew') // temporary cleanup code
unsubscribe()
unschedule()
initialize()
}
def initialize() {
atomicStateByDeviceId.clear()
if (!settings.bridgeHost && state.bridgeHost) { // migrate bridgeHost from state to setting\
setBridgeHost(bridgeHost)
state.remove('bridgeHost')
}
if (selectedDevice) {
ssdpSubscribeUpdate() // Setup listener to update the configured hub details
} else {
ssdpSubscribe() // Setup listener to find all hue hubs
}
ssdpDiscover()
}
def subscribe() {
// Add message subscriptions for devices, if needed
}
/*
* SSDP Device Discover
*/
void ssdpSubscribe() {
subscribe(location, 'ssdpTerm.upnp:rootdevice', ssdpHandler)
}
void ssdpSubscribeUpdate() {
subscribe(location, 'ssdpTerm.upnp:rootdevice', ssdpUpdateHandler)
}
void ssdpUnsubscribe() {
unsubscribe(ssdpHandler)
unsubscribe(ssdpUpdateHandler)
unschedule(ssdpDiscover)
}
void ssdpDiscover() {
sendHubCommand(new hubitat.device.HubAction('lan discovery upnp:rootdevice', hubitat.device.Protocol.LAN))
}
def ssdpHandler(evt) {
def description = evt.description
def parsedEvent = parseLanMessage(description)
def ssdpPath = parsedEvent.ssdpPath
// The Hue bridge publishes the device information in /description.xml, so if this ssdpPath does not match, skip this device.
if (ssdpPath != '/description.xml') { return }
def hub = evt?.hubId
if (parsedEvent.networkAddress) {
parsedEvent << ['hub':hub,
'networkAddress': convertToHexToIP(parsedEvent.networkAddress),
'deviceAddress': convertToHexToInt(parsedEvent.deviceAddress)]
def ssdpUSN = parsedEvent.ssdpUSN.toString()
def hubs = getHubs()
if (!hubs."${ssdpUSN}") {
verifyDevice(parsedEvent)
} else {
updateDevice(parsedEvent)
}
}
}
def ssdpUpdateHandler(evt) {
def description = evt.description
def parsedEvent = parseLanMessage(description)
def ssdpPath = parsedEvent.ssdpPath
// The Hue bridge publishes the device information in /description.xml, so if this ssdpPath does not match, skip this device.
if (ssdpPath != '/description.xml') { return }
def hub = evt?.hubId
if (parsedEvent.networkAddress) {
parsedEvent << ['hub':hub,
'networkAddress': convertToHuexToIP(parsedEvent.networkAddress),
'deviceAddress': convertToHuexToInt(parsedEvent.deviceAddress)]
def ssdpUSN = parsedEvent.ssdpUSN.toString()
if ("${parsedEvent.mac}" == "${selectedDevice}") {
def hubs = getHubs()
if (hubs."${ssdpUSN}") {
log.info "${parsedEvent.mac}: Autodetect IP address ${parsedEvent.networkAddress}"
updateDevice(parsedEvent)
setBridgeHost("${parsedEvent.networkAddress}:${parsedEvent.deviceAddress}")
}
ssdpUnsubscribe()
}
}
}
void updateDevice(parsedEvent) {
def ssdpUSN = parsedEvent.ssdpUSN.toString()
def hubs = getHubs()
def device = hubs["${ssdpUSN}"]
if (device.networkAddress != parsedEvent.networkAddress || device.deviceAddress != parsedEvent.deviceAddress) {
device << ['networkAddress': parsedEvent.networkAddress,
'deviceAddress': parsedEvent.deviceAddress]
if (logEnable) { log.debug "Discovered hub address update: ${device.name}" }
}
}
void verifyDevice(parsedEvent) {
def ssdpPath = parsedEvent.ssdpPath
// The Hue bridge publishes the device information in /description.xml, so if this ssdpPath does not match, skip this device.
if (ssdpPath != '/description.xml') { return }
// Using the httpGet method, and arrow function, perform the validation check w/o the need for a callback function.
httpGet("http://${parsedEvent.networkAddress}:${parsedEvent.deviceAddress}${ssdpPath}") { response ->
if (!response.isSuccess()) {return}
def data = response.data
if (data) {
def device = data.device
String model = device.modelName
String ssdpUSN = "${parsedEvent.ssdpUSN.toString()}"
if (logEnable) { log.debug "Identified model: ${model}" }
if (model =~ 'Philips hue bridge.*') {
def hubId = "${parsedEvent.mac}"[-6..-1]
String name = "${device.friendlyName}".replaceAll(~/\(.*\)/, "(${hubId})")
parsedEvent << ['url': "${data.URLBase}",
'name': "${name}",
'serialNumber': "${device.serialNumber}"]
def hubs = getHubs()
hubs << ["${ssdpUSN}": parsedEvent]
if (logEnable) { log.debug "Discovered new hub: ${name}" }
}
}
}
}
/*
*
* Hue Hub API Integration Functions
*
*/
private requestHubAccess(mac) {
def device = getHubForMac(mac)
def deviceType = '{"devicetype": "AdvanceHueBridgeLink#Hubitat", "generateclientkey": true}'
asynchttpPost(requestHubAccessHandler,
[uri: "http://${device.networkAddress}/api",
contentType: 'application/json',
requestContentType: 'application/json',
body: deviceType], [device: device])
}
def requestHubAccessHandler(response, args) {
def status = response.getStatus();
if (status < 200 || status >= 300) { return }
def data = response.json
if (data) {
if (data.error?.description) {
if (logEnable) { log.error "${data.error.description[0]}" }
} else if (data.success) {
if (data.success.username && data.success.clientkey) {
def device = getHubForMac(args.device.mac)
device.remove("clientkey")
device << [username: "${data.success.username[0]}"] << [clientkey: "${data.success.clientkey[0]}"]
if (logEnable) { log.debug "Obtained credentials: ${device}" }
} else {
log.error "Problem with hub linking. Received response: ${data}"
}
} else {
if (logEnable) { log.error "${data}" }
}
}
}
String getApiUrl() {
"https://${getBridgeHost()}/api/${state.username}"
}
String getApiV2Url() {
uri: "https://${getBridgeHost()}/clip/v2"
}
Map getApiV2Header() {
['hue-application-key': state.username]
}
void refreshHubStatus() {
def url = apiUrl
httpGet([uri: url,
contentType: 'application/json',
ignoreSSLIssues: true,
requestContentType: 'application/json']) { response ->