-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.py
executable file
·305 lines (270 loc) · 9.94 KB
/
graph.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
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
#!/usr/bin/env python3
import sqlite3
import configparser
from datetime import datetime
import rvWhisperUtils
import sys, getopt
color=['red', 'green', 'blue', 'orange', 'rgba(255,255,0,0.5)', 'purple']
def usage():
print("graph.py [-c <configFile>]")
print(" configFile - Defalts to rvwhisper.ini")
def main(argv):
configFile = 'rvwhisper.ini'
try:
opts, args = getopt.getopt(argv, "c:", ["config="])
except getopt.GetoptError as err:
print(err)
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-c", "--config"):
configFile = arg
config = configparser.ConfigParser()
config.read(configFile)
output = open(config.get('GRAPH', 'output', fallback='graph.html'), "w")
# Write out the HTML Header
output.write("""<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.5.0"></script>
<script src="https://cdn.jsdelivr.net/npm/hammerjs@2.0.8"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@1.1.1"></script>
<title>RVWhisper Graphs</title>
</head>
<body>
<canvas id="myChart"></canvas>
<script>
chartData = {
datasets: [
""")
graphPeriod = config.get('GRAPH', 'period', fallback="-30 days")
print("Graphing data over period: %s" % graphPeriod)
chartCount = 0
foundFields = []
for db in config['GRAPH']['db'].split(','):
title = config.get('GRAPH', db, fallback = db)
print("Reading %s (%s)" % (db, title))
# Open the Database
conn = None
try:
conn = sqlite3.connect(db)
except sqlite3.Error as e:
print(e)
# Retrieve the list of suitable fields for visualization
fields = []
c = conn.cursor();
try:
c.execute('SELECT fieldname,count(*) FROM data WHERE timestamp > strftime("%%s", datetime("now", "%s")) GROUP BY fieldname' % graphPeriod)
rows = c.fetchall()
for row in rows:
fields.append(row[0])
except sqlite3.Error as e:
print(e)
print("-> Found fields [%s]" % fields)
# For each field, retrieve the data for the last period
for field in fields:
if field in foundFields:
print("Already used this field...")
else:
foundFields.append(field)
try:
output.write("""{ type: 'line',
label: '%s - %s',
yAxisID: '%s',
showLine: true,
cubicInterpolationMode: 'default',
tension: 0.2,
radius: 0,
data: [""" % (title, field, field))
c.execute('SELECT timestamp,value FROM data WHERE timestamp > strftime("%%s", datetime("now", "%s")) AND fieldname = "%s" ORDER BY timestamp' % (graphPeriod, field))
rows = c.fetchall()
delta = int(config.get('GRAPH', field+"smooth", fallback = 0))
if delta > 0:
# Smoothing of this datatype is enabled.
print("Smoothing")
rows = rvWhisperUtils.smoothTimeseries(rows, delta)
dataString = []
if (field == "DoorState"):
# Special handling for doors.. Doors have "Just Opened", "Just Closed", and "Still Closed" and "Still Open"
# We'll convert that to a binary for easier rendering.
for row in rows:
if ("Closed" in row[1]):
dataString.append('{x: %s, y: 0}' % (row[0]))
else:
dataString.append('{x: %s, y: 1}' % (row[0]))
else:
for row in rows:
dataString.append('{x: %s, y: %s}' % (row[0], row[1]))
output.write(','.join(dataString))
output.write("],")
if (field == "DoorState"):
output.write("fill: 'origin',")
output.write("borderColor: '%s'," % color[chartCount])
output.write("backgroundColor: '%s'" % color[chartCount])
output.write("},")
chartCount += 1
except sqlite3.Error as e:
print(e)
# Close the database, if it was opened successfully
if(conn):
conn.close()
# Now, write out the weather
try:
conn = sqlite3.connect('weather.db')
c = conn.cursor()
c.execute('SELECT timestamp,temp,humidity,sunrise,sunset FROM weather WHERE timestamp > strftime("%%s", datetime("now", "%s")) ORDER BY timestamp' % (graphPeriod))
rows = c.fetchall()
# First write out the environmental temp
output.write("""{ type: 'line',
label: 'Weather - Temperature',
yAxisID: 'DegreesF',
showLine: true,
cubicInterpolationMode: 'default',
tension: 0.2,
radius: 0,
data: [""")
dataString = []
for row in rows:
dataString.append('{x: %s, y: %s}' % (row[0], row[1]))
output.write(','.join(dataString))
output.write("],")
output.write("borderColor: '#bbbbaa'," )
output.write("backgroundColor: '#bbbbaa'" )
output.write("},")
# Now write out the environmental Humidity
output.write("""{ type: 'line',
label: 'Weather - Humidity',
yAxisID: 'PercentHumidity',
showLine: true,
cubicInterpolationMode: 'default',
tension: 0.2,
radius: 0,
data: [""")
dataString = []
for row in rows:
dataString.append('{x: %s, y: %s}' % (row[0], row[2]))
output.write(','.join(dataString))
output.write("],")
output.write("borderColor: '#bbbbee'," )
output.write("backgroundColor: '#bbbbee'" )
output.write("}, ")
# Now write out the Sun state line
output.write("""{ type: 'line',
label: 'Sun',
yAxisID: 'DoorState',
showLine: true,
cubicInterpolationMode: 'default',
tension: 0.2,
radius: 0,
data: [""")
dataString = []
for row in rows:
tNow = int(row[0])
tSunrise = int(row[3])
tSunset = int(row[4])
# If the timestamp is between the Sunrise & Sunset times, assume the sun is up
# Now, since we'll be coloring _under_ the line, we need to invert the result
if tNow > tSunrise and tNow < tSunset:
# Sun is UP
dataString.append('{x: %s, y: 0}' % (row[0]))
else:
# Sun has SET
dataString.append('{x: %s, y: 1}' % (row[0]))
output.write(','.join(dataString))
output.write("],")
output.write("borderColor: 'rgba(64, 64, 64, 0.5)'," )
output.write("backgroundColor: 'rgba(64,64,64,0.5)'," )
output.write("fill: 'origin'" )
output.write("}")
conn.close()
except sqlite3.Error as e:
print(e)
# Write out the HTML Footer
output.write("""
] };
const config = {
type: "line",
data: chartData,
options: {
parsing: false,
interaction: {
mode: 'x',
axis: 'x',
intersect: false
},
plugins: {
zoom: {
pan: {
enabled: true,
mode: 'xy'
},
zoom: {
wheel: {
enabled: true
},
pinch: {
enabled: true
},
mode: 'x'
}
},
decimation: {
enabled: true,
algorithm: 'lttb',
samples: 200,
threshold: 500,
},
tooltip: {
callbacks: {
label: function(context) {
var d = new Date(0);
d.setUTCSeconds(context.parsed.x);
var label = [d.toLocaleString()];
label.push(context.dataset.label + " = " + context.parsed.y);
return label;
}
}
}
},
scales: {""")
side = "left"
for field in foundFields:
output.write("""
%s: {
title: {
display: true,
text: '%s'
},"""% (field, field))
if (config.get(field, 'min', fallback = None)):
output.write("min: %s," % config.get(field, 'min'))
if (config.get(field, 'max', fallback = None)):
output.write("max: %s," % config.get(field, 'max'))
output.write('position: "%s"' % side)
if (side == "left"):
side = "right"
else:
side = "left"
output.write("},")
output.write("""
x: {
type: 'linear',
ticks: {
callback: function(value, index, values) {
var d = new Date(0);
d.setUTCSeconds(value);
return d.toLocaleString();
}
}
}
}
}
};
var myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
</body>
</html>""")
output.close()
if __name__ == "__main__":
main(sys.argv[1:])