-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.groovy
1701 lines (1575 loc) · 78.2 KB
/
app.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
/**
* HOOBS (Connect)
* Copyright 2018, 2019, 2020 Anthony Santilli
*/
String appVersion() { return "2.3.3" }
String appModified() { return "04-28-2020" }
String branch() { return "master" }
String platform() { return "SmartThings" }
String pluginName() { return "${platform()}-v2" }
String appIconUrl() { return "https://raw.githubusercontent.com/hoobs-org/smartthings/main/icon@2x.png" }
String getAppImg(imgName, ext=".png") { return "https://raw.githubusercontent.com/hoobs-org/smartthings/main/images/${imgName}${ext}" }
Map minVersions() { return [plugin: 233] }
definition(
name: "HOOBS (Connect)",
namespace: "hoobs-org",
author: "Anthony Santilli",
description: "Provides the API interface between HOOBS and ${platform()}",
category: "My Apps",
iconUrl: "https://raw.githubusercontent.com/hoobs-org/smartthings/main/icon@1x.png",
iconX2Url: "https://raw.githubusercontent.com/hoobs-org/smartthings/main/icon@2x.png",
iconX3Url: "https://raw.githubusercontent.com/hoobs-org/smartthings/main/icon@3x.png",
oauth: true)
{
appSetting "devMode"
appSetting "log_address"
}
preferences {
page(name: "startPage")
page(name: "mainPage")
page(name: "defineDevicesPage")
page(name: "deviceSelectPage")
page(name: "changeLogPage")
page(name: "capFilterPage")
page(name: "virtDevicePage")
page(name: "developmentPage")
page(name: "historyPage")
page(name: "deviceDebugPage")
page(name: "settingsPage")
page(name: "confirmPage")
}
private Map ignoreLists() {
Boolean noPwr = true
Boolean noEnr = true
Map o = [
commands: ["indicatorWhenOn", "indicatorWhenOff", "ping", "refresh", "indicatorNever", "configure", "poll", "reset"],
attributes: [
'DeviceWatch-Enroll', 'DeviceWatch-Status', "checkInterval", "LchildVer", "FchildVer", "LchildCurr", "FchildCurr", "lightStatus", "lastFanMode", "lightLevel",
"coolingSetpointRange", "heatingSetpointRange", "thermostatSetpointRange"
],
evt_attributes: [
'DeviceWatch-DeviceStatus', "DeviceWatch-Enroll", 'checkInterval', 'devTypeVer', 'dayPowerAvg', 'apiStatus', 'yearCost', 'yearUsage','monthUsage', 'monthEst', 'weekCost', 'todayUsage',
'maxCodeLength', 'maxCodes', 'readingUpdated', 'maxEnergyReading', 'monthCost', 'maxPowerReading', 'minPowerReading', 'monthCost', 'weekUsage', 'minEnergyReading',
'codeReport', 'scanCodes', 'verticalAccuracy', 'horizontalAccuracyMetric', 'altitudeMetric', 'latitude', 'distanceMetric', 'closestPlaceDistanceMetric',
'closestPlaceDistance', 'leavingPlace', 'currentPlace', 'codeChanged', 'codeLength', 'lockCodes', 'healthStatus', 'horizontalAccuracy', 'bearing', 'speedMetric',
'speed', 'verticalAccuracyMetric', 'altitude', 'indicatorStatus', 'todayCost', 'longitude', 'distance', 'previousPlace','closestPlace', 'places', 'minCodeLength',
'arrivingAtPlace', 'lastUpdatedDt', 'scheduleType', 'zoneStartDate', 'zoneElapsed', 'zoneDuration', 'watering', 'eventTime', 'eventSummary', 'endOffset', 'startOffset',
'closeTime', 'endMsgTime', 'endMsg', 'openTime', 'startMsgTime', 'startMsg', 'calName', "deleteInfo", "eventTitle", "floor", "sleeping", "powerSource", "batteryStatus",
"LchildVer", "FchildVer", "LchildCurr", "FchildCurr", "lightStatus", "lastFanMode", "lightLevel", "coolingSetpointRange", "heatingSetpointRange", "thermostatSetpointRange",
"colorName", "locationForURL", "location", "offsetNotify"
],
capabilities: ["Health Check", "Ultraviolet Index", "Indicator", "Window Shade Preset"]
]
if(noPwr) { o?.attributes?.push("power"); o?.evt_attributes?.push("power"); o?.capabilities?.push("Power Meter") }
if(noEnr) { o?.attributes?.push("energy"); o?.evt_attributes?.push("energy"); o?.capabilities?.push("Energy Meter") }
return o
}
def startPage() {
if(!getAccessToken()) { return dynamicPage(name: "mainPage", install: false, uninstall: true) { section() { paragraph title: "OAuth Error", "OAuth is not Enabled for ${app?.getName()}!.\n\nPlease click remove and Enable Oauth under the SmartApp App Settings in the IDE", required: true, state: null } } }
else {
if(!state?.installData) { state?.installData = [initVer: appVersion(), dt: getDtNow().toString(), updatedDt: getDtNow().toString(), shownDonation: false] }
checkVersionData(true)
if(showChgLogOk()) { return changeLogPage() }
return mainPage()
}
}
def mainPage() {
Boolean isInst = (state?.isInstalled == true)
return dynamicPage(name: "mainPage", nextPage: (isInst ? "confirmPage" : ""), install: !isInst, uninstall: true) {
appInfoSect()
section("Define Specific Categories:") {
paragraph "Each category below will adjust the device attributes to make sure they are recognized as the desired device type under HomeKit.\nNOTICE: Don't select the same devices used here in the Select Your Devices Input below.", state: "complete"
Boolean conf = (lightList || buttonList || fanList || fan3SpdList || fan4SpdList || speakerList || shadesList || garageList || tstatList || tstatHeatList)
Integer fansize = (fanList?.size() ?: 0) + (fan3SpdList?.size() ?: 0) + (fan4SpdList?.size() ?: 0)
String desc = "Tap to configure"
if(conf) {
desc = ""
desc += lightList ? "(${lightList?.size()}) Light Devices\n" : ""
desc += buttonList ? "(${buttonList?.size()}) Button Devices\n" : ""
desc += (fanList || fan3SpdList || fan4SpdList) ? "(${fansize}) Fan Devices\n" : ""
desc += speakerList ? "(${speakerList?.size()}) Speaker Devices\n" : ""
desc += shadesList ? "(${shadesList?.size()}) Shade Devices\n" : ""
desc += garageList ? "(${garageList?.size()}) Garage Door Devices\n" : ""
desc += tstatList ? "(${tstatList?.size()}) Tstat Devices\n" : ""
desc += tstatHeatList ? "(${tstatHeatList?.size()}) Tstat Heat Devices\n" : ""
desc += "\nTap to modify..."
}
href "defineDevicesPage", title: "Define Device Types", required: false, image: getAppImg("devices2"), state: (conf ? "complete" : null), description: desc
}
section("All Other Devices:") {
Boolean conf = (sensorList || switchList || deviceList)
String desc = "Tap to configure"
if(conf) {
desc = ""
desc += sensorList ? "(${sensorList?.size()}) Sensor Devices\n" : ""
desc += switchList ? "(${switchList?.size()}) Switch Devices\n" : ""
desc += deviceList ? "(${deviceList?.size()}) Other Devices\n" : ""
desc += "\nTap to modify..."
}
href "deviceSelectPage", title: "Select your Devices", required: false, image: getAppImg("devices"), state: (conf ? "complete" : null), description: desc
}
inputDupeValidation()
section("Capability Filtering:") {
Boolean conf = (
removeAcceleration || removeBattery || removeButton || removeContact || removeEnergy || removeHumidity || removeIlluminance || removeLevel || removeLock || removeMotion ||
removePower || removePresence || removeSwitch || removeTamper || removeTemp || removeValve
)
href "capFilterPage", title: "Filter out capabilities from your devices", required: false, image: getAppImg("filter"), state: (conf ? "complete" : null), description: (conf ? "Tap to modify..." : "Tap to configure")
}
section("Virtual Devices:") {
Boolean conf = (modeList || routineList)
String desc = "Create virtual (mode, routine) devices\n\nTap to Configure..."
if(conf) {
desc = ""
desc += modeList ? "(${modeList?.size()}) Mode Devices\n" : ""
desc += routineList ? "(${routineList?.size()}) Routine Devices\n" : ""
desc += "\nTap to modify..."
}
href "virtDevicePage", title: "Configure Virtual Devices", required: false, image: getAppImg("devices"), state: (conf ? "complete" : null), description: desc
}
section("Smart Home Monitor (SHM):") {
paragraph title:"NOTICE:", "This will not work with the New SmartThings Home Monitor (Under the new mobile app). If you are using the new STHM please disable the setting below."
input "addSecurityDevice", "bool", title: "Allow SHM Control in HomeKit?", required: false, defaultValue: true, submitOnChange: true, image: getAppImg("alarm_home")
}
section("Plugin Options & Review:") {
// paragraph "Turn off if you are having issues sending commands"
// input "sendCmdViaHubaction", "bool", title: "Send HomeKit Commands Locally?", required: false, defaultValue: true, submitOnChange: true, image: getAppImg("command")
input "temp_unit", "enum", title: "Temperature Unit?", required: true, defaultValue: location?.temperatureScale, options: ["F":"Fahrenheit", "C":"Celcius"], submitOnChange: true, image: getAppImg("command")
Integer devCnt = getDeviceCnt()
href url: getAppEndpointUrl("config"), style: "embedded", required: false, title: "Render the platform data for HOOBS plugin", description: "Tap, select, copy, then click \"Done\"", state: "complete", image: getAppImg("info")
if(devCnt > 148) {
paragraph "Notice:\nHOOBS Allows for 149 Devices per Bridge.", image: getAppImg("error"), state: null, required: true
}
paragraph "Devices Selected: (${devCnt})", image: getAppImg("info"), state: "complete"
}
section("History and Device Data:") {
href "historyPage", title: "Command and Event History", image: getAppImg("backup")
href "deviceDebugPage", title: "Device Data Viewer", image: getAppImg("debug")
}
section("App Preferences:") {
def sDesc = getSetDesc()
href "settingsPage", title: "App Settings", description: sDesc, state: (sDesc?.endsWith("modify...") ? "complete" : null), required: false, image: getAppImg("settings")
label title: "App Label (optional)", description: "Rename this App", defaultValue: app?.name, required: false, image: getAppImg("name_tag")
}
if(devMode()) {
section("Dev Mode Options") {
input "sendViaNgrok", "bool", title: "Communicate with plugin via HTTP?", defaultValue: false, submitOnChange: true, image: getAppImg("command")
if(sendViaNgrok) { input "ngrokHttpUrl", "text", title: "Enter the ngrok code from the url", required: true, submitOnChange: true }
}
section("Other Settings:") {
input "restartService", "bool", title: "Restart the HOOBS plugin when you press Save?", required: false, defaultValue: false, submitOnChange: true, image: getAppImg("reset")
}
}
clearTestDeviceItems()
}
}
def deviceValidationErrors() {
/*
NOTE: Determine what we require to determine the thermostat a thermostat so we can support devices like Flair which are custom heat-only thermostats.
*/
Map reqs = [
tstat: [ c:["Thermostat Operating State"], a: [r: ["thermostatOperatingState"], o: ["heatingSetpoint", "coolingSetpoint"]] ],
tstat_heat: [
c: ["Thermostat Operating State"],
a: [
r: ["thermostatOperatingState", "heatingSetpoint"],
o: []
]
]
]
// if(tstatHeatList || tstatList) {}
return reqs
}
def defineDevicesPage() {
return dynamicPage(name: "defineDevicesPage", title: "", install: false, uninstall: false) {
section("Define Specific Categories:") {
paragraph "NOTE: Please do not select a device here and then again in another input below."
paragraph "Each category below will adjust the device attributes to make sure they are recognized as the desired device type under HomeKit", state: "complete"
input "lightList", "capability.switch", title: "Lights: (${lightList ? lightList?.size() : 0} Selected)", multiple: true, submitOnChange: true, required: false, image: getAppImg("light_on")
input "garageList", "capability.garageDoorControl", title: "Garage Doors: (${garageList ? garageList?.size() : 0} Selected)", multiple: true, submitOnChange: true, required: false, image: getAppImg("garage_door")
input "buttonList", "capability.button", title: "Buttons: (${buttonList ? buttonList?.size() : 0} Selected)", multiple: true, submitOnChange: true, required: false, image: getAppImg("button")
input "speakerList", "capability.switch", title: "Speakers: (${speakerList ? speakerList?.size() : 0} Selected)", multiple: true, submitOnChange: true, required: false, image: getAppImg("media_player")
input "shadesList", "capability.windowShade", title: "Window Shades: (${shadesList ? shadesList?.size() : 0} Selected)", multiple: true, submitOnChange: true, required: false, image: getAppImg("window_shade")
}
section("Fans") {
input "fanList", "capability.switch", title: "Fans: (${fanList ? fanList?.size() : 0} Selected)", multiple: true, submitOnChange: true, required: false, image: getAppImg("fan_on")
input "fan3SpdList", "capability.switch", title: "Fans (3 Speeds): (${fan3SpdList ? fan3SpdList?.size() : 0} Selected)", multiple: true, submitOnChange: true, required: false, image: getAppImg("fan_on")
input "fan4SpdList", "capability.switch", title: "Fans (4 Speeds): (${fan4SpdList ? fan4SpdList?.size() : 0} Selected)", multiple: true, submitOnChange: true, required: false, image: getAppImg("fan_on")
}
section("Thermostats") {
input "tstatList", "capability.thermostat", title: "Thermostats: (${tstatList ? tstatList?.size() : 0} Selected)", multiple: true, submitOnChange: true, required: false, image: getAppImg("thermostat")
input "tstatHeatList", "capability.thermostat", title: "Heat Only Thermostats: (${tstatHeatList ? tstatHeatList?.size() : 0} Selected)", multiple: true, submitOnChange: true, required: false, image: getAppImg("thermostat")
}
}
}
def deviceSelectPage() {
return dynamicPage(name: "deviceSelectPage", title: "", install: false, uninstall: false) {
section("All Other Devices:") {
input "sensorList", "capability.sensor", title: "Sensors: (${sensorList ? sensorList?.size() : 0} Selected)", multiple: true, submitOnChange: true, required: false, image: getAppImg("sensors")
input "switchList", "capability.switch", title: "Switches: (${switchList ? switchList?.size() : 0} Selected)", multiple: true, submitOnChange: true, required: false, image: getAppImg("switch")
input "deviceList", "capability.refresh", title: "Others: (${deviceList ? deviceList?.size() : 0} Selected)", multiple: true, submitOnChange: true, required: false, image: getAppImg("devices2")
}
}
}
def settingsPage() {
return dynamicPage(name: "settingsPage", title: "", install: false, uninstall: false) {
section("Logging:") {
input "showEventLogs", "bool", title: "Show Events in Live Logs?", required: false, defaultValue: true, submitOnChange: true, image: getAppImg("debug")
input "showDebugLogs", "bool", title: "Debug Logging?", required: false, defaultValue: false, submitOnChange: true, image: getAppImg("debug")
}
section("Reset Token:") {
paragraph title: "What This?", "This will allow you to clear you existing and auth_token and force a new one to be created"
input "resetAppToken", "bool", title: "Revoke and Recreate Access Token?", defaultValue: false, submitOnChange: true, image: getAppImg("reset")
if(settings?.resetAppToken) { settingUpdate("resetAppToken", "false", "bool"); resetAppToken() }
}
}
}
private resetAppToken() {
logWarn("resetAppToken | Current Access Token Removed...")
state.remove("accessToken")
if(getAccessToken()) {
logInfo("resetAppToken | New Access Token Created...")
}
}
private resetCapFilters() {
List items = settings?.each?.findAll { it?.key?.startsWith("remove") }?.collect { it?.key as String }
if(items?.size()) {
items?.each { item->
settingRemove(item)
}
}
}
private inputDupeValidation() {
Map clnUp = [d: [:], o: [:]]
Map items = [
d: ["fanList": "Fans", "fan3SpdList": "Fans (3-Speed)", "fan4SpdList": "Fans (4-Speed)", "buttonList": "Buttons", "lightList": "Lights", "shadesList": "Window Shadse", "speakerList": "Speakers",
"garageList": "Garage Doors", "tstatList": "Thermostat", "tstatHeatList": "Thermostat (Heat Only)"
],
o: ["deviceList": "Other", "sensorList": "Sensor", "switchList": "Switch"]
]
items?.d?.each { k, v->
List priItems = (settings?."${k}"?.size()) ? settings?."${k}"?.collect { it?.getLabel() } : null
if(priItems) {
items?.d?.each { k2, v2->
List secItems = (settings?."${k2}"?.size()) ? settings?."${k2}"?.collect { it?.getLabel() } : null
if(k != k2 && secItems) {
secItems?.retainAll(priItems)
if(secItems?.size()) {
clnUp?.d[k2] = clnUp?.d[k2] ?: []
clnUp?.d[k2] = (clnUp?.d[k2] + secItems)?.unique()
}
}
}
items?.o?.each { k2, v2->
List secItems = (settings?."${k2}"?.size()) ? settings?."${k2}"?.collect { it?.getLabel() } : null
if(secItems) {
secItems?.retainAll(priItems)
if(secItems?.size()) {
clnUp?.o[k2] = clnUp?.o[k2] ?: []
clnUp?.o[k2] = (clnUp?.o[k2] + secItems)?.unique()
}
}
}
}
}
String out = ""
Boolean show = false
Boolean first = true
if(clnUp?.d?.size()) {
show=true
clnUp?.d?.each { k,v->
out += "${first ? "" : "\n"}${items?.d[k]}:\n "
out += v?.join("\n ") + "\n"
first = false
}
}
if(clnUp?.o?.size()) {
show=true
clnUp?.o?.each { k,v->
out += "${first ? "" : "\n"}${items?.o[k]}:\n "
out += v?.join("\n ") + "\n"
first = false
}
}
if(show && out) {
section("Duplicate Device Validation:") {
paragraph title: "Duplicate Devices Found in these Inputs:", out + "\nPlease remove these duplicate items!", required: true, state: null
}
}
}
String getSetDesc() {
def s = []
if(settings?.showEventLogs == true) s?.push("\u2022 Device Event Logs")
if(settings?.showDebugLogs == true) s?.push("\u2022 Debug Logging")
return s?.size() ? "${s?.join("\n")}\n\nTap to modify..." : "Tap to configure..."
}
def historyPage() {
return dynamicPage(name: "historyPage", title: "", install: false, uninstall: false) {
List cHist = getCmdHistory()?.sort {it?.dt}?.reverse()
List eHist = getEvtHistory()?.sort {it?.dt}?.reverse()
section("Last (${cHist?.size()}) Commands:") {
if(cHist?.size()) {
cHist?.each { c-> paragraph title: c?.dt, "Device: ${c?.data?.device}\nCommand: (${c?.data?.cmd})${c?.data?.value1 ? "\nValue1: (${c?.data?.value1})" : ""}${c?.data?.value2 ? "\nValue2: (${c?.data?.value2})" : ""}", state: "complete" }
} else {paragraph "No Command History Found..." }
}
section("Last (${eHist?.size()}) Events:") {
if(eHist?.size()) {
eHist?.each { h-> paragraph title: h?.dt, "Device: ${h?.data?.device}\nEvent: (${h?.data?.name})${h?.data?.value ? "\nValue: (${h?.data?.value})" : ""}", state: "complete" }
} else {paragraph "No Event History Found..." }
}
}
}
def capFilterPage() {
return dynamicPage(name: "capFilterPage", title: "Filter out capabilities", install: false, uninstall: false) {
section("Restrict Temp Device Creation") {
input "noTemp", "bool", title: "Remove Temp from All Contacts and Water Sensors?", required: false, defaultValue: false, submitOnChange: true
if(settings?.noTemp) {
input "sensorAllowTemp", "capability.sensor", title: "Allow Temp on these Sensors", multiple: true, submitOnChange: true, required: false, image: getAppImg("temperature")
}
}
section("Remove Capabilities from Devices") {
paragraph "This will allow you to filter out certain capabilities from creating unwanted devices under HomeKit"
input "removeAcceleration", "capability.accelerationSensor", title: "Remove Acceleration from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("acceleration")
input "removeBattery", "capability.battery", title: "Remove Battery from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("battery")
input "removeButton", "capability.button", title: "Remove Buttons from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("button")
input "removeContact", "capability.contactSensor", title: "Remove Contact from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("contact")
// input "removeEnergy", "capability.energyMeter", title: "Remove Energy Meter from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("power")
input "removeHumidity", "capability.relativeHumidityMeasurement", title: "Remove Humidity from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("humidity")
input "removeIlluminance", "capability.illuminanceMeasurement", title: "Remove Illuminance from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("illuminance")
input "removeLevel", "capability.switchLevel", title: "Remove Level from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("speed_knob")
input "removeLock", "capability.lock", title: "Remove Lock from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("lock")
input "removeMotion", "capability.motionSensor", title: "Remove Motion from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("motion")
// input "removePower", "capability.powerMeter", title: "Remove Power Meter from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("power")
input "removePresence", "capability.presenceSensor", title: "Remove Presence from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("presence")
input "removeSwitch", "capability.switch", title: "Remove Switch from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("switch")
input "removeTamper", "capability.tamperAlert", title: "Remove Tamper from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("tamper")
input "removeTemp", "capability.temperatureMeasurement", title: "Remove Temperature from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("temperature")
input "removeValve", "capability.valve", title: "Remove Valve from these Devices", multiple: true, submitOnChange: true, required: false, image: getAppImg("valve")
}
section("Filter Reset:", hideable: true, hidden: true) {
input "resetCapFilters", "bool", title: "Clear All Selected Removal Filters?", required: false, defaultValue: false, submitOnChange: true, image: getAppImg("reset")
if(settings?.resetCapFilters) { settingUpdate("resetCapFilters", "false", "bool"); resetCapFilters() }
}
}
}
def virtDevicePage() {
return dynamicPage(name: "virtDevicePage", title: "", install: false, uninstall: false) {
section("Create Devices for Modes in HomeKit?") {
paragraph title: "What are these for?", "A virtual switch will be created for each mode in HomeKit.\nThe switch will be ON when that mode is active.", state: "complete", image: getAppImg("info")
def modes = location?.modes?.sort{it?.name}?.collect { [(it?.id):it?.name] }
input "modeList", "enum", title: "Create Devices for these Modes", required: false, multiple: true, options: modes, submitOnChange: true, image: getAppImg("mode")
}
section("Create Devices for Routines in HomeKit?") {
paragraph title: "What are these?", "A virtual device will be created for each routine in HomeKit.\nThese are very useful for use in Home Kit scenes", state: "complete", image: getAppImg("info")
def routines = location.helloHome?.getPhrases()?.sort { it?.label }?.collect { [(it?.id):it?.label] }
input "routineList", "enum", title: "Create Devices for these Routines", required: false, multiple: true, options: routines, submitOnChange: true, image: getAppImg("routine")
}
}
}
def confirmPage() {
return dynamicPage(name: "confirmPage", title: "Confirmation Page", install: true, uninstall:true) {
section() {
paragraph "Restarting the service is no longer required to apply any device changes under homekit.\n\nThe service will refresh your devices about 15-20 seconds after Pressing Done/Save.", state: "complete", image: getAppImg("info")
}
}
}
def deviceDebugPage() {
return dynamicPage(name: "deviceDebugPage", title: "", install: false, uninstall: false) {
section("All Other Devices:") {
paragraph "Have a device that's not working under homekit like you want?\nSelect a device from one of the inputs below and it will show you all data about the device.", state: "complete", image: getAppImg("info")
if(!debug_switch && !debug_other && !debug_garage && !debug_tstat)
input "debug_sensor", "capability.sensor", title: "Sensors: ", multiple: false, submitOnChange: true, required: false, image: getAppImg("sensors")
if(!debug_sensor && !debug_other && !debug_garage && !debug_tstat)
input "debug_switch", "capability.actuator", title: "Switches: ", multiple: false, submitOnChange: true, required: false, image: getAppImg("switch")
if(!debug_switch && !debug_sensor && !debug_garage && !debug_tstat)
input "debug_other", "capability.refresh", title: "Others Devices: ", multiple: false, submitOnChange: true, required: false, image: getAppImg("devices2")
if(!debug_sensor && !debug_other && !debug_switch)
input "debug_garage", "capability.garageDoorControl", title: "Garage Doors: ", multiple: false, submitOnChange: true, required: false, image: getAppImg("garage_door")
if(!debug_sensor && !debug_other && !debug_switch && !debug_garage)
input "debug_tstat", "capability.thermostat", title: "Thermostats: ", multiple: false, submitOnChange: true, required: false, image: getAppImg("thermostat")
if(debug_other || debug_sensor || debug_switch || debug_garage || debug_tstat) {
href url: getAppEndpointUrl("deviceDebug"), style: "embedded", required: false, title: "Tap here to view Device Data...", description: "", state: "complete", image: getAppImg("info")
}
}
}
}
public clearTestDeviceItems() {
settingRemove("debug_sensor")
settingRemove("debug_switch")
settingRemove("debug_other")
settingRemove("debug_garage")
settingRemove("debug_tstat")
}
def viewDeviceDebug() {
def sDev = null;
if(debug_other) sDev = debug_other
if(debug_sensor) sDev = debug_sensor
if(debug_switch) sDev = debug_switch
if(debug_garage) sDev = debug_garage
if(debug_tstat) sDev = debug_tstat
def json = new groovy.json.JsonOutput().toJson(getDeviceDebugMap(sDev))
def jsonStr = new groovy.json.JsonOutput().prettyPrint(json)
render contentType: "application/json", data: jsonStr
}
def getDeviceDebugMap(dev) {
def r = "No Data Returned"
if(dev) {
try {
r = [:]
r?.name = dev?.displayName?.toString()?.replaceAll("[#\$()!%&@^']", "");
r?.basename = dev?.getName();
r?.deviceid = dev?.getId();
r?.status = dev?.getStatus();
r?.manufacturer = dev?.getManufacturerName() ?: "Unknown";
r?.model = dev?.getModelName() ?: dev?.getTypeName();
r?.deviceNetworkId = dev?.getDeviceNetworkId();
r?.lastActivity = dev?.getLastActivity() ?: null;
r?.capabilities = dev?.capabilities?.collect { it?.name as String }?.unique()?.sort() ?: [];
r?.commands = dev?.supportedCommands?.collect { it?.name as String }?.unique()?.sort() ?: [];
r?.customflags = getDeviceFlags(dev) ?: [];
r?.attributes = [:];
r?.eventHistory = dev?.eventsSince(new Date() - 1, [max: 20])?.collect { "${it?.date} | [${it?.name}] | (${it?.value}${it?.unit ? " ${it?.unit}" : ""})" };
dev?.supportedAttributes?.collect { it?.name as String }?.unique()?.sort()?.each { r?.attributes[it] = dev?.currentValue(it as String); };
} catch(ex) {
logError("Error while generating device data: ", ex);
}
}
return r
}
def getDeviceCnt(phyOnly=false) {
List devices = []
List items = deviceSettingKeys()?.collect { it?.key as String }
items?.each { item -> if(settings[item]?.size() > 0) devices = devices + settings[item] }
if(!phyOnly) {
["modeList", "routineList"]?.each { item->
if(settings[item]?.size() > 0) devices = devices + settings[item]
}
}
return devices?.unique()?.size() ?: 0
}
def installed() {
logDebug("${app.name} | installed() has been called...")
state?.isInstalled = true
state?.installData = [initVer: appVersion(), dt: getDtNow().toString(), updatedDt: "Not Set", showDonation: false, shownChgLog: true]
initialize()
}
def updated() {
logDebug("${app.name} | updated() has been called...")
state?.isInstalled = true
if(!state?.installData) { state?.installData = [initVer: appVersion(), dt: getDtNow().toString(), updatedDt: getDtNow().toString(), shownDonation: false] }
unsubscribe()
stateCleanup()
initialize()
}
def initialize() {
if(getAccessToken()) {
subscribeToEvts()
runEvery5Minutes("healthCheck")
} else { logError("initialize error: Unable to get or generate smartapp access token") }
}
def getAccessToken() {
try {
if(!atomicState?.accessToken) {
atomicState?.accessToken = createAccessToken();
logWarn("SmartApp Access Token Missing... Generating New Token!!!")
return true;
}
return true
} catch (ex) {
def msg = "Error: OAuth is not Enabled for ${appName()}!. Please click remove and Enable Oauth under the SmartApp App Settings in the IDE"
logError("getAccessToken Exception: ${msg}")
return false
}
}
private subscribeToEvts() {
runIn(4, "registerDevices")
logInfo("Starting Device Subscription Process")
if(settings?.addSecurityDevice) {
subscribe(location, "alarmSystemStatus", changeHandler)
}
if(settings?.modeList) {
logDebug("Registering (${settings?.modeList?.size() ?: 0}) Virtual Mode Devices")
subscribe(location, "mode", changeHandler)
if(state?.lastMode == null) { state?.lastMode = location?.mode?.toString() }
}
state?.subscriptionRenewed = 0
subscribe(app, onAppTouch)
if(settings?.sendCmdViaHubaction != false) { subscribe(location, null, lanEventHandler, [filterEvents:false]) }
if(settings?.routineList) {
logDebug("Registering (${settings?.routineList?.size() ?: 0}) Virtual Routine Devices")
subscribe(location, "routineExecuted", changeHandler)
}
}
private healthCheck() {
checkVersionData()
if(checkIfCodeUpdated()) {
logWarn("Code Version Change Detected... Health Check will occur on next cycle.")
return
}
}
private checkIfCodeUpdated() {
logDebug("Code versions: ${state?.codeVersions}")
if(state?.codeVersions) {
if(state?.codeVersions?.mainApp != appVersion()) {
checkVersionData(true)
state?.pollBlocked = true
updCodeVerMap("mainApp", appVersion())
Map iData = atomicState?.installData ?: [:]
iData["updatedDt"] = getDtNow().toString()
iData["shownChgLog"] = false
if(iData?.shownDonation == null) {
iData["shownDonation"] = false
}
atomicState?.installData = iData
logInfo("Code Version Change Detected... | Re-Initializing SmartApp in 5 seconds")
return true
}
}
return false
}
private stateCleanup() {
List removeItems = []
if(state?.directIP && state?.directPort) {
state?.pluginDetails = [
directIP: state?.directIP,
directPort: state?.directPort
]
removeItems?.push("directIP")
removeItems?.push("directPort")
}
removeItems?.each { if(state?.containsKey(it)) state?.remove(it) }
}
def onAppTouch(event) {
updated()
}
def renderDevices() {
Map devMap = [:]
List devList = []
List items = deviceSettingKeys()?.collect { it?.key as String }
items = items+["modeList", "routineList"]
items?.each { item ->
if(settings[item]?.size()) {
settings[item]?.each { dev->
try {
Map devObj = getDeviceData(item, dev) ?: [:]
if(devObj?.size()) { devMap[dev] = devObj }
} catch (e) {
logError("Device (${dev?.displayName}) Render Exception: ${ex.message}")
}
}
}
}
if(settings?.addSecurityDevice == true) { devList?.push(getSecurityDevice()) }
if(devMap?.size()) { devMap?.sort{ it?.value?.name }?.each { k,v-> devList?.push(v) } }
return devList
}
def getDeviceData(type, sItem) {
// log.debug "getDeviceData($type, $sItem)"
String curType = null
String devId = sItem
Boolean isVirtual = false
String firmware = null
String name = null
Map optFlags = [:]
def attrVal = null
def obj = null
switch(type) {
case "routineList":
isVirtual = true
curType = "Routine"
optFlags["virtual_routine"] = 1
obj = getRoutineById(sItem)
if(obj) {
name = "Routine - " + obj?.label
attrVal = "off"
}
break
case "modeList":
isVirtual = true
curType = "Mode"
optFlags["virtual_mode"] = 1
obj = getModeById(sItem)
if(obj) {
name = "Mode - " + obj?.name
attrVal = modeSwitchState(obj?.name)
}
break
default:
curType = "device"
obj = sItem
// Define firmware variable and initialize it out of device handler attribute`
try {
if (sItem?.hasAttribute("firmware")) { firmware = sItem?.currentValue("firmware")?.toString() }
} catch (ex) { firmware = null }
break
}
if(curType && obj) {
return [
name: !isVirtual ? sItem?.displayName?.toString()?.replaceAll("[#\$()!%&@^']", "") : name?.toString()?.replaceAll("[#\$()!%&@^']", ""),
basename: !isVirtual ? sItem?.name : name,
deviceid: !isVirtual ? sItem?.id : devId,
status: !isVirtual ? sItem?.status : "Online",
manufacturerName: (!isVirtual ? sItem?.getManufacturerName() : pluginName()) ?: pluginName(),
modelName: !isVirtual ? (sItem?.getModelName() ?: sItem?.getTypeName()) : "${curType} Device",
serialNumber: !isVirtual ? sItem?.getDeviceNetworkId() : "${curType}${devId}",
firmwareVersion: firmware ?: "1.0.0",
lastTime: !isVirtual ? (sItem?.getLastActivity() ?: null) : now(),
capabilities: !isVirtual ? deviceCapabilityList(sItem) : ["${curType}": 1],
commands: !isVirtual ? deviceCommandList(sItem) : [on: 1],
deviceflags: !isVirtual ? getDeviceFlags(sItem) : optFlags,
attributes: !isVirtual ? deviceAttributeList(sItem) : ["switch": attrVal]
]
}
return null
}
String modeSwitchState(String mode) {
return location?.mode?.toString() == mode ? "on" : "off"
}
def getSecurityDevice() {
return [
name: "Security Alarm",
basename: "Security Alarm",
deviceid: "alarmSystemStatus_${location?.id}",
status: "ACTIVE",
manufacturerName: pluginName(),
modelName: "Security System",
serialNumber: "SHM",
firmwareVersion: "1.0.0",
lastTime: null,
capabilities: ["Alarm System Status": 1, "Alarm": 1],
commands: [],
attributes: ["alarmSystemStatus": getSecurityStatus()]
]
}
def getDeviceFlags(device) {
Map opts = [:]
if(settings?.fan3SpdList?.find { it?.id == device?.id }) {
opts["fan_3_spd"] = 1
}
if(settings?.fan4SpdList?.find { it?.id == device?.id }) {
opts["fan_4_spd"] = 1
}
// if(opts?.size()) log.debug "opts: ${opts}"
return opts
}
def findDevice(dev_id) {
List allDevs = []
deviceSettingKeys()?.collect { it?.key as String }?.each { key-> allDevs = allDevs + (settings?."${key}" ?: []) }
return allDevs?.find { it?.id == dev_id } ?: null
}
def authError() {
return [error: "Permission denied"]
}
def getSecurityStatus(retInt=false) {
def cur = location.currentState("alarmSystemStatus")?.value
def inc = getShmIncidents()
if(inc != null && inc?.size()) { cur = 'alarm_active' }
if(retInt) {
switch (cur) {
case 'stay':
return 0
case 'away':
return 1
case 'night':
return 2
case 'off':
return 3
case 'alarm_active':
return 4
}
} else { return cur ?: "disarmed" }
}
private setSecurityMode(mode) {
logInfo("Setting the Smart Home Monitor Mode to (${mode})...")
sendLocationEvent(name: 'alarmSystemStatus', value: mode.toString())
}
def renderConfig() {
Map jsonMap = [
platform: pluginName(),
name: pluginName(),
app_url: apiServerUrl("/api/smartapps/installations/"),
app_id: app?.getId(),
access_token: atomicState?.accessToken,
temperature_unit: settings?.temp_unit ?: location?.temperatureScale,
validateTokenId: false,
logConfig: [
debug: false,
showChanges: true,
hideTimestamp: false,
hideNamePrefix: false,
file: [
enabled: true
]
]
]
def configJson = new groovy.json.JsonOutput().toJson(jsonMap)
def configString = new groovy.json.JsonOutput().prettyPrint(configJson)
render contentType: "text/plain", data: configString
}
def renderLocation() {
return [
latitude: location?.latitude,
longitude: location?.longitude,
mode: location?.mode,
name: location?.name,
temperature_scale: settings?.temp_unit ?: location?.temperatureScale,
zip_code: location?.zipCode,
hubIP: location?.hubs[0]?.localIP,
local_commands: false, //(settings?.sendCmdViaHubaction != false),
app_version: appVersion()
]
}
def CommandReply(statusOut, messageOut) {
def replyJson = new groovy.json.JsonOutput().toJson([status: statusOut, message: messageOut])
render contentType: "application/json", data: replyJson
}
private getHttpHeaders(headers) {
def obj = [:]
new String(headers.decodeBase64()).split("\r\n")?.each {param ->
def nameAndValue = param.split(":")
obj[nameAndValue[0]] = (nameAndValue.length == 1) ? "" : nameAndValue[1].trim()
}
return obj
}
def lanEventHandler(evt) {
// log.trace "lanEventHandler..."
try {
def evtData = parseLanMessage(evt?.description?.toString())
Map headers = evtData?.headers
def slurper = new groovy.json.JsonSlurper()
def body = evtData?.body ? slurper?.parseText(evtData?.body as String) : null
// log.trace "lanEventHandler... | headers: ${headerMap}"
// log.debug "headers: $headers"
// log.debug "body: $body"
Map msgData = [:]
if (headers?.size()) {
String evtSrc = (headers?.evtsource || body?.evtsource) ? (headers?.evtsource ?: body?.evtsource) : null
if (evtSrc && evtSrc?.startsWith("Homebridge_${pluginName()}_${app?.getId()}")) {
String evtType = (headers?.evttype || body?.evttype) ? (headers?.evttype ?: body?.evttype) : null
if (body && evtType) {
switch(evtType) {
case "hkCommand":
// log.trace "hkCommand($msgData)"
def val1 = body?.values?.value1 ?: null
def val2 = body?.values?.value2 ?: null
processCmd(body?.deviceid, body?.command, val1, val2, true)
break
case "enableDirect":
// log.trace "enableDirect($msgData)"
state?.pluginDetails = [
directIP: body?.ip,
directPort: body?.port,
version: body?.version ?: null
]
updCodeVerMap("plugin", body?.version ?: null)
activateDirectUpdates(true)
break
case "attrUpdStatus":
// if(body?.evtStatus && body?.evtStatus != "OK") { log.warn "Attribute Update Failed | Device: ${body?.evtDevice} | Attribute: ${body?.evtAttr}" }
break
default:
break
}
}
}
}
} catch (ex) {
logError "lanEventHandler Exception:", ex
}
}
def deviceCommand() {
// log.info("Command Request: $params")
def val1 = request?.JSON?.value1 ?: null
def val2 = request?.JSON?.value2 ?: null
processCmd(params?.id, params?.command, val1, val2)
}
private processCmd(devId, cmd, value1, value2, local=false) {
logInfo("Process Command${local ? "(LOCAL)" : ""} | DeviceId: $devId | Command: ($cmd)${value1 ? " | Param1: ($value1)" : ""}${value2 ? " | Param2: ($value2)" : ""}")
def device = findDevice(devId)
def command = cmd
if(settings?.addSecurityDevice != false && devId == "alarmSystemStatus_${location?.id}") {
setSecurityMode(command)
CommandReply("Success", "Security Alarm, Command $command")
} else if (settings?.modeList && command == "mode" && devId) {
logDebug("Virtual Mode Received: ${devId}")
changeMode(devId)
CommandReply("Success", "Mode Device, Command $command")
} else if (settings?.routineList && command == "routine" && devId) {
logDebug("Virtual Routine Received: ${devId}")
runRoutine(devId)
CommandReply("Success", "Routine Device, Command $command")
} else {
if (!device) {
logError("Device Not Found")
CommandReply("Failure", "Device Not Found")
} else if (!device?.hasCommand(command as String)) {
logError("Device ${device.displayName} does not have the command $command")
CommandReply("Failure", "Device ${device.displayName} does not have the command $command")
} else {
try {
if (value2 != null) {
device?."$command"(value1,value2)
logInfo("Command Successful for Device ${device.displayName} | Command ${command}($value1, $value2)")
} else if (value1 != null) {
device?."$command"(value1)
logInfo("Command Successful for Device ${device.displayName} | Command ${command}($value1)")
} else {
device?."$command"()
logInfo("Command Successful for Device ${device.displayName} | Command ${command}()")
}
CommandReply("Success", "Device ${device.displayName} | Command ${command}()")
logCmd([cmd: command, device: device?.displayName, value1: value1, value2: value2])
} catch (e) {
logError("Error Occurred for Device ${device.displayName} | Command ${command}()")
CommandReply("Failure", "Error Occurred For Device ${device.displayName} | Command ${command}()")
}
}
}
}
def changeMode(modeId) {
if(modeId) {
def mode = findVirtModeDevice(modeId)
if(mode) {
logInfo("Setting the Location Mode to (${mode})...")
setLocationMode(mode)
state?.lastMode = mode
} else { logError("Unable to find a matching mode for the id: ${modeId}") }
}
}
def runRoutine(rtId) {
if(rtId) {
def rt = findVirtRoutineDevice(rtId)
if(rt?.label) {
logInfo("Executing the (${rt?.label}) Routine...")
location?.helloHome?.execute(rt?.label)
} else { logError("Unable to find a matching routine for the id: ${rtId}") }
}
}
def deviceAttribute() {
def device = findDevice(params?.id)
def attribute = params?.attribute
if (!device) {
httpError(404, "Device not found")
} else {
return [currentValue: device?.currentValue(attribute)]
}
}
def findVirtModeDevice(id) {
return getModeById(id) ?: null
}
def findVirtRoutineDevice(id) {
return getRoutineById(id) ?: null
}
def deviceQuery() {
log.trace "deviceQuery(${params?.id}"
def device = findDevice(params?.id)
if (!device) {
def mode = findVirtModeDevice(params?.id)
def routine = findVirtModeDevice(params?.id)
def obj = mode ? mode : routine ?: null
if(!obj) {
device = null
httpError(404, "Device not found")
} else {
def name = routine ? obj?.label : obj?.name
def type = routine ? "Routine" : "Mode"
def attrVal = routine ? "off" : modeSwitchState(obj?.name)
try {
deviceData?.push([
name: name,
deviceid: params?.id,
capabilities: ["${type}": 1],
commands: [on:1],
attributes: ["switch": attrVal]
])
} catch (e) {
logError("Error Occurred Parsing ${item} ${type} ${name}, Error: ${ex}")
}
}
}
if (result) {
def jsonData = [
name: device.displayName,
deviceid: device.id,
capabilities: deviceCapabilityList(device),
commands: deviceCommandList(device),
attributes: deviceAttributeList(device)
]
def resultJson = new groovy.json.JsonOutput().toJson(jsonData)
render contentType: "application/json", data: resultJson
}
}
def deviceCapabilityList(device) {
String devId = device?.getId()
def capItems = device?.capabilities?.findAll{ !(it?.name in ignoreLists()?.capabilities) }?.collectEntries { capability-> [ (capability?.name as String):1 ] }
if(isDeviceInInput("lightList", device?.id)) {
capItems["LightBulb"] = 1
}
if(isDeviceInInput("buttonList", device?.id)) {
capItems["Button"] = 1
}
if(isDeviceInInput("fanList", device?.id)) {
capItems["Fan"] = 1
}
if(isDeviceInInput("speakerList", device?.id)) {
capItems["Speaker"] = 1
}
if(isDeviceInInput("shadesList", device?.id)) {
capItems["Window Shade"] = 1
}
if(isDeviceInInput("garageList", device?.id)) {
capItems["Garage Door Control"] = 1
}
if(isDeviceInInput("tstatList", device?.id)) {
capItems["Thermostat"] = 1
capItems["Thermostat Operating State"] = 1
}
if(isDeviceInInput("tstatHeatList", device?.id)) {
capItems["Thermostat"] = 1
capItems["Thermostat Operating State"] = 1
capItems?.remove("Thermostat Cooling Setpoint")
}
if(settings?.noTemp && capItems["Temperature Measurement"] && (capItems["Contact Sensor"] || capItems["Water Sensor"])) {
Boolean remTemp = true
if(settings?.sensorAllowTemp && isDeviceInInput("sensorAllowTemp", device?.id)) remTemp = false
if(remTemp) { capItems?.remove("Temperature Measurement") }