/
idle-node-refresher.groovy
217 lines (195 loc) · 8.08 KB
/
idle-node-refresher.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
//
// Copyright (c) 2020-2024, Denny Page
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Idle Node Refresher (Child application)
//
// Version 1.0.0 Initial release
// Version 1.0.1 Bug fix - incorrect use of idle interval instead of
// refresh interval for min sleep.
// Version 1.1.0 Add initialization function to ensure worker schedule
// isn't lost during reboot. Use seconds for calculations
// rather than milliseconds. Avoid runInMillis.
// Version 1.1.1 Delay actions on reboot
// Version 1.1.2 Change initialized function to systemStart subscription.
// Initialized isn't called for apps.
// Version 2.0.0 Code restructure and cleanup
// Version 2.0.1 Use capability.refresh for node selection
//
definition(
name: "Idle Node Refresher",
namespace: "cococafe",
author: "Denny Page",
description: "Refresh idle nodes in the network",
category: "Utility",
importUrl: "https://raw.githubusercontent.com/dennypage/hubitat/master/applications/idle-node-refresher/idle-node-refresher.groovy",
parent: "cococafe:Idle Node Refreshers",
iconUrl: "",
iconX2Url: "",
iconX3Url: ""
)
preferences
{
page(name: "configPage")
}
def configPage() {
dynamicPage(name: "", title: "Idle Node Refresher", install: true, uninstall: true, refreshInterval: 0)
{
section("")
{
input "name", "text", title: "<b>Refresher name</b>", multiple: false, required: true
}
section("")
{
paragraph "<b>Nodes to be monitored</b>: The nodes to be monitored and refreshed when idle. " +
"Selected nodes must have a refresh() command."
input "nodes", "capability.refresh", title: "Nodes to be monitored", multiple: true, required: true
}
section("")
{
paragraph "<b>Inactivity Idle Hours</b>: The number of hours of inactivity before a node " +
"is considered idle. A reasonable value for this is 24 (1 day) or greater. The " +
"minimum value is 1."
input "idleHours", "number", title: "Inactivity Idle Hours", required: true, defaultValue: 25
}
section("")
{
paragraph "<b>Refresh Interval Minutes</b>: The minimum number of minutes between idle " +
"node refreshes. Only one node will be refreshed per interval. A reasonable " +
"value for this is 5 or greater. The minimum value is 2."
input "refreshMinutes", "number", title: "Refresh Interval Minutes", required: true, defaultValue: 10
}
section("")
{
paragraph "<b>Refresh Switch</b>: If this option is enabled and the device being " +
"refreshed has Switch capability, one minute after calling refresh() on the device " +
"we will read the current value of the switch and call on() or off() as appropriate " +
"to refresh the current state. The advantage of refreshing switch state is that it " +
"will trigger Z-Wave Plus devices to update their route if appropriate. The " +
"disadvantage of switch refresh is additional network traffic. Additionally, if the " +
"state in the driver is stale due to prior communication issues, it could result in " +
"the switch mysteriously turning on or off."
input "refreshSwitch", "bool", title: "Refresh switch state (on/off)", defaultValue: false
}
}
}
void installed() {
app.updateLabel(name)
updateLastCache()
updateSortedIndex()
runIn(1, refreshNode)
}
void updated() {
subscribe(location, "systemStart", hubRestartHandler)
unschedule()
if (idleHours < 1) {
app.updateSetting("idleHours", 1)
log.warn "Input value for Inactivity Idle Hours too low: value changed to 1 hour"
}
if (refreshMinutes < 2) {
app.updateSetting("refreshMinutes", 2)
log.warn "Input value for Refresh Interval Minutes too low: value changed to 2 minutes"
}
installed()
}
void hubRestartHandler(evt) {
unschedule()
runIn(60, installed)
}
private Long lastNodeActivity(Integer node) {
// 2020-11-17 01:56:54+0000
return Date.parse("yyyy-MM-dd HH:mm:ssZ", "${nodes[node].getLastActivity()}").getTime() / 1000
}
void updateLastCache() {
state.lastCache = []
(0 .. nodes.size() - 1).each { node ->
state.lastCache[node] = lastNodeActivity(node)
}
}
void updateSortedIndex() {
List indexList = []
(0 .. nodes.size() - 1).each { node ->
indexList[node] = node
}
state.sortedIndex = indexList.sort { a, b -> state.lastCache[a] <=> state.lastCache[b] }
}
void switchRefresh(Map args) {
node = args.node
try {
String state = nodes[node].currentState("switch", true).value
log.info "Node ${nodes[node].getDisplayName()}: Refreshing switch state (${state})..."
if (state && state == "on") {
nodes[node].on()
}
else
{
nodes[node].off()
}
}
catch (e) {
log.warn "Node ${nodes[node].getDisplayName()}: ${e}"
}
}
void refreshNode() {
Long now = now() / 1000
Long idleSeconds = idleHours * 3600
Long refreshSeconds = refreshMinutes * 60
Long seconds
for (int i = 0; i < state.sortedIndex.size(); i++) {
node = state.sortedIndex[i]
seconds = now - state.lastCache[node]
if (seconds >= idleSeconds) {
// Update our cached value
state.lastCache[node] = lastNodeActivity(node)
seconds = (now - state.lastCache[node])
if (seconds >= idleSeconds) {
// Put the node at the end of the line
// NB: Even if refresh() does not update lastActivity, we won't refresh
// the node again until idleHours has expired
state.lastCache[node] = now
try {
Integer hours = seconds / 3600
log.info "Node ${nodes[node].getDisplayName()}: last activity was ${hours} hours ago. Refreshing..."
nodes[node].refresh()
}
catch (e) {
log.warn "Node ${nodes[node].getDisplayName()}: ${e}"
}
// Refresh switch state if requested
if (refreshSwitch && nodes[node].hasCapability("Switch")) {
runIn(60, switchRefresh, [data: [node: node]])
}
break
}
}
}
// Re-sort to integrate any activity cache changes
updateSortedIndex()
// Schedule our next refresh
seconds = idleSeconds - (now - state.lastCache[state.sortedIndex[0]])
if (seconds < refreshSeconds) seconds = refreshSeconds
runIn(seconds, refreshNode)
}