-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhome-energy-logger.groovy
384 lines (334 loc) · 13.5 KB
/
home-energy-logger.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
/**
* Electricity Logger
*
* Copyright 2019 Leonard Budney
*
* 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, along with the following
* terms:
*
* 1. You may convey a work based on this program in accordance
* with section 5, provided that you retain the above notices.
*
* 2. You may convey verbatim copies of this program code as you
* receive it, in any medium, provided that you retain the above
* notices.
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
definition(
name: "Electricity Logger",
namespace: "budney",
author: "Leonard Budney",
description: "Logs electricity usage along with some other stuff, like the state of the thermostat.",
category: "My Apps",
iconUrl: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience.png",
iconX2Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/[email protected]",
iconX3Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/[email protected]")
preferences {
section("Home Energy Monitor") {
input "theMeter", "capability.energyMeter", required: true
}
section("Thermostat") {
input "theThermostat", "capability.thermostat", required: true
}
section("Thermometers") {
input "indoorTemp", "capability.temperatureMeasurement", required: false, title: "Indoors"
input "outdoorTemp", "capability.temperatureMeasurement", required: false, title: "Outdoors"
}
section("Hygrometers") {
input "indoorHumidity", "capability.relativeHumidityMeasurement", required: false, title: "Indoors"
input "outdoorHumidity", "capability.relativeHumidityMeasurement", required: false, title: "Outdoors"
}
section("Check Interval") {
input "interval", "number", required: true, title: "Minutes?", submitOnChange: true
}
section("Elasticsearch") {
input "indexPrefix", "text", required: true, title: "Prefix"
input "indexHost", "text", required: true, title: "Host:Port"
}
}
def installed() {
log.debug "Installed with settings: ${settings}"
initialize()
}
def updated() {
log.debug "Updated with settings: ${settings}"
unsubscribe()
initialize()
}
def initialize() {
// Subscribe to thermostat state changes
subscribe(theThermostat, "thermostatOperatingState.heating", hvacHandler)
subscribe(theThermostat, "thermostatOperatingState.idle", hvacHandler)
subscribe(theThermostat, "thermostatOperatingState.cooling", hvacHandler)
subscribe(theThermostat, "thermostatMode.off", hvacHandler)
// Subscribe to changes in the temperature setpoints
subscribe(theThermostat, "heatingSetpoint", heatingSetpointHandler)
subscribe(theThermostat, "coolingSetpoint", coolingSetpointHandler)
// Subscribe to temperature and humidity changes
subscribe(indoorTemp, "temperature", indoorTemperatureHandler)
subscribe(outdoorTemp, "temperature", outdoorTemperatureHandler)
subscribe(indoorHumidity, "humidity", indoorHumidityHandler)
subscribe(outdoorHumidity, "humidity", outdoorHumidityHandler)
// Subscribe to energy meter to detect updates
subscribe(theMeter, "energy", energyHandlerTotal)
subscribe(theMeter, "energy1", energyHandlerProbe1)
subscribe(theMeter, "energy2", energyHandlerProbe2)
// Subscribe to the power meter for more updates
subscribe(theMeter, "power", powerHandlerTotal)
subscribe(theMeter, "power1", powerHandlerProbe1)
subscribe(theMeter, "power2", powerHandlerProbe2)
}
// Refresh the energy meter. When it finishes, the subscribed attributes will cause
// the new reading to be logged.
def loggingLoop() {
logCurrentState()
runIn(60 * interval, loggingLoop)
}
// Store the latest data in elasticsearch
def logCurrentState() {
def indexName = indexName()
state.report['@timestamp'] = formatDate(new Date())
try {
def request = new physicalgraph.device.HubAction(
method: "POST",
path: "/$indexName/doc",
headers: [
"HOST": indexHost
],
body: state.report,
null,
[ callback: elasticsearchResponse ]
)
sendHubCommand(request)
}
catch (Exception e) {
log.error "Caught exception $e sending to elasticsearch"
}
}
// Derive the index name to store readings
String indexName() {
def prefix = indexPrefix
def datestamp = new Date().format("yyyy.MM.dd", TimeZone.getTimeZone('UTC'))
return "$prefix-$datestamp"
}
// Handler for changes to heating/cooling state
def hvacHandler(evt) {
log.info evt.descriptionText
def thermostat = evt.device
def newState = evt.stringValue
def timestamp = formatDate(evt.date)
// Update the report object with the new furnace state
state.report.hvac.heating.on = (newState == "heating") ? true : false
state.report.hvac.cooling.on = (newState == "cooling") ? true : false
state.report.hvac.timestamp = timestamp
}
def heatingSetpointHandler(evt) {
log.info evt.descriptionText
state.report.hvac.heating.setpoint = evt.value
}
def coolingSetpointHandler(evt) {
log.info evt.descriptionText
state.report.hvac.cooling.setpoint = evt.value
}
// Generic handler for changes in temperature and humidity
def climateHandler(evt, where) {
log.info evt.descriptionText
where.value = evt.value
where.timestamp = formatDate(evt.date)
log.debug "Updated climate value: ${where}"
}
// Stupid wrappers for the generic climate handler
def indoorTemperatureHandler(evt) { climateHandler(evt, state.report.climate.indoor.temperature) }
def indoorHumidityHandler(evt) { climateHandler(evt, state.report.climate.indoor.humidity) }
def outdoorTemperatureHandler(evt) { climateHandler(evt, state.report.climate.outdoor.temperature) }
def outdoorHumidityHandler(evt) { climateHandler(evt, state.report.climate.outdoor.humidity) }
// Update the report when there's a new energy reading
def energyHandler(evt, where) {
log.info evt.descriptionText
def timestamp = evt.date
def previousTimestamp = parseTimestamp(where.kwh.period_to)
double elapsed = evt.date.getTime() - previousTimestamp.getTime()
double currentEnergy = asDouble(evt.value)
double previousEnergy = asDouble(where.kwh.cumulative)
// Ignore updates that are milliseconds apart
if (elapsed < 10) {return}
// Ignore updates of 1 Watt-hour or less
if (currentEnergy - previousEnergy < 0.001) {return}
// Before overwriting the current state, log it to Elasticsearch
if (parseTimestamp(state.report['@timestamp']) < previousTimestamp) {
logCurrentState()
}
where.kwh = [
period_to: formatDate(timestamp),
period_from: formatDate(previousTimestamp),
period_seconds: elapsed / 1000,
cumulative: currentEnergy,
period_total: currentEnergy - previousEnergy,
per_month: (currentEnergy - previousEnergy) * 30 * 24 * 60 * 60 * 1000 / elapsed,
]
}
// Stupid wrappers for the generic energy handler
def energyHandlerTotal(evt) { energyHandler(evt, state.report.electricity.total) }
def energyHandlerProbe1(evt) { energyHandler(evt, state.report.electricity.probe1) }
def energyHandlerProbe2(evt) { energyHandler(evt, state.report.electricity.probe2) }
// Generic handler for new power readings
def powerHandler(evt, where) {
log.info evt.descriptionText
def timestamp = formatDate(evt.date)
def previousTimestamp = parseTimestamp(where.watts.timestamp)
double currentPower = asInt(evt.value)
double previousPower = asInt(where.watts.current)
double elapsed = evt.date.getTime() - previousTimestamp.getTime()
// Before overwriting the current state, log it to Elasticsearch
if (parseTimestamp(state.report['@timestamp']) < previousTimestamp) {
logCurrentState()
}
where.watts = [
timestamp: timestamp,
current: currentPower,
previous: previousPower,
period_average: (currentPower + previousPower) / 2,
]
}
// Stupid wrappers for the generic handler
def powerHandlerTotal(evt) { powerHandler(evt, state.report.electricity.total) }
def powerHandlerProbe1(evt) { powerHandler(evt, state.report.electricity.probe1) }
def powerHandlerProbe2(evt) { powerHandler(evt, state.report.electricity.probe2) }
// Construct the actual map of data to store in Elasticsearch
Map dataEntry(readings) {
def elapsed = readings.current.timestamp - readings.previous.timestamp
def probe1_ratio = asInt(readings.current.power1) / (asInt(readings.current.power1) + asInt(readings.current.power2))
def timestamp = formatDate(new Date(state.lastMeterReadingTimestamp))
def entry = [
"@timestamp": formatDate(new Date()),
electricity: [
timestamp: timestamp,
period_seconds: elapsed / 1000,
total: [
kwh: [
timestamp: timestamp,
cumulative: readings.current.energy,
period_total: readings.current.energy - readings.previous.energy,
per_month: (readings.current.energy - readings.previous.energy) * 30 * 24 * 60 * 60 * 1000 / elapsed,
],
watts: [
timestamp: timestamp,
current: readings.current.power,
previous: readings.previous.power,
period_average: (readings.current.energy - readings.previous.energy) * 1000 / ( elapsed / ( 1000 * 60 * 60 ) ),
],
],
probe1: [
kwh: [
timestamp: timestamp,
period_total: probe1_ratio * (readings.current.energy - readings.previous.energy),
per_month: probe1_ratio * (readings.current.energy - readings.previous.energy) * 30 * 24 * 60 * 60 * 1000 / elapsed,
],
watts: [
timestamp: timestamp,
current: readings.current.power1,
previous: readings.previous.power1,
period_average: probe1_ratio * (readings.current.energy - readings.previous.energy) * 1000 / ( elapsed / ( 1000 * 60 * 60 ) ),
],
],
probe2: [
kwh: [
timestamp: timestamp,
period_total: (1 - probe1_ratio) * (readings.current.energy - readings.previous.energy),
per_month: (1 - probe1_ratio) * (readings.current.energy - readings.previous.energy) * 30 * 24 * 60 * 60 * 1000 / elapsed,
],
watts: [
timestamp: timestamp,
current: readings.current.power2,
previous: readings.previous.power2,
period_average: (1 - probe1_ratio) * (readings.current.energy - readings.previous.energy) * 1000 / ( elapsed / ( 1000 * 60 * 60 ) ),
],
],
],
hvac: [
timestamp: timestamp,
heating: [
on: state.heatingState,
setpoint: theThermostat.currentValue("heatingSetpoint"),
],
cooling: [
on: state.coolingState,
setpoint: theThermostat.currentValue("coolingSetpoint"),
]
],
climate: [
indoor: [
temperature: [
value: state.indoorTemperature,
timestamp: timestamp,
],
humidity: [
value: state.indoorHumidity,
timestamp: timestamp,
]
],
outdoor: [
temperature: [
value: state.outdoorTemperature,
timestamp: timestamp,
],
humidity: [
value: state.outdoorHumidity,
timestamp: timestamp,
]
],
]
]
return entry
}
Integer asInt(value) {
if (!value) {
return value
}
try {
return value as Integer
}
catch (Exception e) {
log.error "Caught exception $e converting '$value' to integer"
return null
}
}
Double asDouble(value) {
if (!value) {
return value
}
try {
return value as Double
}
catch (Exception e) {
log.error "Caught exception $e converting '$value' to integer"
return null
}
}
void elasticsearchResponse(hubResponse) {
log.debug "hubResponse: status {$hubResponse.status}: {$hubResponse.json}"
}
Date parseTimestamp(str) {
def format = "yyyy-MM-dd'T'HH:mm:ss"
try { return Date.parse(format + "X", str) } catch (Exception e) {}
try { return Date.parse(format + ".SX", str) } catch (Exception e) {}
try { return Date.parse(format + ".SSX", str) } catch (Exception e) {}
try { return Date.parse(format + ".SSSX", str) }
catch (Exception e) {
throw e
}
}
String formatDate(Date date) {
return date.format("yyyy-MM-dd'T'HH:mm:ss.SSSX", TimeZone.getTimeZone('UTC'))
}