-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
executable file
·128 lines (98 loc) · 4.29 KB
/
app.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
#!/usr/bin/env python
__author__ = 'phubbard'
__date__ = '7/23/15'
# see https://pythonspot.com/flask-and-great-looking-charts-using-chart-js/
import datetime
import logging
import os
from math import floor
from peewee import *
from flask import Flask, Markup, render_template, send_from_directory, make_response, jsonify
from config import *
from model import *
app = Flask(__name__)
log = logging.getLogger('raven-app')
def calc_stride(num_max, item_count):
if item_count <= num_max:
return 1
array_stride = int(floor(item_count / num_max))
return array_stride
# TODO average values instead of just decimating the array - want a true downsample
def get_todays_readings(num_final=100):
usage_vals = UsageDatum.select().where(UsageDatum.timestamp >= datetime.date.today())
array_stride = calc_stride(num_final, usage_vals.count())
decimated = usage_vals[::array_stride]
rc = []
for val in decimated:
rc.append({'x': val.timestamp, 'y': val.kW})
return rc
def get_todays_readings_relative(num_final=100):
# Pull all readings for today, but the times are seconds since midnight, for easier plotting
today = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
usage_vals = UsageDatum.select().where(UsageDatum.timestamp >= datetime.date.today())
# Decimate the array
array_stride = calc_stride(num_final, usage_vals.count())
decimated = usage_vals[::array_stride]
# Now convert each timestamp to relative, on a scale of 0 to 24 fractional hours in the day
# TODO List comprehension
rc = []
for datum in decimated:
tdiff = (datum.timestamp - today).total_seconds()
rc.append({'x': tdiff * (24.0 / 86400), 'y': datum.kW})
datum.timestamp = tdiff
return rc
def get_yesterdays_readings_relative(num_final=100):
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
# Cute trick from https://www.tutorialspoint.com/How-to-convert-date-to-datetime-in-Python
tzero = datetime.datetime.combine(yesterday, datetime.datetime.min.time())
usage_vals = UsageDatum.select().where(UsageDatum.timestamp >= yesterday, UsageDatum.timestamp < today)
array_stride = calc_stride(num_final, usage_vals.count())
decimated = usage_vals[::array_stride]
# Now convert each timestamp to relative
# TODO List comprehension
rc = []
for datum in decimated:
tdiff = (datum.timestamp - tzero).total_seconds()
rc.append({'x': tdiff * ( 24.0 / 86400), 'y': datum.kW})
return rc
def get_latest_reading():
val = UsageDatum.select().order_by(UsageDatum.timestamp.desc()).limit(1).get()
return val.kW
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
@app.route('/')
def rel_chart():
# Pull downsampled sets of data for today and yesterday
# TODO this is 4 SQL queries - rewrite for single query, this is a bottleneck
today_data = get_todays_readings_relative()
yd_data = get_yesterdays_readings_relative()
today_abs = get_todays_readings()
last = get_latest_reading()
if last > 0:
current = f'{last}W (consuming from grid)'
else:
current = f'{last}W (generating to grid)'
return render_template('chart.html', today=today_data, yesterday=yd_data, current=current, today_abs=today_abs)
@app.route('/latest')
def latest_value():
# API for gauge updates
return make_response(str(get_latest_reading()))
@app.route('/mini')
def mini_chart():
# Goal here is mobile-friendly dashboard - latest reading and a pre-scaled min/max display
val = get_latest_reading()
return render_template('mini.html', latest=val)
@app.route('/old')
def chart():
# Pull downsampled sets of data for today and yesterday
print('today')
labels, values = zip(*[(x.timestamp, x.kW) for x in get_todays_readings()])
print('yesterday')
y_labels, y_values = zip(*[(x.timestamp, x.kW) for x in get_yesterdays_readings()])
print('render')
return render_template('chart.html', values=values, labels=labels, yesterday_values=y_values, yesterday_labels=y_labels)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5050, debug=True)