-
Notifications
You must be signed in to change notification settings - Fork 26
/
HousePanel.groovy
2505 lines (2224 loc) · 86.2 KB
/
HousePanel.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
/**
* HousePanel
*
* Copyright 2016 to 2019 Kenneth Washington
*
* 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.
*
* This app started life displaying the history of various ssmartthings
* but it has morphed into a full blown smart panel web application
* it displays and enables interaction with switches, dimmers, locks, etc
*
* Revision history:
* 02/02/2020 - added secondary hub push and include hub id in the push
* 01/10/2020 - add mode chenge hub push and clean up code
* 12/20/2019 - bug fixes and cleanup
* 12/19/2019 - update to include new Sonos audioNotification capability
* 08/25/2019 - bugfix water leak to prevent error if wet and dry not supported
* update switches to include name
* 08/18/2019 - added water action for setting dry and wet
* 07/29/2019 - change Hubitat HubId to the actual Hub UID instead of App Id
* 07/03/2019 - added DeviceWatch-Enroll new ignore field and fixed comment above
* work on fixing color reporting for bulbs - still not quite right
* 05/27/2019 - remove blanks and images from groovy
* 05/14/2019 - add native music artist, album, art fields when present
* 05/11/2019 - clean up and tweak music; longer delays in subscribes
* 05/03/2019 - user option to specify format of event time fields
* 05/01/2019 - add try/catch for most things to prevent errors and more cleanup
* 04/30/2019 - clean up this groovy file
* 04/22/2019 - clean up SHM and HSM to return similar display fields
* - mimic Night setting in SHM to match how HSM works
* 04/21/2019 - deal with missing prefix and other null protections
* 04/18/2019 - add direct mode change for SHM and HSM (HE bug in HSM)
* 04/17/2019 - merge groovy files with detector for hub type
* 04/09/2019 - add history fields
* 03/15/2019 - fix names of mode, blank, and image, and add humidity to temperature
* 03/14/2019 - exclude fields that are not interesting from general tiles
* 03/02/2019 - added motion sensors to subscriptions and fix timing issue
* 02/26/2019 - add hubId to name query
* 02/15/2019 - change hubnum to use hubId so we can remove hubs without damage
* 02/10/2019 - redo subscriptions for push to make more efficient by group
* 02/07/2019 - tweak to ignore stuff that was blocking useful push updates
* 02/03/2019 - switch thermostat and music tiles to use native key field names
* 01/30/2019 - implement push notifications and logger
* 01/27/2019 - first draft of direct push notifications via hub post
* 01/19/2019 - added power and begin prepping for push notifications
* 01/14/2019 - fix bonehead error with switches and locks not working right due to attr
* 01/05/2019 - fix music controls to work again after separating icons out
* 12/01/2018 - hub prefix option implemented for unique tiles with multiple hubs
* 11/21/2018 - add routine to return location name
* 11/19/2018 - thermostat tweaks to support new custom tile feature
* 11/18/2018 - fixed mode names to include size cues
* 11/17/2018 - bug fixes and cleanup to match Hubitat update
* 10/30/2018 - fix thermostat bug
* 08/20/2018 - fix another bug in lock that caused render to fail upon toggle
* 08/11/2018 - miscellaneous code cleanup
* 07/24/2018 - fix bug in lock opening and closing with motion detection
* 06/11/2018 - added mobile option to enable or disable pistons and fix debugs
* 06/10/2018 - changed icons to amazon web services location for https
* 04/18/2018 - Bugfix curtemp in Thermostat, thanks to @kembod for finding this
* 04/08/2018 - Important bug fixes for thermostat and music tiles
* 03/11/2018 - Added Smart Home Monitor from Chris Hoadley
* 03/10/2018 - Major speedup by reading all things at once
* 02/25/2018 - Update to support sliders and color hue picker
* 01/04/2018 - Fix bulb bug that returned wrong name in the type
* 12/29/2017 - Changed bulb to colorControl capability for Hue light support
* Added support for colorTemperature in switches and lights
* 12/10/2017 - Added name to each thing query return
* - Remove old code block of getHistory code
*
*/
public static String version() { return "V2.064" }
public static String handle() { return "HousePanel" }
definition(
name: "${handle()}",
namespace: "kewashi",
author: "Kenneth Washington",
description: "Tap here to install ${handle()} ${version()} - a highly customizable dashboard smart app. ",
category: "Convenience",
iconUrl: "https://s3.amazonaws.com/kewpublicicon/smartthings/hpicon1x.png",
iconX2Url: "https://s3.amazonaws.com/kewpublicicon/smartthings/hpicon2x.png",
iconX3Url: "https://s3.amazonaws.com/kewpublicicon/smartthings/hpicon3x.png",
oauth: [displayName: "HousePanel", displayLink: ""])
preferences {
section("HousePanel Configuration") {
paragraph "Welcome to HousePanel. Below you will authorize your things for HousePanel."
paragraph "prefix to uniquely identify certain tiles for this hub. " +
"If left blank, hub type will determine prefix; e.g., st_ for SmartThings or h_ for Hubitat"
input (name: "hubprefix", type: "text", multiple: false, title: "Hub Prefix:", required: false, defaultValue: "st_")
paragraph "Set Hubitat Cloud Calls option to True if your HousePanel app is NOT on your local LAN. " +
"When this is true the cloud URL will be shown for use in HousePanel. When calls are through the Cloud endpoint " +
"actions will be slower than local installations. This only applies to Hubitat. SmartThings always uses Cloud calls."
input (name: "cloudcalls", type: "bool", title: "Cloud Calls", defaultValue: false, required: false, displayDuringSetup: true)
paragraph "Enable Pistons? You must have WebCore installed for this to work. Beta feature for Hubitat hubs."
input (name: "usepistons", type: "bool", multiple: false, title: "Use Pistons?", required: false, defaultValue: false)
paragraph "Timezone and Format for event time fields; e.g., America/Detroit, Europe/London, or America/Los_Angeles"
input (name: "timezone", type: "text", multiple: false, title: "Timezone Name:", required: false, defaultValue: "America/Detroit")
input (name: "dateformat", type: "text", multiple: false, title: "Date Format:", required: false, defaultValue: "M/dd h:mm")
paragraph "Specify these parameters to enable direct and instant hub pushes when things change in your home."
input "webSocketHost", "text", title: "Host IP", defaultValue: "192.168.11.20", required: false
input "webSocketPort", "text", title: "Port", defaultValue: "19234", required: false
paragraph "The Alt IP and Port values are used to send hub pushes to two distinct installations of HousePanel. " +
"If left blank a secondary hub push will not occur. Only use this if you are hosting two versions of HP " +
"that both need to stay in sync with your smart home hubs."
input "webSocketHost2", "text", title: "Alt Host IP", defaultValue: "192.168.11.186", required: false
input "webSocketPort2", "text", title: "Alt Port", defaultValue: "3080", required: false
}
section("Lights and Switches") {
input "myswitches", "capability.switch", multiple: true, required: false, title: "Switches"
input "mydimmers", "capability.switchLevel", hideWhenEmpty: true, multiple: true, required: false, title: "Dimmers"
input "mymomentaries", "capability.momentary", hideWhenEmpty: true, multiple: true, required: false, title: "Momentary Buttons"
input "mylights", "capability.light", hideWhenEmpty: true, multiple: true, required: false, title: "Lights"
input "mybulbs", "capability.colorControl", hideWhenEmpty: true, multiple: true, required: false, title: "Bulbs"
}
section ("Motion and Presence") {
input "mypresences", "capability.presenceSensor", hideWhenEmpty: true, multiple: true, required: false, title: "Presence"
input "mymotions", "capability.motionSensor", multiple: true, required: false, title: "Motion"
}
section ("Door and Contact Sensors") {
input "mycontacts", "capability.contactSensor", hideWhenEmpty: true, multiple: true, required: false, title: "Contact Sensors"
input "mydoors", "capability.doorControl", hideWhenEmpty: true, multiple: true, required: false, title: "Doors"
input "mylocks", "capability.lock", hideWhenEmpty: true, multiple: true, required: false, title: "Locks"
}
section ("Thermostat & Environment") {
input "mythermostats", "capability.thermostat", hideWhenEmpty: true, multiple: true, required: false, title: "Thermostats"
input "mytemperatures", "capability.temperatureMeasurement", hideWhenEmpty: true, multiple: true, required: false, title: "Temperature Measures"
input "myilluminances", "capability.illuminanceMeasurement", hideWhenEmpty: true, multiple: true, required: false, title: "Illuminances"
input "myweathers", "device.smartweatherStationTile", hideWhenEmpty: true, title: "Weather tile", multiple: true, required: false
}
section ("Water, Sprinklers & Smoke") {
input "mywaters", "capability.waterSensor", hideWhenEmpty: true, multiple: true, required: false, title: "Water Sensors"
input "myvalves", "capability.valve", hideWhenEmpty: true, multiple: true, required: false, title: "Sprinklers"
input "mysmokes", "capability.smokeDetector", hideWhenEmpty: true, multiple: true, required: false, title: "Smoke Detectors"
}
section ("Music & Other Sensors") {
paragraph "Any thing can be added as an Other sensor. Other sensors bring in ALL fields supported by the device handler."
input "mymusics", "capability.musicPlayer", hideWhenEmpty: true, multiple: true, required: false, title: "Music Players (legacy)"
input "myaudios", "capability.audioNotification", hideWhenEmpty: true, multiple: true, required: false, title: "Audio Devices"
input "mypowers", "capability.powerMeter", multiple: true, required: false, title: "Power Meters"
input "myothers", "capability.sensor", multiple: true, required: false, title: "Other and Virtual Sensors"
}
section("Logging") {
input (
name: "configLogLevel",
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
)
}
}
mappings {
path("/getallthings") {
action: [ POST: "getAllThings" ]
}
path("/doaction") {
action: [ POST: "doAction" ]
}
path("/doquery") {
action: [ POST: "doQuery" ]
}
path("/gethubinfo") {
action: [ POST: "getHubInfo" ]
}
}
def installed() {
initialize()
}
def updated() {
unsubscribe()
initialize()
}
def initialize() {
def hubtype = getPlatform()
state.usepistons = settings?.usepistons ?: false
state.directIP = settings?.webSocketHost ?: ""
state.directPort = settings?.webSocketPort ?: "19234"
state.directIP2 = settings?.webSocketHost2 ?: ""
state.directPort2 = settings?.webSocketPort2 ?: "3080"
state.tz = settings?.timezone ?: "America/Detroit"
state.prefix = settings?.hubprefix ?: getPrefix()
state.dateFormat = settings?.dateformat ?: "M/dd h:mm"
configureHub();
if ( state.usepistons ) {
webCoRE_init()
}
state.loggingLevelIDE = settings.configLogLevel?.toInteger() ?: 3
logger("Installed ${hubtype} hub with settings: ${settings} ", "debug")
if (state.directIP)
{
postHub(state.directIP, state.directPort, "initialize", "", "", "", "")
if ( state.directIP2 ) {
postHub(state.directIP2, state.directPort2, "initialize", "", "", "", "")
}
registerLocations()
runIn(200, "registerAll")
}
}
// detection routines - the commented line is more efficient but less foolproof
private Boolean isHubitat() {
def istrue = physicalgraph?.device?.HubAction ? false : true
// def istrue = hubUID ? true : false
return istrue
}
private Boolean isST() {
return ( ! isHubitat() )
}
private String getPlatform() {
def hubtype = isHubitat() ? 'Hubitat' : 'SmartThings'
return hubtype
}
private String getPrefix() {
def hubpre = isHubitat() ? 'h_' : 'st_'
return hubpre
}
def configureHub() {
def hub = location.hubs[0]
def hubid
def hubip
def endpt
def firmware = hub?.firmwareVersionString ?: "unknown"
if ( !isHubitat() ) {
state.hubid = hub.id
hubip = hub.localIP
logger("You must go through the OAUTH flow to obtain a proper SmartThings AccessToken", "info")
logger("You must go through the OAUTH flow to obtain a proper SmartThings EndPoint", "info")
} else {
// state.hubid = app.id
state.hubid = hubUID
if ( cloudcalls ) {
hubip = "https://oauth.cloud.hubitat.com";
endpt = "${hubip}/${hubUID}/apps/${app.id}/"
logger("Cloud installation was requested and is reflected in the hubip and endpt info", "info")
} else {
hubip = hub.localIP
endpt = "${hubip}/apps/api/${app.id}/"
}
logger("Hubitat AccessToken = ${state.accessToken}", "info")
logger("Hubitat EndPoint = ${endpt}", "info")
}
logger("Use this information on the Auth page of HousePanel.", "info")
logger("Hub Platform = ${getPlatform()}", "info")
logger("Hub IP = ${hubip}", "info")
logger("Hub ID = ${state.hubid}", "info")
logger("Hub Firmware = ${firmware}", "info")
logger("rPI IP Address = ${state.directIP}", "info")
logger("rPI webSocket Port = ${state.directPort}", "info")
logger("Alt IP Address = ${state.directIP2}", "info")
logger("Alt webSocket Port = ${state.directPort2}", "info")
logger("date Timezone for events = ${state.tz}", "info")
logger("date Format for events = ${state.dateFormat}", "info")
}
def addHistory(resp, item) {
if (resp && item ) {
try {
def start = new Date() - 7
def thestates = item.eventsSince(start,["max":4])
def i = 0;
def priorval = ""
def tz = TimeZone.getTimeZone( state.tz ?: "America/Detroit" )
thestates.each {
if ( it.value!=priorval ) {
i++
def evtvalue = it.value + " " + it.date.format(state.dateFormat ?: "M/dd h:mm", tz)
resp.put("event_${i}", evtvalue )
priorval = it.value
}
}
} catch (e) {
logger("Cannot retrieve history for device ${item.displayName}", "info")
}
}
return resp
}
def addBattery(resp, item) {
addAttr(resp, item, "battery")
}
def addAttr(resp, item, attr) {
if ( resp && item && item.hasAttribute(attr) ) {
resp.put(attr, item.currentValue(attr))
}
return resp
}
def getSwitch(swid, item=null) {
def resp = false
item = item ? item : myswitches.find {it.id == swid }
if ( item ) {
resp = [name: item.displayName]
resp = addBattery(resp, item)
resp.put("switch", item.currentValue("switch"))
resp = addHistory(resp, item)
}
return resp
}
def getBulb(swid, item=null) {
getThing(mybulbs, swid, item)
}
def getLight(swid, item=null) {
getThing(mylights, swid, item)
}
def getMomentary(swid, item=null) {
def resp = false
item = item ? item : mymomentaries.find {it.id == swid }
if ( item ) {
resp = [name: item.displayName]
resp = addBattery(resp, item)
if ( item.hasCapability("Switch") ) {
def curval = item.currentValue("switch")
if (curval!="on" && curval!="off") { curval = "off" }
resp.put("momentary", curval)
}
resp = addHistory(resp, item)
}
return resp
}
def getDimmer(swid, item=null) {
getThing(mydimmers, swid, item)
}
def getMotion(swid, item=null) {
getThing(mymotions, swid, item)
}
def getContact(swid, item=null) {
getThing(mycontacts, swid, item)
}
// change to only return lock status and battery
def getLock(swid, item=null) {
item = item? item : mylocks.find {it.id == swid }
def resp = false
if ( item ) {
resp = [name: item.displayName]
resp = addBattery(resp, item)
resp.put("lock", item.currentValue("lock"))
resp = addHistory(resp, item)
}
return resp
}
// this was updated to use the real key names so that push updates work
// note -changes were also made in housepanel.php and elsewhere to support this
def getMusic(swid, item=null) {
// def resp = getThing(mymusics, swid, item)
item = item? item : mymusics.find {it.id == swid }
def resp = false
if ( item ) {
resp = [
name: item.displayName,
trackDescription: item.currentValue("trackDescription"),
status: item.currentValue("status"),
level: item.currentValue("level"),
mute: item.currentValue("mute")
]
// add native track information if attributes exist
// this code is from @rsb in the ST forum
resp = addAttr(resp, item, "currentArtist")
resp = addAttr(resp, item, "currentAlbum")
resp = addAttr(resp, item, "trackImage")
resp = addBattery(resp, item)
resp = addHistory(resp, item)
}
// log.debug resp
return resp
}
def getAudio(swid, item=null) {
def raw = getThing(myaudios, swid, item)
logger(raw, "info" )
// lets put it in the desired order
// "groupVolumeUp", "groupVolumeDown", "muteGroup", "unmuteGroup",
def resp = [name: raw.name, audioTrackData: raw.audioTrackData,
_rewind: raw._rewind, _previousTrack: raw._previousTrack,
_pause: raw._pause, _play: raw._play, _stop: raw._stop,
_nextTrack: raw._nextTrack, _fastForward: raw._fastForward,
playbackStatus: raw.playbackStatus,
// _mute: raw._mute, _unmute: raw._unmute,
_muteGroup: raw._muteGroup, _unmuteGroup: raw._unmuteGroup,
//_volumeUp: raw._volumeUp, _volumeDown: raw._volumeDown,
_groupVolumeUp: raw._groupVolumeUp, _groupVolumeDown: raw._groupVolumeDown,
volume: raw.volume,
mute: raw.mute, groupRole: raw.groupRole]
return resp
}
// this was updated to use the real key names so that push updates work
// note -changes were also made in housepanel.php and elsewhere to support this
def getThermostat(swid, item=null) {
item = item? item : mythermostats.find {it.id == swid }
def resp = false
if ( item ) {
resp = [name: item.displayName,
temperature: item.currentValue("temperature"),
heatingSetpoint: item.currentValue("heatingSetpoint"),
coolingSetpoint: item.currentValue("coolingSetpoint"),
thermostatFanMode: item.currentValue("thermostatFanMode"),
thermostatMode: item.currentValue("thermostatMode"),
thermostatOperatingState: item.currentValue("thermostatOperatingState")
]
resp = addBattery(resp, item)
resp = addAttr(resp, item, "humidity")
resp = addHistory(resp, item)
}
return resp
}
// use absent instead of "not present" for absence state
def getPresence(swid, item=null) {
item = item ? item : mypresences.find {it.id == swid }
def resp = false
if ( item ) {
resp = [name: item.displayName]
resp = addBattery(resp, item)
def pval = (item.currentValue("presence")=="present") ? "present" : "absent"
resp.put("presence", pval)
resp = addHistory(resp, item)
}
return resp
}
def getWater(swid, item=null) {
getThing(mywaters, swid, item)
}
def getValve(swid, item=null) {
getThing(myvalves, swid, item)
}
def getDoor(swid, item=null) {
getThing(mydoors, swid, item)
}
def getIlluminance(swid, item=null) {
item = item ? item : myilluminances.find {it.id == swid }
def resp = false
if ( item ) {
resp = [name: item.displayName]
resp = addBattery(resp, item)
resp.put("illuminance", item.currentValue("illuminance") )
resp = addHistory(resp, item)
}
return resp
}
def getSmoke(swid, item=null) {
getThing(mysmokes, swid, item)
}
// return temperature for this capability and humidity if it has one
def getTemperature(swid, item=null) {
item = item ? item : mytemperatures.find {it.id == swid }
def resp = false
if ( item ) {
resp = [name: item.displayName]
resp = addBattery(resp, item)
resp.put("temperature", item.currentValue("temperature") )
resp = addAttr(resp, item, "humidity")
resp = addHistory(resp, item)
}
return resp
}
def getWeather(swid, item=null) {
getDevice(myweathers, swid, item)
}
def getOther(swid, item=null) {
getThing(myothers, swid, item)
}
def getPower(swid, item=null) {
getThing(mypowers, swid, item)
}
def extractName(swid, prefix) {
def postfix = swid ?: ""
if ( state.prefix && swid && swid.startsWith(state.prefix) ) {
def k = state.prefix.length()
postfix = swid.substring(k)
}
def thename = "$prefix $postfix"
}
def getMyMode(swid, item=null) {
def allmodes = location.getModes()
def curmode = location.getCurrentMode()
def resp = [ name: extractName(swid, "Mode"),
sitename: location.getName(), themode: curmode?.getName() ];
for (defcmd in allmodes) {
def modename = defcmd.getName()
resp.put("_${modename}",modename)
}
return resp
}
def getSHMState(swid, item=null){
def cmds = ["away", "stay", "night", "off"]
def keynames = ["Away", "Home", "Night", "Disarmed"]
def key = location.currentState("alarmSystemStatus")?.value
// mimic the states provided by HSM
def i = cmds.findIndexOf{it == key}
if ( i<0 ) { i = 3 }
// if mode is night and set to stay change mode to fake night setting
if ( i==1 ) {
def curmode = location.getCurrentMode()?.getName()
if ( curmode == "Night" ) { i= 2 }
}
def statusname = keynames[i]
def resp = [name : "Smart Home Monitor", state: statusname]
for (defcmd in cmds) {
resp.put("_${defcmd}",defcmd)
}
return resp
}
def getHSMState(swid, item=null) {
// uses Hubitat specific call for HSM per
// https://community.hubitat.com/t/hubitat-safety-monitor-api/934/11
def cmds = ["armAway", "armHome", "armNight", "disarm", "armRules", "disarmRules", "disarmAll", "armAll", "cancelAlerts"]
def keys = ["armedAway", "armedHome", "armedNight", "disarmed"]
def keynames = ["Away", "Home", "Night", "Disarmed"]
def key = location.hsmStatus ?: false
def resp
if ( !key ) {
resp = [name : "Hubitat Safety Monitor", state: "Not Installed"]
logger("location hsmStatus is invalid; it is not installed","info")
} else {
def i = keys.findIndexOf{ it == key }
def statusname = (i >= 0) ? keynames[i] : "Disarmed"
resp = [name : "Hubitat Safety Monitor", state: statusname]
logger("location hsmStatus returned: ${key} as name: ${statusname}","debug")
for (defcmd in cmds) {
resp.put("_${defcmd}",defcmd)
}
}
return resp
}
def getBlank(swid, item=null) {
def resp = [name: extractName(swid, "Blank")]
return resp
}
def getImage(swid, item=null) {
def resp = [name: extractName(swid, "Image"), url: "${swid}"]
return resp
}
def getRoutine(swid, item=null) {
def routines = location.helloHome?.getPhrases()
def routine = item ? item : routines.find{it.id == swid}
def resp = routine ? [name: routine.label, label: routine.label] : false
return resp
}
// change pistonName to name to be consistent
// but retain original for backward compatibility reasons
def getPiston(swid, item=null) {
item = item ? item : webCoRE_list().find {it.id == swid}
def resp = [name: item.name, pistonName: "idle"]
return resp
}
// a generic device getter to streamline code
def getDevice(mydevices, swid, item=null) {
def resp = false
if ( mydevices ) {
item = item ? item : mydevices.find {it.id == swid }
if (item) {
resp = [:]
def attrs = item.getSupportedAttributes()
attrs.each {att ->
try {
def attname = att.name
def attval = item.currentValue(attname)
resp.put(attname,attval)
} catch (e) {
logger("Attempt to read device for ${swid} failed ${e}", "error")
}
}
}
}
return resp
}
// make a generic thing getter to streamline the code
def getThing(things, swid, item=null, reservedcap=null) {
item = item ? item : things?.find {it.id == swid }
def resp = item ? [:] : false
if ( item ) {
resp.put("name",item.displayName)
if ( !reservedcap ) {
reservedcap = ["supportedTrackControlCommands", "supportedPlaybackCommands" ,"presets", "groupVolume", "groupMute",
"groupPrimaryDeviceId", "groupId",
"DeviceWatch-DeviceStatus", "DeviceWatch-Enroll", "checkInterval", "healthStatus"]
}
item.capabilities.each {cap ->
// def capname = cap.getName()
cap.attributes?.each {attr ->
try {
def othername = attr.getName()
def othervalue = item.currentValue(othername)
if ( !reservedcap.contains(othername) ) {
resp.put(othername,othervalue)
}
} catch (ex) {
logger("Attempt to read attribute for ${swid} failed ${ex}", "error")
}
}
}
// add commands other than standard ones
// "groupVolumeUp", "groupVolumeDown", "muteGroup", "unmuteGroup",
def reserved = ["setLevel","setHue","on","off","open","close",
"setSaturation","setColorTemperature","setColor","setAdjustedColor",
"indicatorWhenOn","indicatorWhenOff","indicatorNever",
"enrollResponse","stopLevelChange","poll","ping","configure","refresh"]
item.supportedCommands.each { comm ->
try {
def comname = comm.getName()
def args = comm.getArguments()
def arglen = 0
if (args != null)
arglen = args.size()
logger("Command for ${swid} = $comname with $arglen args = $args ", "trace")
if ( arglen==0 && ! reserved.contains(comname) ) {
resp.put( "_"+comname, comname )
}
} catch (ex) {
logger("Attempt to read command for ${swid} failed ${ex}", "error")
}
}
resp = addHistory(resp, item)
}
// fix color
if ( resp["hue"] && resp["saturation"] && resp["level"]) {
def h = resp["hue"].toInteger()
def s = resp["saturation"].toInteger()
def v = resp["level"].toInteger()
def newcolor = hsv2rgb(h, s, v)
resp["hue"] = h
resp["saturation"] = s
resp["level"] = v
resp["color"] ? resp["color"] = newcolor : resp.put("color", newcolor)
}
return resp
}
// make a generic thing list getter to streamline the code
def getThings(resp, things, thingtype) {
def n = things ? things.size() : 0
logger("Number of things of type ${thingtype} = ${n}", "debug")
things?.each {
try {
def val = getThing(things, it.id, it)
resp << [name: it.displayName, id: it.id, value: val, type: thingtype]
} catch (e) {}
}
return resp
}
def logStepAndIncrement(step)
{
logger("Debug ${step}", "trace")
return step+1
}
// This retrieves and returns all things
// used up front or whenever we need to re-read all things
def getAllThings() {
def resp = []
def run = 1
run = logStepAndIncrement(run)
resp = getSwitches(resp)
run = logStepAndIncrement(run)
resp = getDimmers(resp)
run = logStepAndIncrement(run)
resp = getMomentaries(resp)
run = logStepAndIncrement(run)
resp = getLights(resp)
run = logStepAndIncrement(run)
resp = getBulbs(resp)
run = logStepAndIncrement(run)
resp = getContacts(resp)
run = logStepAndIncrement(run)
resp = getDoors(resp)
run = logStepAndIncrement(run)
resp = getLocks(resp)
run = logStepAndIncrement(run)
resp = getMotions(resp)
run = logStepAndIncrement(run)
resp = getPresences(resp)
run = logStepAndIncrement(run)
resp = getThermostats(resp)
run = logStepAndIncrement(run)
resp = getTemperatures(resp)
run = logStepAndIncrement(run)
resp = getIlluminances(resp)
if ( isST() ) {
run = logStepAndIncrement(run)
resp = getWeathers(resp)
}
run = logStepAndIncrement(run)
resp = getValves(resp)
run = logStepAndIncrement(run)
resp = getWaters(resp)
run = logStepAndIncrement(run)
resp = getMusics(resp)
run = logStepAndIncrement(run)
resp = getAudios(resp)
run = logStepAndIncrement(run)
resp = getSmokes(resp)
run = logStepAndIncrement(run)
resp = getModes(resp)
if ( isST() ) {
run = logStepAndIncrement(run)
resp = getSHMStates(resp)
run = logStepAndIncrement(run)
resp = getRoutines(resp)
}
if ( isHubitat() ) {
run = logStepAndIncrement(run)
resp = getHSMStates(resp)
}
run = logStepAndIncrement(run)
resp = getOthers(resp)
// run = logStepAndIncrement(run)
// resp = getBlanks(resp)
// run = logStepAndIncrement(run)
// resp = getImages(resp)
run = logStepAndIncrement(run)
resp = getPowers(resp)
// optionally include pistons based on user option
if (state.usepistons) {
run = logStepAndIncrement(run)
resp = getPistons(resp)
}
return resp
}
def getModes(resp) {
logger("Getting 4 mode tiles","debug");
def vals = ["m1x1","m1x2","m2x1","m2x2"]
try {
vals.each {
def val = getMyMode(it)
resp << [name: val.name, id: "${state.prefix}${it}", value: val, type: "mode"]
}
} catch (e) {}
return resp
}
def getSHMStates(resp) {
logger("Getting Smart Home Monitor state for SmartThings Hub","debug");
try {
def val = getSHMState("${state.prefix}shm")
resp << [name: "Smart Home Monitor", id: "${state.prefix}shm", value: val, type: "shm"]
} catch (e) {}
return resp
}
def getHSMStates(resp) {
logger("Getting Hubitat Safety Monitor state for Hubitat Hub","debug");
try{
def val = getHSMState("${state.prefix}hsm")
if ( val ) {
resp << [name: "Hubitat Safety Monitor", id: "${state.prefix}hsm", value: val, type: "hsm"]
}
} catch (e) {}
return resp
}
def getBlanks(resp) {
def vals = ["b1x1","b1x2","b2x1","b2x2"]
try {
vals.each {
def val = getBlank("${state.prefix}${it}")
resp << [name: val.name, id: "${state.prefix}${it}", value: val, type: "blank"]
}
} catch (e) {}
return resp
}
def getImages(resp) {
def vals = ["img1","img2","img3","img4"]
try {
vals.each {
def val = getImage("${state.prefix}${it}")
resp << [name: val.name, id: "${state.prefix}${it}", value: val, type: "image"]
}
} catch (e) {}
return resp
}
def getPistons(resp) {
def plist = webCoRE_list()
logger("Number of pistons = " + plist?.size() ?: 0, "debug")
try {
plist?.each {
def val = getPiston(it.id, it)
resp << [name: it.name, id: it.id, value: val, type: "piston"]
}
} catch (e) {}
return resp
}
def getSwitches(resp) {
try {
myswitches?.each {
def multivalue = getSwitch(it.id, it)
resp << [name: it.displayName, id: it.id, value: multivalue, type: "switch" ]
}
} catch (e) {}
return resp
}
def getBulbs(resp) {
getThings(resp, mybulbs, "bulb")
}
def getLights(resp) {
getThings(resp, mylights, "light")
}
def getDimmers(resp) {
getThings(resp, mydimmers, "switchlevel")
}
def getMotions(resp) {
getThings(resp, mymotions, "motion")
}
def getContacts(resp) {
getThings(resp, mycontacts, "contact")
}
def getMomentaries(resp) {
try {
mymomentaries?.each {
if ( it.hasCapability("Switch") ) {
def val = getMomentary(it.id, it)
resp << [name: it.displayName, id: it.id, value: val, type: "momentary" ]
}
}
} catch (e) {}
return resp
}
def getLocks(resp) {
try {
mylocks?.each {
def multivalue = getLock(it.id, it)
resp << [name: it.displayName, id: it.id, value: multivalue, type: "lock"]
}
} catch (e) {}
return resp
}
def getMusics(resp) {
try {
mymusics?.each {
def multivalue = getMusic(it.id, it)
resp << [name: it.displayName, id: it.id, value: multivalue, type: "music"]
}
} catch (e) {}
return resp
}
def getAudios(resp) {
try {
myaudios?.each {
def multivalue = getAudio(it.id, it)
resp << [name: it.displayName, id: it.id, value: multivalue, type: "audio"]
}
} catch (e) {}
return resp
}
def getThermostats(resp) {
try {
mythermostats?.each {
def multivalue = getThermostat(it.id, it)
resp << [name: it.displayName, id: it.id, value: multivalue, type: "thermostat" ]
}
} catch (e) {}
return resp
}
def getPresences(resp) {
try {
mypresences?.each {
def multivalue = getPresence(it.id, it)
resp << [name: it.displayName, id: it.id, value: multivalue, type: "presence"]
}
} catch (e) {}
return resp
}
def getWaters(resp) {
getThings(resp, mywaters, "water")
}
def getValves(resp) {
getThings(resp, myvalves, "valve")
}
def getDoors(resp) {
getThings(resp, mydoors, "door")
}
def getIlluminances(resp) {
getThings(resp, myilluminances, "illuminance")
}
def getSmokes(resp) {
getThings(resp, mysmokes, "smoke")
}
def getTemperatures(resp) {
try {
mytemperatures?.each {
def val = getTemperature(it.id, it)
resp << [name: it.displayName, id: it.id, value: val, type: "temperature"]
}
} catch (e) {}
return resp
}
def getWeathers(resp) {
try {
myweathers?.each {
def multivalue = getWeather(it.id, it)
resp << [name: it.displayName, id: it.id, value: multivalue, type: "weather"]
}
} catch (e) {}
return resp
}
// get hellohome routines - thanks to ady264 for the tip
def getRoutines(resp) {
try {
def routines = location.helloHome?.getPhrases()
def n = routines ? routines.size() : 0
if ( n > 0 ) { logger("Number of routines = ${n}","debug"); }
routines?.each {
def multivalue = getRoutine(it.id, it)
resp << [name: it.label, id: it.id, value: multivalue, type: "routine"]
}
} catch (e) {}
return resp