-
Notifications
You must be signed in to change notification settings - Fork 23
/
google-home-community.groovy
5624 lines (5264 loc) · 206 KB
/
google-home-community.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
// Copyright 2021 The Google Home Community Contributors
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// Changelog:
// * Feb 24 2020 - Initial release
// * Feb 24 2020 - Add the Sensor device type and the Query Only Open/Close setting to better support contact sensors.
// * Feb 27 2020 - Fix issue with devices getting un-selected when linking to Google Home
// * Feb 27 2020 - Add Setting to enable/disable debug logging
// * Feb 28 2020 - Add support for using a single command with a parameter for the OnOff trait
// * Feb 29 2020 - Fall back to using device name if device label isn't defined
// * Mar 01 2020 - Add support for the Toggles device trait
// * Mar 15 2020 - Add confirmation and PIN code support
// * Mar 15 2020 - Fix Open/Close trait when "Discrete Only Open/Close" isn't set
// * Mar 17 2020 - Add support for the Lock/Unlock trait
// * Mar 18 2020 - Add support for the Color Setting trait
// * Mar 19 2020 - Add support for ambient temperature sensors using the "Query Only Temperature Setting" attribute
// of the Temperature Setting trait
// * Mar 20 2020 - Add support for the Temperature Control trait
// * Mar 21 2020 - Change Temperature Setting trait to use different setpoint commands and attributes per mode
// * Mar 21 2020 - Sort device types by name on the main settings page
// * Mar 21 2020 - Don't configure setpoint attribute and command for the "off" thermostat mode
// * Mar 21 2020 - Fix some Temperture Setting and Temperature Control settings that were using the wrong input type
// * Mar 21 2020 - Fix the Temperature Setting heat/cool buffer and Temperature Control temperature step conversions
// from Fahrenheit to Celsius
// * Mar 29 2020 - Add support for the Humidity Setting trait
// * Apr 08 2020 - Fix timeout error by making scene activation asynchronous
// * Apr 08 2020 - Add support for the Rotation trait
// * Apr 10 2020 - Add new device types: Carbon Monoxide Sensor, Charger, Remote Control, Set-Top Box,
// Smoke Detector, Television, Water Purifier, and Water Softener
// * Apr 10 2020 - Add support for the Volume trait
// * Aug 05 2020 - Add support for Camera trait
// * Aug 25 2020 - Add support for Global PIN Codes
// * Oct 03 2020 - Add support for devices not allowing volumeSet command when changing volume
// * Jan 18 2021 - Fix SetTemperature command of the TemperatureControl trait
// * Jan 19 2021 - Added Dock and StartStop Traits
// * Jan 31 2021 - Don't break the whole app if someone creates an invalid toggle
// * Feb 28 2021 - Add new device types supported by Google
// * Apr 18 2021 - Added Locator Trait
// * Apr 23 2021 - Added Energy Storage, Software Update, Reboot, Media State (query untested) and
// Timer (commands untested) Traits. Added missing camera trait protocol attributes.
// * May 04 2021 - Fixed time remaining trait of Energy Storage
// * May 07 2021 - Immediate response mode: change poll from 5 seconds to 1 second and return
// PENDING response for any devices which haven't yet reached the desired state
// * May 07 2021 - Add roomHint based on Hubitat room names
// * May 07 2021 - Log requests and responses in JSON to make debugging easier
// * May 09 2021 - Handle missing rooms API gracefully for compatibility with Hubitat < 2.2.7
// * May 10 2021 - Treat level/position of 99 as 100 instead of trying to scale
// * May 20 2021 - Add a reverseDirection setting to the Open/Close trait to support devices that consider position
// 0 to be fully open
// * Jun 27 2021 - Log a warning on SYNC if a device is selected as multiple device types
// * Mar 05 2022 - Added supportsFanSpeedPercent trait for controlling fan by percentage
// * May 07 2022 - Add error handling so one bad device doesn't prevent reporting state of other devices
// * Jun 15 2022 - Fix a crash on trait configuration introduced by Hubitat 2.3.2.127
// * Jun 20 2022 - Fixed CameraStream trait to match the latest Google API. Moved protocol support to the
// driver level to accomodate different camera stream sources
// - Added Arm/Disarm Trait
// - Added ability for the app to use device level pin codes retrieved from the device driver
// - Pincode challenge in the order device_driver -> device_GHC -> global_GHC -> null
// - Added support for returning the matching user position for Arm/Disarm and Lock/Unlock to the
// device driver
// * Jun 21 2022 - Apply rounding more consistently to temperatures
// * Jun 21 2022 - Added SensorState Trait
// * Jun 23 2022 - Fix error attempting to round null
// * Sep 08 2022 - Fix SensorState labels
// * Oct 18 2022 - Added TransportControl Trait
// * Nov 30 2022 - Implement RequestSync and ReportState APIs
// * Feb 03 2023 - Uppercase values sent for MediaState attributes
// * Mar 06 2023 - Fix hub version comparison
// * May 20 2023 - Fix error in SensorState which prevented multiple trait types from being reported.
// Allow for traits to support descriptive and/or numeric responses.
// * Jun 06 2023 - Add support for the OccupancySensing trait
// * Apr 12 2024 - Code cleanup
import groovy.json.JsonException
import groovy.json.JsonOutput
import groovy.transform.Field
import java.time.Duration
import java.time.Instant
import com.nimbusds.jose.JOSEObjectType
import com.nimbusds.jose.JWSAlgorithm
import com.nimbusds.jose.JWSHeader
import com.nimbusds.jose.crypto.RSASSASigner
import com.nimbusds.jose.jwk.JWK
import com.nimbusds.jwt.JWTClaimsSet
import com.nimbusds.jwt.SignedJWT
definition(
name: "Google Home Community",
namespace: "mbudnek",
author: "Miles Budnek",
description: "Community-maintained Google Home integration",
category: "Integrations",
iconUrl: "",
iconX2Url: "",
iconX3Url: "",
importUrl: "https://raw.githubusercontent.com/mbudnek/google-home-hubitat-community/master/google-home-community.groovy" // IgnoreLineLength
)
preferences {
page(name: "mainPreferences")
page(name: "deviceTypePreferences")
page(name: "deviceTypeDelete")
page(name: "deviceTraitPreferences")
page(name: "deviceTraitDelete")
page(name: "togglePreferences")
page(name: "toggleDelete")
}
mappings {
path("/action") {
action: [
POST: "handleAction"
]
}
}
def installed() {
LOGGER.debug("App installed, agentUserId=${agentUserId}")
updateDeviceEventSubscription()
}
def updated() {
LOGGER.debug("Preferences updated")
unsubscribe("handleDeviceEvent")
if (settings.googleServiceAccountJSON) {
requestSync()
if (settings.reportState) {
allKnownDevices().each { entry ->
subscribe(entry.value.device, "handleDeviceEvent", [filterEvents: true])
}
reportStateForDevices(allKnownDevices())
}
}
}
def handleDeviceEvent(event) {
LOGGER.debug("Handling device event, deviceId=${event.deviceId} device=${event.device}")
def deviceId = event.deviceId
def deviceInfo = allKnownDevices()."${deviceId}"
reportStateForDevices([(deviceId): deviceInfo])
}
private reportStateForDevices(devices) {
def requestId = UUID.randomUUID().toString()
def req = [
requestId: requestId,
agentUserId: agentUserId,
payload: [
devices: [
states: [:],
],
],
]
devices.each { deviceId, deviceInfo ->
def deviceState = [:]
deviceInfo.deviceType.traits.each { traitType, deviceTrait ->
deviceState += "deviceStateForTrait_${traitType}"(deviceTrait, deviceInfo.device)
}
if (deviceState.size()) {
req.payload.devices.states."${deviceId}" = deviceState
} else {
LOGGER.debug(
"Not reporting state for device ${deviceInfo.device} to Home Graph (no state -- maybe a scene?)"
)
}
}
if (req.payload.devices.states.size()) {
def token = fetchOAuthToken()
def params = [
uri: "https://homegraph.googleapis.com/v1/devices:reportStateAndNotification",
headers: [
Authorization: "Bearer REDACTED",
],
body: req,
]
LOGGER.debug("Posting device state requestId=${requestId}: ${params}")
params.headers.authorization = "Bearer ${token}"
try {
httpPostJson(params) { resp ->
LOGGER.debug("Finished posting device state requestId=${requestId}")
}
} catch (Exception ex) {
LOGGER.exception(
"Error posting device state:\nrequest=${req}\n",
ex
)
}
} else {
LOGGER.debug("No device state to report; not sending device state report to Home Graph")
}
}
def requestSync() {
LOGGER.info("Requesting Google sync devices")
def params = [
uri: "https://homegraph.googleapis.com/v1/devices:requestSync",
headers: [
Authorization: "Bearer ${fetchOAuthToken()}",
],
body: [
agentUserId: agentUserId,
],
]
httpPostJson(params) { resp ->
LOGGER.debug("Finished requesting Google sync devices")
}
}
def uninstalled() {
LOGGER.debug("App uninstalled")
// TODO: Uninstall from Google
}
@SuppressWarnings('AssignmentInConditional')
def appButtonHandler(buttonPressed) {
def match
if ((match = (buttonPressed =~ /^addPin:(.+)$/))) {
def deviceTypeName = match.group(1)
def deviceType = deviceTypeFromSettings(deviceTypeName)
addDeviceTypePin(deviceType)
} else if ((match = (buttonPressed =~ /^deletePin:(.+)\.pin\.(.+)$/))) {
def pinId = match.group(2)
// If we actually delete the PIN here then it will get added back when the
// device type settings page re-submits after the button handler finishes.
// Instead just set a flag that we want to delete this PIN, and the settings
// page will take care of actually deleting it.
state.pinToDelete = pinId
}
}
private hubVersionLessThan(versionString) {
def hubVersion = location.hub.firmwareVersionString.split("\\.")
def targetVersion = versionString.split("\\.")
for (def i = 0; i < targetVersion.length; ++i) {
if ((hubVersion[i] as int) < (targetVersion[i] as int)) {
return true
} else if ((hubVersion[i] as int) > (targetVersion[i] as int)) {
return false
}
}
return false
}
@SuppressWarnings('MethodSize')
def mainPreferences() {
// Make sure that the deviceTypeFromSettings returns by giving it a display name
app.updateSetting("GlobalPinCodes.display", "Global PIN Codes")
def globalPinCodes = deviceTypeFromSettings('GlobalPinCodes')
if (state.pinToDelete) {
deleteDeviceTypePin(globalPinCodes, state.pinToDelete)
state.remove("pinToDelete")
}
if (settings.deviceTypeToEdit != null) {
def toEdit = settings.deviceTypeToEdit
app.removeSetting("deviceTypeToEdit")
return deviceTypePreferences(deviceTypeFromSettings(toEdit))
}
if (settings.deviceTypeToDelete != null) {
def toDelete = settings.deviceTypeToDelete
app.removeSetting("deviceTypeToDelete")
return deviceTypeDelete(deviceTypeFromSettings(toDelete))
}
state.remove("currentlyEditingDeviceType")
return dynamicPage(name: "mainPreferences", title: "Device Selection", install: true, uninstall: true) {
section {
input(
name: "modesToExpose",
title: "Modes to expose",
type: "mode",
multiple: true
)
}
def allDeviceTypes = deviceTypes().sort { deviceType -> deviceType.display }
section {
allDeviceTypes.each { deviceType ->
input(
// Note: This name _must_ be converted to a String.
// If it isn't, then all devices will be removed when linking to Google Home
name: "${deviceType.name}.devices" as String,
type: "capability.${deviceType.type}",
title: "${deviceType.display} devices",
multiple: true
)
}
}
section {
if (allDeviceTypes) {
def deviceTypeOptions = allDeviceTypes.collectEntries { deviceType ->
[deviceType.name, deviceType.display]
}
input(
name: "deviceTypeToEdit",
title: "Edit Device Type",
description: "Select a device type to edit...",
width: 6,
type: "enum",
options: deviceTypeOptions,
submitOnChange: true
)
input(
name: "deviceTypeToDelete",
title: "Delete Device Type",
description: "Select a device type to delete...",
width: 6,
type: "enum",
options: deviceTypeOptions,
submitOnChange: true
)
}
href(title: "Define new device type", description: "", style: "page", page: "deviceTypePreferences")
}
if (!hubVersionLessThan("2.3.4.115")) {
section("Home Graph Integration") {
// codenarc-disable LineLength
paragraph(
'''\
Follow these steps to enable Google Home Graph Integration:
1) Enable Google Home Graph API at https://console.developers.google.com/apis/api/homegraph.googleapis.com/overview
2) Create a Service Account with Role='Service Account Token Creator' at https://console.cloud.google.com/apis/credentials/serviceaccountkey
3) From Service Accounts, go to Keys -> Add Key -> Create new key -> JSON and save to disk
4) Paste contents of the file in Google Service Account Authorization below\
'''.stripIndent()
)
// codenarc-enable LineLength
input(
name: "googleServiceAccountJSON",
title: "Google Service Account Authorization",
type: "password",
submitOnChange: true
)
if (settings.googleServiceAccountJSON) {
input(
name: "reportState",
title: "Push device events to Google",
type: "bool",
defaultValue: true
)
}
}
}
section("Global PIN Codes") {
globalPinCodes?.pinCodes?.each { pinCode ->
input(
name: "GlobalPinCodes.pin.${pinCode.id}.name",
title: "PIN Code Name",
type: "text",
required: true,
width: 6
)
input(
name: "GlobalPinCodes.pin.${pinCode.id}.value",
title: "PIN Code Value",
type: "password",
required: true,
width: 5
)
input(
name: "deletePin:GlobalPinCodes.pin.${pinCode.id}",
title: "X",
type: "button",
width: 1
)
}
input(
name: "addPin:GlobalPinCodes",
title: "Add PIN Code",
type: "button"
)
}
section {
input(
name: "debugLogging",
title: "Enable Debug Logging",
type: "bool",
defaultValue: false
)
}
}
}
@SuppressWarnings('MethodSize')
def deviceTypePreferences(deviceType) {
state.remove("currentlyEditingDeviceTrait")
if (deviceType == null) {
deviceType = deviceTypeFromSettings(state.currentlyEditingDeviceType) // codenarc-disable-line NoScriptBindings
}
if (settings.deviceTraitToAdd != null) {
def toAdd = settings.deviceTraitToAdd
app.removeSetting("deviceTraitToAdd")
def traitName = "${deviceType.name}.traits.${toAdd}"
addTraitToDeviceTypeState(deviceType.name, toAdd)
return deviceTraitPreferences([name: traitName])
}
if (state.pinToDelete) {
deleteDeviceTypePin(deviceType, state.pinToDelete)
state.remove("pinToDelete")
}
return dynamicPage(name: "deviceTypePreferences", title: "Device Type Definition", nextPage: "mainPreferences") {
def devicePropertyName = deviceType != null ? deviceType.name : "deviceTypes.${state.nextDeviceTypeIndex++}"
state.currentlyEditingDeviceType = devicePropertyName
section {
input(
name: "${devicePropertyName}.display",
title: "Device type name",
type: "text",
required: true
)
input(
name: "${devicePropertyName}.type",
title: "Device type",
type: "enum",
options: HUBITAT_DEVICE_TYPES,
required: true
)
input(
name: "${devicePropertyName}.googleDeviceType",
title: "Google Home device type",
description: "The device type to report to Google Home",
type: "enum",
options: GOOGLE_DEVICE_TYPES,
required: true
)
}
def currentDeviceTraits = deviceType?.traits ?: [:]
section("Device Traits") {
if (deviceType != null) {
deviceType.traits.each { traitType, deviceTrait ->
href(
title: GOOGLE_DEVICE_TRAITS[traitType],
description: "",
style: "page",
page: "deviceTraitPreferences",
params: deviceTrait
)
}
}
def deviceTraitOptions = GOOGLE_DEVICE_TRAITS.findAll { key, value ->
!(key in currentDeviceTraits.keySet())
}
input(
name: "deviceTraitToAdd",
title: "Add Trait",
description: "Select a trait to add to this device...",
type: "enum",
options: deviceTraitOptions,
submitOnChange: true
)
}
def deviceTypeCommands = []
currentDeviceTraits.each { traitType, deviceTrait ->
deviceTypeCommands += deviceTrait.commands
}
if (deviceTypeCommands) {
section {
input(
name: "${devicePropertyName}.confirmCommands",
title: "The Google Assistant will ask for confirmation before performing these actions",
type: "enum",
options: deviceTypeCommands,
multiple: true
)
input(
name: "${devicePropertyName}.secureCommands",
title: "The Google Assistant will ask for a PIN code before performing these actions",
type: "enum",
options: deviceTypeCommands,
multiple: true,
submitOnChange: true
)
}
if (deviceType?.secureCommands || deviceType?.pinCodes) {
section {
input(
name: "${devicePropertyName}.useDevicePinCodes",
title: "Select to use device driver pincodes. " +
"Deselect to use Google Home Community app pincodes.",
type: "bool",
defaultValue: "false",
submitOnChange: true
)
}
if (deviceType?.useDevicePinCodes == true) {
// device attribute is set to use device driver pincodes
section("PIN Codes (Device Driver)") {
input(
name: "${devicePropertyName}.pinCodeAttribute",
title: "Device pin code attribute",
type: "text",
defaultValue: "lockCodes",
required: true
)
input(
name: "${devicePropertyName}.pinCodeValue",
title: "Device pin code value",
type: "text",
defaultValue: "code",
required: true
)
}
} else {
// device attribute is set to use app pincodes
section("PIN Codes (Google Home Community)") {
deviceType.pinCodes.each { pinCode ->
input(
name: "${devicePropertyName}.pin.${pinCode.id}.name",
title: "PIN Code Name",
type: "text",
required: true,
width: 6
)
input(
name: "${devicePropertyName}.pin.${pinCode.id}.value",
title: "PIN Code Value",
type: "password",
required: true,
width: 5
)
input(
name: "deletePin:${devicePropertyName}.pin.${pinCode.id}",
title: "X",
type: "button",
width: 1
)
}
if (deviceType?.secureCommands) {
input(
name: "addPin:${devicePropertyName}",
title: "Add PIN Code",
type: "button"
)
}
}
}
}
}
}
}
def deviceTypeDelete(deviceType) {
return dynamicPage(name: "deviceTypeDelete", title: "Device Type Deleted", nextPage: "mainPreferences") {
LOGGER.debug("Deleting device type ${deviceType.display}")
app.removeSetting("${deviceType.name}.display")
app.removeSetting("${deviceType.name}.type")
app.removeSetting("${deviceType.name}.googleDeviceType")
app.removeSetting("${deviceType.name}.devices")
app.removeSetting("${deviceType.name}.confirmCommands")
app.removeSetting("${deviceType.name}.secureCommands")
app.removeSetting("${deviceType.name}.useDevicePinCodes")
app.removeSetting("${deviceType.name}.pinCodeAttribute")
app.removeSetting("${deviceType.name}.pinCodeValue")
def pinCodeIds = deviceType.pinCodes*.id
pinCodeIds.each { pinCodeId -> deleteDeviceTypePin(deviceType, pinCodeId) }
app.removeSetting("${deviceType.name}.pinCodes")
deviceType.traits.each { traitType, deviceTrait -> deleteDeviceTrait(deviceTrait) }
state.deviceTraits.remove(deviceType.name as String)
section {
paragraph("The ${deviceType.display} device type was deleted")
}
}
}
@SuppressWarnings('NoScriptBindings') // False positive when assigning to method parameter
def deviceTraitPreferences(deviceTrait) {
if (deviceTrait == null) {
deviceTrait = deviceTypeTraitFromSettings(state.currentlyEditingDeviceTrait)
} else {
// re-load in case individual trait preferences functions have traits with submitOnChange: true
deviceTrait = deviceTypeTraitFromSettings(deviceTrait.name)
}
state.currentlyEditingDeviceTrait = deviceTrait.name
return dynamicPage(
name: "deviceTraitPreferences",
title: "Preferences For ${GOOGLE_DEVICE_TRAITS[deviceTrait.type]} Trait",
nextPage: "deviceTypePreferences",
) {
"deviceTraitPreferences_${deviceTrait.type}"(deviceTrait)
section {
href(
title: "Remove Device Trait",
description: "",
style: "page",
page: "deviceTraitDelete",
params: deviceTrait,
)
}
}
}
def deviceTraitDelete(deviceTrait) {
return dynamicPage(name: "deviceTraitDelete", title: "Device Trait Deleted", nextPage: "deviceTypePreferences") {
deleteDeviceTrait(deviceTrait)
section {
paragraph("The ${GOOGLE_DEVICE_TRAITS[deviceTrait.type]} trait was removed")
}
}
}
@SuppressWarnings(['MethodSize', 'UnusedPrivateMethod'])
private deviceTraitPreferences_ArmDisarm(deviceTrait) {
final HUBITAT_ALARM_LEVELS = [
"disarmed": "Disarm",
"armed home": "Home",
"armed night": "Night",
"armed away": "Away",
]
final HUBITAT_ALARM_COMMANDS = [
"disarmed": "disarm",
"armed home": "armHome",
"armed night": "armNight",
"armed away": "armAway",
]
final HUBITAT_ALARM_VALUES = [
"disarmed": "disarmed",
"armed home": "armed home",
"armed night": "armed night",
"armed away": "armed away",
]
section("Arm/Disarm Settings") {
input(
name: "${deviceTrait.name}.armedAttribute",
title: "Armed/Disarmed Attribute",
type: "text",
defaultValue: "securityKeypad",
required: true
)
input(
name: "${deviceTrait.name}.armLevelAttribute",
title: "Current Arm Level Attribute",
type: "text",
defaultValue: "securityKeypad",
required: true
)
input(
name: "${deviceTrait.name}.exitAllowanceAttribute",
title: "Exit Delay Value Attribute",
type: "text",
defaultValue: "exitAllowance",
required: true
)
input(
name: "${deviceTrait.name}.cancelCommand",
title: "Cancel Arming Command",
type: "text",
defaultValue: "disarm",
required: true
)
input(
name: "${deviceTrait.name}.armLevels",
title: "Supported Alarm Levels",
type: "enum",
options: HUBITAT_ALARM_LEVELS,
multiple: true,
required: true,
submitOnChange: true
)
deviceTrait.armLevels.each { armLevel ->
input(
name: "${deviceTrait.name}.armLevels.${armLevel.key}.googleNames",
title: "Google Home Level Names for ${HUBITAT_ALARM_LEVELS[armLevel.key]}",
description: "A comma-separated list of names that the Google Assistant will " +
"accept for this alarm setting",
type: "text",
required: "true",
defaultValue: HUBITAT_ALARM_LEVELS[armLevel.key]
)
input(
name: "${deviceTrait.name}.armCommands.${armLevel.key}.commandName",
title: "Hubitat Command for ${HUBITAT_ALARM_LEVELS[armLevel.key]}",
type: "text",
required: "true",
defaultValue: HUBITAT_ALARM_COMMANDS[armLevel.key]
)
input(
name: "${deviceTrait.name}.armValues.${armLevel.key}.value",
title: "Hubitat Value for ${HUBITAT_ALARM_LEVELS[armLevel.key]}",
type: "text",
required: "true",
defaultValue: HUBITAT_ALARM_VALUES[armLevel.key]
)
}
input(
name: "${deviceTrait.name}.returnUserIndexToDevice",
title: "Select to return the user index with the device command on a pincode match. " +
"Not all device drivers support this operation.",
type: "bool",
defaultValue: false,
submitOnChange: true
)
}
}
@SuppressWarnings('UnusedPrivateMethod')
private deviceTraitPreferences_Brightness(deviceTrait) {
section("Brightness Settings") {
input(
name: "${deviceTrait.name}.brightnessAttribute",
title: "Current Brightness Attribute",
type: "text",
defaultValue: "level",
required: true
)
input(
name: "${deviceTrait.name}.setBrightnessCommand",
title: "Set Brightness Command",
type: "text",
defaultValue: "setLevel",
required: true
)
}
}
@SuppressWarnings('UnusedPrivateMethod')
def deviceTraitPreferences_CameraStream(deviceTrait) {
section("Stream Camera") {
input(
name: "${deviceTrait.name}.cameraStreamURLAttribute",
title: "Camera Stream URL Attribute",
type: "text",
defaultValue: "streamURL",
required: true
)
input(
name: "${deviceTrait.name}.cameraSupportedProtocolsAttribute",
title: "Camera Stream Supported Protocols Attribute",
type: "text",
defaultValue: "supportedProtocols",
required: true
)
input(
name: "${deviceTrait.name}.cameraStreamProtocolAttribute",
title: "Camera Stream Protocol Attribute",
type: "text",
defaultValue: "streamProtocol",
required: true
)
input(
name: "${deviceTrait.name}.cameraStreamCommand",
title: "Start Camera Stream Command",
type: "text",
defaultValue: "on",
required: true
)
}
}
@SuppressWarnings(['MethodSize', 'UnusedPrivateMethod'])
private deviceTraitPreferences_ColorSetting(deviceTrait) {
section("Color Setting Preferences") {
input(
name: "${deviceTrait.name}.fullSpectrum",
title: "Full-Spectrum Color Control",
type: "bool",
required: true,
submitOnChange: true
)
if (deviceTrait.fullSpectrum) {
input(
name: "${deviceTrait.name}.hueAttribute",
title: "Hue Attribute",
type: "text",
defaultValue: "hue",
required: true
)
input(
name: "${deviceTrait.name}.saturationAttribute",
title: "Saturation Attribute",
type: "text",
defaultValue: "saturation",
required: true
)
input(
name: "${deviceTrait.name}.levelAttribute",
title: "Level Attribute",
type: "text",
defaultValue: "level",
required: true
)
input(
name: "${deviceTrait.name}.setColorCommand",
title: "Set Color Command",
type: "text",
defaultValue: "setColor",
required: true
)
}
input(
name: "${deviceTrait.name}.colorTemperature",
title: "Color Temperature Control",
type: "bool",
required: true,
submitOnChange: true
)
if (deviceTrait.colorTemperature) {
input(
name: "${deviceTrait.name}.colorTemperature.min",
title: "Minimum Color Temperature",
type: "number",
defaultValue: 2200,
required: true
)
input(
name: "${deviceTrait.name}.colorTemperature.max",
title: "Maximum Color Temperature",
type: "number",
defaultValue: 6500,
required: true
)
input(
name: "${deviceTrait.name}.colorTemperatureAttribute",
title: "Color Temperature Attribute",
type: "text",
defaultValue: "colorTemperature",
required: true
)
input(
name: "${deviceTrait.name}.setColorTemperatureCommand",
title: "Set Color Temperature Command",
type: "text",
defaultValue: "setColorTemperature",
required: true
)
}
if (deviceTrait.fullSpectrum && deviceTrait.colorTemperature) {
input(
name: "${deviceTrait.name}.colorModeAttribute",
title: "Color Mode Attribute",
type: "text",
defaultValue: "colorMode",
required: true
)
input(
name: "${deviceTrait.name}.fullSpectrumModeValue",
title: "Full-Spectrum Mode Value",
type: "text",
defaultValue: "RGB",
required: true
)
input(
name: "${deviceTrait.name}.temperatureModeValue",
title: "Color Temperature Mode Value",
type: "text",
defaultValue: "CT",
required: true
)
}
}
}
@SuppressWarnings('UnusedPrivateMethod')
private deviceTraitPreferences_Dock(deviceTrait) {
section("Dock Settings") {
input(
name: "${deviceTrait.name}.dockAttribute",
title: "Dock Attribute",
type: "text",
defaultValue: "status",
required: true
)
input(
name: "${deviceTrait.name}.dockValue",
title: "Docked Value",
type: "text",
defaultValue: "docked",
required: true
)
input(
name: "${deviceTrait.name}.dockCommand",
title: "Dock Command",
type: "text",
defaultValue: "returnToDock",
required: true
)
}
}
@SuppressWarnings(['UnusedPrivateMethod', 'MethodSize'])
private deviceTraitPreferences_EnergyStorage(deviceTrait) {
final GOOGLE_ENERGY_STORAGE_DISTANCE_UNIT_FOR_UX = [
"KILOMETERS": "Kilometers",
"MILES": "Miles",
]
final GOOGLE_CAPACITY_UNITS = [
"SECONDS": "Seconds",
"MILES": "Miles",
"KILOMETERS": "Kilometers",
"PERCENTAGE": "Percentage",
"KILOWATT_HOURS": "Kilowatt Hours",
]
section("Energy Storage Settings") {
input(
name: "${deviceTrait.name}.isRechargeable",
title: "Rechargeable",
type: "bool",
defaultValue: false,
required: true,
submitOnChange: true
)
input(
name: "${deviceTrait.name}.capacityRemainingRawValue",
title: "Capacity Remaining Value",
type: "text",
defaultValue: "battery",
required: true
)
input(
name: "${deviceTrait.name}.capacityRemainingUnit",
title: "Capacity Remaining Unit",
type: "enum",
options: GOOGLE_CAPACITY_UNITS,
defaultValue: "PERCENTAGE",
multiple: false,
required: true,
submitOnChange: true
)
}
section(hideable: true, hidden: true, "Advanced Settings") {
input(
name: "${deviceTrait.name}.queryOnlyEnergyStorage",
title: "Query Only Energy Storage",
type: "bool",
defaultValue: true,
required: true,
submitOnChange: true
)
if (deviceTrait.queryOnlyEnergyStorage == false) {
input(
name: "${deviceTrait.name}.chargeCommand",
title: "Charge Command",
type: "text",
required: true
)
}
input(
name: "${deviceTrait.name}.capacityUntilFullRawValue",
title: "Capacity Until Full Value",
type: "text",
)
input(
name: "${deviceTrait.name}.capacityUntilFullUnit",
title: "Capacity Until Full Unit",
type: "enum",
options: GOOGLE_CAPACITY_UNITS,
multiple: false,
submitOnChange: true
)
input(
name: "${deviceTrait.name}.descriptiveCapacityRemainingAttribute",
title: "Descriptive Capacity Remaining",
type: "text",
)
input(
name: "${deviceTrait.name}.isChargingAttribute",
title: "Charging Attribute",
type: "text",
)
input(
name: "${deviceTrait.name}.chargingValue",
title: "Charging Value",
type: "text",
)
input(
name: "${deviceTrait.name}.isPluggedInAttribute",
title: "Plugged in Attribute",
type: "text",
)
input(
name: "${deviceTrait.name}.pluggedInValue",
title: "Plugged in Value",
type: "text",
)