-
Notifications
You must be signed in to change notification settings - Fork 0
/
moisture.py
58 lines (51 loc) · 2.08 KB
/
moisture.py
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
from twisted.internet.task import LoopingCall
import rrdtool
SAMPLE_PERIOD = 300 # Every 5 minutes
RRD_NAME = "moisture.rrd"
class MoistureSampler(object):
"""
An instance of this class samples, records, and reports moisture readings.
"""
def __init__(self, device, sensorRegister):
self.device = device
self.sensorRegister = sensorRegister
self.sampleLoop = LoopingCall(self.sampleAndLog)
self.sampleLoop.start(SAMPLE_PERIOD, now=False)
self.checkRRD()
def checkRRD(self):
"""
Checks for RRD_NAME, creating it if necessary.
"""
import os
try:
os.stat(RRD_NAME)
except OSError:
self.createRRD()
def createRRD(self):
"""
Creates an RRD with these RRAs:
Hourly (all 12 readings)
Daily
Weekly
Monthly (6-hour summaries)
Yearly
Note: Sensor range is 0-1.8 V
"""
print "Creating database", RRD_NAME
rrdtool.create(RRD_NAME,
"--step", str(SAMPLE_PERIOD),
"DS:moisture:GAUGE:%s:0:1.8" % (str(2*SAMPLE_PERIOD),), # Sensor range is 0-1.8 V
"RRA:AVERAGE:0.5:1:12", # Hourly (all 12 readings)
"RRA:AVERAGE:0.5:12:24", # Daily
"RRA:AVERAGE:0.5:12:168", # Weekly
"RRA:AVERAGE:0.5:72:120", # Monthly (6-hour summaries)
"RRA:AVERAGE:0.5:288:365") # Yearly
def sampleAndLog(self):
reading = self.device.readRegister(self.sensorRegister)
rrdtool.update(RRD_NAME,
"N:" + str(reading))
def fetchAverage(self, startTime = None):
if startTime:
return rrdtool.fetch(RRD_NAME, "AVERAGE", "--start", startTime)
else:
return rrdtool.fetch(RRD_NAME, "AVERAGE")