-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathsimple-device-viewer.groovy
2280 lines (2037 loc) · 66.7 KB
/
simple-device-viewer.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
/**
* Simple Device Viewer v 2.5.2
*
* Author:
* Kevin LaFramboise (krlaframboise)
*
* Contributors:
* Tim Larson (codethug)
*
* URL to documentation:
* https://community.smartthings.com/t/release-simple-device-viewer/42481?u=krlaframboise
*
* Changelog:
*
* 2.5.2 (07/11/2017)
* - Added Threshold and Notification Settings for Power Meter devices (added by codethug)
* - Reduced timeouts by changing main screen to display capability page links regardless of whether or not there are devices with that capability.
* - Added timeout checking to ensure user is always able to open the application.
* - Added ranges for thresholds which will hopefull cause the negative sign to be displayed on iOS.
* - Fixed issue with not being able to set the thresholds to 0.
* - Removed default values from threshold settings and made application skip over thresholds that are empty.
*
* 2.5.1 (02/21/2017)
* - Optionally display device's online/offline status in the dashboard.
* - Optionally override last even threshold and send notifications for offline devices.
* - Fixed timeout problem with Display Settings screen.
*
* 2.4.1 (01/21/2017)
* - Switched to SmartThings last activity field and only use the device's event history and state history if the device activity is null.
* - Added Acceleration Sensor Capability
* - Added Dashboard Layout options for condensed and multiple columns.
* - Added setting that allows you to choose which one is used.
*
* 2.3.2 (01/09/2017)
* - Fixed attribute for valve capability.
*
* 2.3.1 (01/07/2017)
* - Fixed problem with All Devices - States screen.
*
* 2.3.0 (01/06/2017)
* - Added support for Energy Meter, Illuminance Measurement, Power Meter, Relative Humidity Measurement, Valve
* - Added abort to "All Device - States" to prevent timeout errors.
*
* 2.2.3 (09/21/2016)
* - Still having occassional timeouts so made it abort sooner,
* but run more often when it's not successful.
*
* 2.2.1 (09/19/2016)
* - Made the program detect potential timeout errors and
* abort before it times out and then pickup where it left
* off the next time it runs.
*
* 2.1 (09/13/2016)
* - Added Ask Alexa Notification Option.
* - Reversed order of Events screen.
* - Changed Sort By Value default settings to true.
* - Added 3 more icons for battery levels.
*
* 2.0.1 (09/02/2016)
* - Bug fix due to platform issue.
*
* 2.0 (08/09/2016)
* - Added Dashboard
* - Added exclude device option for all capabilities.
*
* 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.
*
*/
definition(
name: "Simple Device Viewer",
namespace: "krlaframboise",
author: "Kevin LaFramboise",
description: "Provides information about the state of the specified devices.",
category: "My Apps",
iconUrl: "https://raw.githubusercontent.com/krlaframboise/Resources/master/simple-device-viewer/simple-device-viewer-icon.png",
iconX2Url: "https://raw.githubusercontent.com/krlaframboise/Resources/master/simple-device-viewer/simple-device-viewer-icon-2x.png",
iconX3Url: "https://raw.githubusercontent.com/krlaframboise/Resources/master/simple-device-viewer/simple-device-viewer-icon-3x.png")
preferences {
page(name:"mainPage")
page(name:"capabilityPage")
page(name:"lastEventPage")
page(name:"refreshLastEventPage")
page(name:"toggleSwitchPage")
page(name:"devicesPage")
page(name:"displaySettingsPage")
page(name:"thresholdsPage")
page(name:"notificationsPage")
page(name:"pollingPage")
page(name:"otherSettingsPage")
page(name:"dashboardSettingsPage")
page(name:"enableDashboardPage")
page(name:"disableDashboardPage")
}
// Main Menu Page
def mainPage() {
dynamicPage(name:"mainPage", uninstall:true, install:true) {
if (getAllDevices().size() != 0) {
section() {
getDashboardHref()
}
}
section() {
if (getAllDevices().size() != 0) {
state.lastCapabilitySetting = null
getPageLink("lastEventLink",
"All Devices - Last Event",
"lastEventPage")
getCapabilityPageLink(null)
}
getSelectedCapabilitiesPageLinks()
}
section("Settings") {
getPageLink("devicesLink",
"Choose Devices",
"devicesPage")
getPageLink("displaySettingsLink",
"Display Settings",
"displaySettingsPage")
getPageLink("thresholdsLink",
"Threshold Settings",
"thresholdsPage")
getPageLink("notificationsLink",
"Notification Settings",
"notificationsPage")
getPageLink("pollingLink",
"Polling Settings",
"pollingPage")
getPageLink("otherSettingsLink",
"Other Settings",
"otherSettingsPage")
getPageLink("dashboardSettingsPageLink",
"Dashboard Settings",
"dashboardSettingsPage")
}
}
}
private getSelectedCapabilitiesPageLinks() {
def startTime = new Date().time
def aborted = false
def timeout = 5000
def selectedCaps = getSelectedCapabilitySettings(timeout)
if (new Date().time - startTime > timeout) {
aborted = true
}
selectedCaps.each {
getCapabilityPageLink(it)
}
if (aborted) {
paragraph "Unable to load items within the allowed time. Check the Choose Devices screen to make sure each device is only selected once. If that doesn't eliminate this message, try reducing the number of Capabilities selected in the Display Settings screen."
}
}
private getDashboardHref() {
if (!state.endpoint) {
href "enableDashboardPage", title: "Enable Dashboard", description: ""
}
else {
href "", title: "View Dashboard", style: "external", url: api_dashboardUrl()
}
}
// Page for choosing devices and which capabilities to use.
def devicesPage() {
dynamicPage(name:"devicesPage") {
section ("Choose Devices") {
paragraph "Select all the devices that you want to be able to view in this application.\n\nYou can use any of the fields below to select a device, but you only need to select each device once. Duplicates are automatically removed so selecting a device more than once won't hurt anything."
input "actuators", "capability.actuator",
title: "Which Actuators?",
multiple: true,
hideWhenEmpty: true,
required: false
input "sensors", "capability.sensor",
title: "Which Sensors?",
multiple: true,
hideWhenEmpty: true,
required: false
capabilitySettings().each {
input "${getPrefName(it)}Devices",
"capability.${getPrefType(it)}",
title: "Which ${getPluralName(it)}?",
multiple: true,
hideWhenEmpty: true,
required: false
}
}
}
}
def displaySettingsPage() {
dynamicPage(name:"displaySettingsPage") {
section ("Display Options") {
paragraph "All the capabilities supported by the selected devices are shown on the main screen by default, but this field allows you to limit the list to specific capabilities."
input "enabledCapabilities", "enum",
title: "Display Which Capabilities?",
multiple: true,
options: getCapabilitySettingNames(false),
required: false,
submitOnChange: true
}
section ("Device Capability Exclusions") {
paragraph "The capability pages display all the devices that support the capability by default, but these fields allow you to exclude devices from each page."
input "enabledExclusions", "enum",
title: "Enable Device Exclusions for Which Capabilities?",
multiple: true,
options: getCapabilitySettingNames(true),
required: false,
submitOnChange: true
if (settings?.enabledExclusions?.find { it == "Events" }) {
input "lastEventExcludedDevices",
"enum",
title: "Exclude these devices from the Last Events page:",
multiple: true,
required: false,
options:getExcludedDeviceOptions(null)
}
capabilitySettings().each { cap ->
if (settings?.enabledExclusions?.find { it == getPluralName(cap) }) {
input "${getPrefName(cap)}ExcludedDevices",
"enum",
title: "Exclude these devices from the ${getPluralName(cap)} page:",
multiple: true,
required: false,
options: getDisplayExcludedDeviceOptions(cap)
}
}
}
}
}
private getDisplayExcludedDeviceOptions(cap) {
def devices = []
getDevicesByCapability(getCapabilityName(cap)).each {
if (deviceMatchesSharedCapability(it, cap)) {
devices << it.displayName
}
}
return devices?.sort()
}
// Page for defining thresholds used for icons and notifications
def thresholdsPage() {
dynamicPage(name:"thresholdsPage") {
section () {
paragraph "The thresholds specified on this page are used to determine icons in the SmartApp and when to send notifications."
}
section("Battery Thresholds") {
input "lowBatteryThreshold", "number",
title: "Enter Low Battery %:",
multiple: false,
range:"0..100"
}
section("Temperature Thresholds") {
input "lowTempThreshold", "number",
title: "Enter Low Temperature:",
required: false,
range:"-200..200"
input "highTempThreshold", "number",
title: "Enter High Temperature:",
required: false,
range:"-200..200"
}
section("Power Thresholds") {
input "lowPowerThreshold", "number",
title: "Enter Low Power in Watts:",
required: false,
range:"0..100000"
input "highPowerThreshold", "number",
title: "Enter High Power in Watts:",
required: false,
range:"0..100000"
}
section("Last Event Thresholds") {
input "lastEventThreshold", "number",
title: "Last event should be within:",
required: false,
defaultValue: 7
input "lastEventThresholdUnit", "enum",
title: "Choose unit of time:",
required: false,
defaultValue: "days",
options: ["seconds", "minutes", "hours", "days"]
input "lastEventThresholdOverride", "bool",
title: "Override Last Event Threshold for Offline Devices?",
required: false,
defaultValue: false
}
}
}
// Page for SMS and Push notification settings
def notificationsPage() {
dynamicPage(name:"notificationsPage") {
section ("Notification Settings") {
paragraph "When notifications are enabled, notifications will be sent when the device value goes above or below the threshold specified in the Threshold Settings."
input "createAskAlexaMsg", "bool",
title: "Create Ask Alexa Message?",
required: false,
defaultValue: false
input "sendPush", "bool",
title: "Send Push Notifications?",
required: false
input("recipients", "contact", title: "Send notifications to") {
input "phone", "phone",
title: "Send text message to",
description: "Phone Number",
required: false
}
mode title: "Only send Notifications for specific mode(s)",
required: false
input "maxNotifications", "number",
title: "Enter maximum number of notifications to receive within 5 minutes:",
required: false
}
section ("Battery Notifications") {
input "batteryNotificationsEnabled", "bool",
title: "Send battery notifications?",
defaultValue: false,
required: false
input "batteryNotificationsRepeat", "number",
title: "Send repeat notifications every: (hours)",
defaultValue: 0,
required: false
input "batteryNotificationsExcluded", "enum",
title: "Exclude these devices from battery notifications:",
multiple: true,
required: false,
options: getExcludedDeviceOptions("Battery")
}
section ("Temperature Notifications") {
input "temperatureNotificationsEnabled", "bool",
title: "Send Temperature Notifications?",
defaultValue: false,
required: false
input "temperatureNotificationsRepeat", "number",
title: "Send repeat notifications every: (hours)",
defaultValue: 0,
required: false
input "temperatureNotificationsExcluded", "enum",
title: "Exclude these devices from temperature notifications:",
multiple: true,
required: false,
options: getExcludedDeviceOptions("Temperature Measurement")
}
section ("Power Notifications") {
input "powerNotificationsEnabled", "bool",
title: "Send Power Notifications?",
defaultValue: false,
required: false
input "powerNotificationsRepeat", "number",
title: "Send repeat notifications every: (hours)",
defaultValue: 0,
required: false
input "powerNotificationsExcluded", "enum",
title: "Exclude these devices from power notifications:",
multiple: true,
required: false,
options: getExcludedDeviceOptions("Power Meter")
}
section ("Last Event Notifications") {
input "lastEventNotificationsEnabled", "bool",
title: "Send Last Event notification?",
defaultValue: false,
required: false
input "lastEventNotificationsRepeat", "number",
title: "Send repeat notifications every: (hours)",
defaultValue: 0,
required: false
input "lastEventNotificationsExcluded", "enum",
title: "Exclude these devices from last event notifications:",
multiple: true,
required: false,
options: getExcludedDeviceOptions(null)
}
}
}
// Page for Polling settings
def pollingPage() {
dynamicPage(name:"pollingPage") {
section ("Polling Settings") {
paragraph "If you enable the polling feature, the devices that support the Polling Capability will be polled at a regular interval."
paragraph "Polling your devices too frequently can cause them to stop responding or miss other commands that get sent to it."
input "pollingEnabled", "bool",
title: "Polling Enabled",
defaultValue: false,
required: false
input "pollingInterval", "number",
title: "How often should the devices be polled? (minutes)\n(Must be between 5 and ${6 * 24 * 60})",
defaultValue: (4 * 60),
range: "5..${6 * 24 * 60}",
required: false
}
section("Polling Restrictions") {
input "pollingExcluded", "enum",
title: "Exclude these devices from Polling",
multiple: true,
required: false,
options: getExcludedDeviceOptions("Polling")
}
}
}
private getExcludedDeviceOptions(capabilityName) {
if (capabilityName) {
getDevicesByCapability(capabilityName).collect { it.displayName }?.sort()
}
else {
getAllDevices().collect { it.displayName }?.sort()
}
}
// Page for misc preferences.
def otherSettingsPage() {
dynamicPage(name:"otherSettingsPage") {
section ("Other Settings") {
label(name: "label",
title: "Assign a name",
required: false)
input "iconsEnabled", "bool",
title: "Display Device State Icons?",
defaultValue: true,
required: false
input "condensedViewEnabled", "bool",
title: "Condensed View Enabled?",
defaultValue: false,
required: false
}
section ("Sorting") {
input "batterySortByValue", "bool",
title: "Sort by Battery Value?",
defaultValue: true,
required: false
input "tempSortByValue", "bool",
title: "Sort by Measurement Value?",
defaultValue: true,
required: false
input "lastEventSortByValue", "bool",
title: "Sort by Last Event Value?",
defaultValue: true,
required: false
}
section ("Last Event Accuracy") {
input "checkHistoryThreshold", "number",
title: "Check History Threshold: (Hours)\n(This SmartApp uses the device's last activity field, but this setting allows you to specify the number of hours the last activity has to be behind before manually retrieving the last event from the device history.)",
defaultValue: 12,
range: "1..168",
required: false
input "lastEventAccuracy", "number",
title: "Accuracy Level (1-25)\n(Setting this to a higher number will improve the accuracy for devices that generate a lot of events, but if you're seeing timeout errors in Live Logging, you should set this to a lower number.)",
defaultValue: 8,
range: "1..25",
required: false
input "lastEventByStateEnabled", "bool",
title: "Advanced Last Event Check Enabled?\n(When enabled, the devices events and state changes are used to determine the most recent activity.)",
defaultValue: true,
required: false
}
section ("Logging") {
input "logging", "enum",
title: "Types of messages to log:",
multiple: true,
required: false,
defaultValue: ["debug", "info"],
options: ["debug", "info", "trace"]
}
section ("Resources") {
paragraph "If you want to be able to use different icons, fork krlaframboise's GitHub Resources repository and change this url to the forked path. If you do change this setting, make sure that the new location contains all the Required Files."
href "", title: "View Required Resource List",
style: "external",
url: "http://htmlpreview.github.com/?https://github.com/krlaframboise/Resources/blob/master/simple-device-viewer/required-resources.html"
input "resourcesUrl", "text",
title: "Resources Url:",
required: false,
defaultValue: getResourcesUrl()
}
section ("Scheduling") {
paragraph "Leave this field empty unless you're using an external timer to turn on a switch at regular intervals. If you select a switch, the application will check to see if notifications need to be sent when its turned on instead of using SmartThings scheduler to check every 5 minutes."
input "timerSwitch", "capability.switch",
title: "Select timer switch:",
required: false
}
}
}
def dashboardSettingsPage() {
dynamicPage(name:"dashboardSettingsPage") {
section ("Dashboard Settings") {
if (state.endpoint) {
log.info "Dashboard Url: ${api_dashboardUrl()}"
input "dashboardRefreshInterval", "number",
title: "Dashboard Refresh Interval: (60-86400 seconds)",
range: "60..86400",
defaultValue: 300,
required: false
input "dashboardDefaultView", "enum",
title: "Default View:",
required: false,
options: getCapabilitySettingNames(true)
input "dashboardMenuPosition", "enum",
title: "Menu Position:",
defaultValue: "Top of Page",
required: false,
options: ["Top of Page", "Bottom of Page"]
input "dashboardLayout", "enum",
title: "Layout:",
defaultValue: "Normal",
required: false,
options: ["Normal", "Condensed - 1 Column", "Condensed - 2 Column", "Condensed - 3 Column"]
input "displayOnlineOfflineStatus", "bool",
title: "Display Online/Offline Status:",
defaultValue: false,
required: false
input "customCSS", "text",
title:"Enter CSS rules that should be appended to the dashboard's CSS file.",
required: false
getPageLink("disableDashboardPageLink",
"Disable Dashboard",
"disableDashboardPage")
}
else {
getPageLink("enableDashboardPageLink",
"Enable Dashboard",
"enableDashboardPage")
}
}
}
}
private getPageLink(linkName, linkText, pageName, args=null) {
def map = [
name: "$linkName",
title: "$linkText",
description: "",
page: "$pageName",
required: false
]
if (args) {
map.params = args
}
href(map)
}
private disableDashboardPage() {
dynamicPage(name: "disableDashboardPage", title: "") {
section() {
if (state.endpoint) {
try {
revokeAccessToken()
}
catch (e) {
logDebug "Unable to revoke access token: $e"
}
state.endpoint = null
}
paragraph "The Dashboard has been disabled! Tap Done to continue"
}
}
}
private enableDashboardPage() {
dynamicPage(name: "enableDashboardPage", title: "") {
section() {
if (initializeAppEndpoint()) {
paragraph "The Dashboard is now enabled. Tap Done to continue"
}
else {
paragraph "Please go to your SmartThings IDE, select the My SmartApps section, click the 'Edit Properties' button of the Simple Device Viewer app, open the OAuth section and click the 'Enable OAuth in Smart App' button. Click the Update button to finish.\n\nOnce finished, tap Done and try again.", title: "Please enable OAuth for Simple Device Viewer", required: true, state: null
}
}
}
}
// Lists all devices and their last event times.
def lastEventPage() {
dynamicPage(name:"lastEventPage") {
section ("Time Since Last Event") {
href(
name: "refreshLastEventLink",
title: "Refresh Data",
description: "${getRefreshLastEventLinkDescription()}",
page: "refreshLastEventPage",
required: false
)
def items = getAllDeviceLastEventListItems()?.unique()
if (settings.lastEventSortByValue != false) {
items?.each { it.sortValue = (it.sortValue * -1) }
}
getParagraphs(items)
}
}
}
private getRefreshLastEventLinkDescription() {
def stateRefreshed = (state.stateCachedTime) ? getTimeSinceLastActivity(new Date().time - state.stateCachedTime) : "?"
def eventsRefreshed = (state.eventCachedTime) ? getTimeSinceLastActivity(new Date().time - state.eventCachedTime) : "?"
return "Events refreshed ${eventsRefreshed.toLowerCase()} ago.\nState refreshed ${stateRefreshed.toLowerCase()} ago."
}
def refreshLastEventPage() {
dynamicPage(name:"refreshLastEventPage") {
section () {
refreshDeviceActivityCache()
paragraph "Started refreshing last events, but this process could take up to a minute."
}
}
}
// Lists all devices supporting switch capability as links that can be used to toggle their state
def toggleSwitchPage(params) {
dynamicPage(name:"toggleSwitchPage") {
section () {
paragraph "Wait a few seconds before pressing Done to ensure that the previous page refreshes correctly."
if (params.deviceId) {
def device = params.deviceId ? getAllDevices().find { it.id == params.deviceId } : null
def newState = device?.currentSwitch == "off" ? "on" : "off"
paragraph toggleSwitch(device, newState)
}
else {
getDevicesByCapability("Switch").each {
paragraph toggleSwitch(it, "off")
}
}
}
}
}
private toggleSwitch(device, newState) {
if (device) {
if (newState == "on") {
device.on()
}
else {
device.off()
}
return "Turned ${device.displayName} ${newState.toUpperCase()}"
}
}
// Lists all devices and all the state of all their capabilities
def capabilityPage(params) {
dynamicPage(name:"capabilityPage") {
def capSetting = params.capabilitySetting ? params.capabilitySetting : state.lastCapabilitySetting
if (capSetting) {
state.lastCapabilitySetting = capSetting
section("${getPluralName(capSetting)}") {
if (capSetting.name in ["Switch","Light"]) {
href(
name: "allOffSwitchLink",
title: "Turn Off All ${getPluralName(capSetting)}",
description: "",
page: "toggleSwitchPage",
required: false
)
getSwitchToggleLinks(getDeviceCapabilityListItems(capSetting))
}
else {
getParagraphs(getDeviceCapabilityListItems(capSetting))
}
}
}
else {
getAllSelectedCapabilitiesSection()
}
}
}
private getAllSelectedCapabilitiesSection() {
section("All Selected Capabilities") {
def startTime = new Date().time
def timeout = 15000
def aborted = false
def capListItems = []
def selectedCapSettings = getSelectedCapabilitySettings(timeout)
getAllDevices().each {
if (new Date().time - startTime > timeout) {
aborted = true
}
else {
capListItems << getDeviceAllCapabilitiesListItem(selectedCapSettings, it)
}
}
if (aborted) {
paragraph "Unable to load the states of all devices within the allowed time. If you've selected a lot of devices and capabilities, you might not be able to use the 'All Devices - States' view."
}
if (capListItems) {
getParagraphs(capListItems)
}
}
}
private getSwitchToggleLinks(listItems) {
listItems.sort { it.sortValue }
return listItems.unique().each {
href(
image: it.image ? it.image : "",
name: "switchLink${it.deviceId}",
title: "${it.title}",
description: "",
page: "toggleSwitchPage",
required: false,
params: [deviceId: it.deviceId]
)
}
}
private getParagraphs(listItems) {
listItems.sort { it.sortValue }
if (!condensedViewEnabled) {
return listItems.unique().each {
it.image = it.image ? it.image : ""
paragraph image: "${it.image}", "${it.title}"
}
}
else {
def content = null
listItems.unique().each {
content = content ? content.concat("\n${it.title}") : "${it.title}"
}
if (content) {
paragraph "$content"
}
}
}
private getCapabilityPageLink(cap) {
return href(
name: cap ? "${getPrefName(cap)}Link" : "allDevicesLink",
title: cap ? "${getPluralName(cap)}" : "All Devices - States",
description: "",
page: "capabilityPage",
required: false,
params: [capabilitySetting: cap]
)
}
// Checks if any devices have the specificed capability
private devicesHaveCapability(name) {
return getAllDevices().find { it.hasCapability(name) } ? true : false
}
private getDevicesByCapability(name, excludeList=null) {
removeExcludedDevices(getAllDevices()
.findAll { it.hasCapability(name.toString()) }
.sort() { it.displayName.toLowerCase() }, excludeList)
}
private getDeviceAllCapabilitiesListItem(selectedCapSettings, device) {
def listItem = [
sortValue: device.displayName
]
selectedCapSettings.each {
if (device.hasCapability(getCapabilityName(it))) {
listItem.status = (listItem.status ? "${listItem.status}, " : "").concat(getDeviceCapabilityStatusItem(device, it).status)
}
}
listItem.title = getDeviceStatusTitle(device, listItem.status)
return listItem
}
private getDeviceCapabilityListItems(cap) {
def items = []
getDevicesByCapability(getCapabilityName(cap), settings["${getPrefName(cap)}ExcludedDevices"])?.each {
if (deviceMatchesSharedCapability(it, cap)) {
items << getDeviceCapabilityListItem(it, cap)
}
}
return items
}
private deviceMatchesSharedCapability(device, cap) {
if (cap.name in ["Switch", "Light"]) {
def isLight = (lightDevices?.find { it.id == device.id }) ? true : false
return ((cap.name == "Light") == isLight)
}
else {
return true
}
}
private getDeviceCapabilityListItem(device, cap) {
def listItem = getDeviceCapabilityStatusItem(device, cap)
listItem.deviceId = "${device.id}"
if (listItem.image && cap.imageOnly && !condensedViewEnabled) {
listItem.title = "${device.displayName}"
}
else {
listItem.title = "${getDeviceStatusTitle(device, listItem.status)}"
}
listItem
}
private getCapabilitySettingByPrefName(prefName) {
capabilitySettings().find { getPrefName(it) == prefName }
}
private getCapabilitySettingByPluralName(pluralName) {
capabilitySettings().find { getPluralName(it)?.toLowerCase() == pluralName?.toLowerCase()}
}
private getCapabilitySettingByName(name) {
capabilitySettings().find { it.name == name }
}
private getAllDeviceLastEventListItems() {
removeExcludedDevices(getAllDevices(), lastEventExcludedDevices)?.collect {
getDeviceLastEventListItem(it)
}
}
private getDeviceLastEventListItem(device) {
def now = new Date().time
def lastActivity = getDeviceLastActivity(device)
def lastEventTime = lastActivity?.time ?: 0
def listItem = [
value: lastEventTime ? now - lastEventTime : Long.MAX_VALUE,
status: lastEventTime ? "${getTimeSinceLastActivity(now - lastEventTime)}" : "N/A",
deviceId: device.deviceNetworkId
]
listItem.title = getDeviceStatusTitle(device, listItem.status)
listItem.sortValue = settings.lastEventSortByValue != false ? listItem.value : device.displayName
listItem.image = getLastEventImage(lastEventTime, device.status)
return listItem
}
private getDeviceLastActivity(device) {
def activity = getDeviceCache(device.deviceNetworkId)?.activity
if (activity?.size()) {
return activity.sort { it.time }.last()
}
}
/*There's currently a bug that limits the number
of events returned to 50 so this method loops
through the list until it finds one that has
a source containing "DEVICE".*/
private getDeviceLastDeviceEvent(device) {
def totalLoops = safeToInteger(settings.lastEventAccuracy, 1)
def startDate = new Date() - 7
def endDate = new Date()
def lastEvent
totalLoops = (totalLoops > 3) ? 3 : totalLoops // Limit to 3 due to event timeout problem.
for (int index= 0; index < totalLoops; index++) {
def events = device.eventsBetween(startDate, endDate, [max:50]).flatten()
if (events) {
lastEvent = events?.find { "${it.source}".startsWith("DEVICE") }
if (lastEvent?.date?.time) {
// Found an event with the correct source so stop checking.
index = totalLoops
}
else {
// Haven't found an event with the correct so move the
// end date so the next 50 events will be retrieved.
endDate = events.last()?.date
}
}
else {
// Checked all the events so stop checking.
index = totalLoops
}
}
if (lastEvent) {
return [
name: lastEvent.name,
value: lastEvent.value,
time: lastEvent.date.time,
type: "event"
]
}
}
private getDeviceLastStateChange(device) {
if (settings.lastEventByStateEnabled != false) {
def lastState
device.supportedAttributes.each {
def attributeState = device.currentState("$it")
if (attributeState) {
if (!lastState || lastState.date.time < attributeState.date.time) {
lastState = attributeState
}
}
}
if (lastState) {
return [
name: lastState.name,
value: lastState.value,
time: lastState.date?.time,
type: "state"
]
}
}
}
private getTimeSinceLastActivity(ms) {
if (ms < msSecond()) {
return "$ms MS"
}
else if (ms < msMinute()) {
return "${calculateTimeSince(ms, msSecond())} SECS"
}
else if (ms < msHour()) {
return "${calculateTimeSince(ms, msMinute())} MINS"
}
else if (ms < msDay()) {
return "${calculateTimeSince(ms, msHour())} HRS"
}
else {
return "${calculateTimeSince(ms, msDay())} DAYS"
}
}
private calculateTimeSince(ms, divisor) {
return "${((float)(ms / divisor)).round()}"
}
private String getDeviceStatusTitle(device, status) {
if (!status || status == "null") {
status = "N/A"
}
if (state.refreshingDashboard) {
return "${device.displayName}${getOnlineOfflineStatus(device.status)}"
}
else {
return "${status} -- ${device.displayName}"
}
}
private getOnlineOfflineStatus(deviceStatus) {
if (settings?.displayOnlineOfflineStatus && deviceStatus?.toLowerCase() in ["online", "offline"]) {
return " (${deviceStatus.toLowerCase()})"
}
else {
return ""
}
}
private getDeviceCapabilityStatusItem(device, cap) {
try {
return getCapabilityStatusItem(cap, device.displayName, device.currentValue(getAttributeName(cap)).toString())
}
catch (e) {
log.error "Device: ${device?.displayName} - Capability: $cap - Error: $e"
return [
image: "",
sortValue: device?.displayName,
value: "",
status: "N/A"
]
}
}
private getCapabilityStatusItem(cap, sortValue, value) {
def item = [
image: "",
sortValue: sortValue,
value: value
]
item.status = item.value
if ("${item.status}" != "null") {
if (item.status == getActiveState(cap) && !state.refreshingDashboard) {
item.status = "*${item.status}"
}
switch (cap.name) {