forked from loverso-smartthings/googleDocsLogging
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle-sheets-logging.groovy
362 lines (311 loc) · 12.6 KB
/
google-sheets-logging.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
/*
* SmartThings example Code for Google sheets logging
*
* Copyright 2016 Charles Schwer
*
* 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: "${appName()}",
namespace: "cschwer",
author: "Charles Schwer",
description: "Log to Google Sheets",
category: "My Apps",
singleInstance: true,
iconUrl: "https://raw.githubusercontent.com/loverso-smartthings/googleDocsLogging/master/img/logoSheets.png",
iconX2Url: "https://raw.githubusercontent.com/loverso-smartthings/googleDocsLogging/master/img/[email protected]",
iconX3Url: "https://raw.githubusercontent.com/loverso-smartthings/googleDocsLogging/master/img/[email protected]")
preferences {
page(name: "startPage")
page(name: "parentPage")
page(name: "childStartPage")
}
def startPage() {
if (parent) {
childStartPage()
} else {
parentPage()
}
}
def parentPage() {
return dynamicPage(name: "parentPage", title: "", nextPage: "", install: true, uninstall: true) {
section("Create a new logging automation.") {
app(name: "childApps", appName: appName(), namespace: "cschwer", title: "Google Sheets Logging Automation", multiple: true)
}
section("About") {
paragraph "Version 1.3"
href url:"https://github.com/loverso-smartthings/googleDocsLogging", style:"embedded", required:false, title:"Installation instructions"
}
}
}
def childStartPage() {
return dynamicPage(name: "childStartPage", title: "", install: true, uninstall: true) {
section("Contact Sensors to Log") {
input "contacts", "capability.contactSensor", title: "Doors open/close", required: false, multiple: true
input "contactLogType", "enum", title: "Values to log", options: ["open/closed", "true/false", "1/0"], defaultValue: "open/closed", required: true, multiple: false
}
section("Motion Sensors to Log") {
input "motions", "capability.motionSensor", title: "Motion Sensors", required: false, multiple: true
input "motionLogType", "enum", title: "Values to log", options: ["active/inactive", "true/false", "1/0"], defaultValue: "active/inactive", required: true, multiple: false
}
section("Thermostat Settings") {
input "heatingSetPoints", "capability.thermostat", title: "Heating Setpoints", required: false, multiple: true
input "coolingSetPoints", "capability.thermostat", title: "Cooling Setpoints", required: false, multiple: true
input "thermOperatingStates", "capability.thermostat", title: "Operating States", required: false, multiple: true
}
section("Locks to Log") {
input "locks", "capability.lock", title: "Locks", multiple: true, required: false
input "lockLogType", "enum", title: "Values to log", options: ["locked/unlocked", "true/false", "1/0"], defaultValue: "locked/unlocked", required: true, multiple: false
}
section("Log Other Devices") {
input "temperatures", "capability.temperatureMeasurement", title: "Temperatures", required: false, multiple: true
input "humidities", "capability.relativeHumidityMeasurement", title: "Humidity Sensors", required: false, multiple: true
input "illuminances", "capability.illuminanceMeasurement", title: "Illuminance Sensors", required: false, multiple: true
input "presenceSensors", "capability.presenceSensor", title: "Presence Sensors", required: false, multiple: true
input "switches", "capability.switch", title: "Switches", required: false, multiple: true
input "dimmerSwitches", "capability.switchLevel", title: "Dimmer Switches", required: false, multiple: true
input "energyMeters", "capability.energyMeter", title: "Energy Meters", required: false, multiple: true
input "powerMeters", "capability.powerMeter", title: "Power Meters", required: false, multiple: true
input "batteries", "capability.battery", title: "Batteries", multiple: true, required: false
input "sensors", "capability.sensor", title: "Sensors", required: false, multiple: true
input "sensorAttributes", "text", title: "Sensor Attributes (comma delimited)", required: false
}
section ("Google Sheets") {
input "urlKey", "text", title: "Script URL key", required: true
input "appsDomain", "text", title: "Apps domainname", description: "Only set this if not using google.com", required: false
}
section ("Technical settings") {
input "queueTime", "enum", title:"Time to queue events before pushing to Google (in minutes)", options: ["0", "1", "5", "10", "15"], defaultValue:"5"
input "resetVals", "enum", title:"Reset the state values (queue, schedule, etc)", options: ["yes", "no"], defaultValue: "no"
}
section([mobileOnly:true], "Options") {
label(title: "Assign a name", required: true)
}
}
}
private def appName() {
return "${parent ? "Google Sheet Logging Automation" : "Google Sheets Logging"}"
}
def installed() {
log.debug "installed"
setOriginalState()
initialize()
}
def updated() {
log.debug "Updated"
unsubscribe()
initialize()
if (settings.resetVals == "yes") {
setOriginalState()
settings.resetVals = "no"
}
}
def initialize() {
if (parent) {
initChild()
} else {
initParent()
}
log.debug "End initialize()"
}
def initParent() {
log.debug "initParent()"
}
def initChild() {
log.debug "initChild()"
unsubscribe()
subscribe(locks, "lock", handleLockEvent)
subscribe(batteries, "battery", handleNumberEvent)
subscribe(contacts, "contact", handleContactEvent)
subscribe(motions, "motion", handleMotionEvent)
subscribe(heatingSetPoints, "heatingSetpoint", handleNumberEvent)
subscribe(coolingSetPoints, "coolingSetpoint", handleNumberEvent)
subscribe(thermOperatingStates, "thermostatOperatingState", handleStringEvent)
subscribe(temperatures, "temperature", handleNumberEvent)
subscribe(energyMeters, "energy", handleNumberEvent)
subscribe(powerMeters, "power", handleNumberEvent)
subscribe(humidities, "humidity", handleNumberEvent)
subscribe(illuminances, "illuminance", handleNumberEvent)
subscribe(presenceSensors, "presence", handleStringEvent)
subscribe(switches, "switch", handleStringEvent)
subscribe(dimmerSwitches, "switch", handleStringEvent)
subscribe(dimmerSwitches, "level", handleNumberEvent)
if (sensors != null && sensorAttributes != null) {
sensorAttributes.tokenize(',').each {
subscribe(sensors, it, handleStringEvent)
}
}
}
def setOriginalState() {
log.debug "Set original state"
unschedule()
atomicState.queue = [:]
atomicState.failureCount=0
atomicState.scheduled=false
atomicState.lastSchedule=0
}
def handleStringEvent(evt) {
log.debug "handling string event ${evt}"
if (settings.queueTime.toInteger() > 0) {
queueValue(evt) { it }
} else {
sendValue(evt) { it }
}
}
def handleNumberEvent(evt) {
if (settings.queueTime.toInteger() > 0) {
queueValue(evt) { it.toString() }
} else {
sendValue(evt) { it.toString() }
}
}
def handleContactEvent(evt) {
// default to open/close, the value of the event
def convertClosure = { it }
if (contactLogType == "true/false")
convertClosure = { it == "open" ? "true" : "false" }
else if ( contactLogType == "1/0")
convertClosure = { it == "open" ? "1" : "0" }
if (settings.queueTime.toInteger() > 0) {
queueValue(evt, convertClosure)
} else {
sendValue(evt, convertClosure)
}
}
def handleMotionEvent(evt) {
// default to active/inactive, the value of the event
def convertClosure = { it }
if (motionLogType == "true/false")
convertClosure = { it == "active" ? "true" : "false" }
else if (motionLogType == "1/0")
convertClosure = { it == "active" ? "1" : "0" }
if (settings.queueTime.toInteger() > 0) {
queueValue(evt, convertClosure)
} else {
sendValue(evt, convertClosure)
}
}
def handleLockEvent(evt) {
// default to locked/unlocked, the value of the event
def convertClosure = { it }
if (lockLogType == "true/false") {
convertClosure = { it == "locked" ? "true" : "false" }
} else if (lockLogType == "1/0") {
convertClosure = { it == "locked" ? "1" : "0" }
}
if (settings.queueTime.toInteger() > 0) {
queueValue(evt, convertClosure)
} else {
sendValue(evt, convertClosure)
}
}
private def baseUrl() {
String url = "https://script.google.com/"
if (settings.appsDomain != null) url += "a/"
url += "macros/"
if (settings.appsDomain != null) url += "${appsDomain}/"
url += "s/${urlKey}/exec?"
log.debug "url ["+url+"]"
return url
}
private sendValue(evt, Closure convert) {
def keyId = URLEncoder.encode(evt.displayName.trim()+ " " +evt.name)
def value = URLEncoder.encode(convert(evt.value))
log.debug "Logging to GoogleSheets ${keyId} = ${value}"
def url = baseUrl() + "${keyId}=${value}"
log.debug "${url}"
def putParams = [
uri: url
]
httpGet(putParams) { response ->
log.debug(response.status)
if (response.status != 200 ) {
log.debug "Google logging failed, status = ${response.status}"
}
}
}
private queueValue(evt, Closure convert) {
checkAndProcessQueue()
if ( evt?.value ) {
def keyId = URLEncoder.encode(evt.displayName.trim()+ " " +evt.name)
def value = URLEncoder.encode(convert(evt.value))
log.debug "Logging to queue ${keyId} = ${value}"
if ( atomicState.queue == [:] ) {
// format time in the same wasy as sheets does
def eventTime = URLEncoder.encode(evt.date.format( 'M/d/yyyy HH:mm:ss', location.timeZone ))
addToQueue("Time", eventTime)
}
addToQueue(keyId, value)
log.debug(atomicState.queue)
scheduleQueue()
}
}
private addToQueue(key, value) {
def queue = atomicState.queue
queue.put(key, value)
atomicState.queue = queue
}
private checkAndProcessQueue() {
if (atomicState.scheduled && ((now() - atomicState.lastSchedule) > (settings.queueTime.toInteger()*120000))) {
// if event has been queued for twice the amount of time it should be, then we are probably stuck
sendEvent(name: "scheduleFailure", value: now())
unschedule()
processQueue()
}
}
def scheduleQueue() {
if (atomicState.failureCount >= 3) {
log.debug "Too many failures, clearing queue"
sendEvent(name: "queueFailure", value: now())
resetState()
}
if (!atomicState.scheduled) {
runIn(settings.queueTime.toInteger() * 60, processQueue)
atomicState.scheduled=true
atomicState.lastSchedule=now()
}
}
private resetState() {
atomicState.queue = [:]
atomicState.failureCount=0
atomicState.scheduled=false
}
def processQueue() {
atomicState.scheduled=false
log.debug "Processing Queue"
if (atomicState.queue != [:]) {
def url = baseUrl()
for ( e in atomicState.queue ) { url+="${e.key}=${e.value}&" }
url = url[0..-2]
log.debug(url)
try {
def putParams = [
uri: url
]
httpGet(putParams) { response ->
log.debug(response.status)
if (response.status != 200 ) {
log.debug "Google logging failed, status = ${response.status}"
atomicState.failureCount = atomicState.failureCount+1
scheduleQueue()
} else {
log.debug "Google accepted event(s)"
resetState()
}
}
atomicState.queue = [:]
atomicState.failureCount=0
atomicState.scheduled=false
} catch(e) {
def errorInfo = "Error sending value: ${e}"
log.error errorInfo
}
}
}