Merge pull request #30 from mattbk/threshold

Calculate how much the furnace is running
This commit is contained in:
mattbk
2017-11-24 22:54:25 -06:00
committed by GitHub
2 changed files with 151 additions and 126 deletions

View File

@ -58,123 +58,145 @@ app.debug = True # Make this False if you are no longer debugging
@app.route("/") @app.route("/")
def lab_temp(): def lab_temp():
import sys import sys
import Adafruit_DHT import Adafruit_DHT
humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 17) humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 17)
temperature = temperature * 9/5.0 + 32 temperature = temperature * 9/5.0 + 32
if humidity is not None and temperature is not None: if humidity is not None and temperature is not None:
return render_template("live.html",temp=temperature,hum=humidity) return render_template("live.html",temp=temperature,hum=humidity)
else: else:
return render_template("no_sensor.html") return render_template("no_sensor.html")
@app.route("/history", methods=['GET']) #Add date limits in the URL #Arguments: from=2015-03-04&to=2015-03-05 @app.route("/history", methods=['GET']) #Add date limits in the URL #Arguments: from=2015-03-04&to=2015-03-05
def history(): def history():
temperatures, humidities, timezone, from_date_str, to_date_str = get_records() temperatures, humidities, timezone, from_date_str, to_date_str, range_hours = get_records()
# Create new record tables so that datetimes are adjusted back to the user browser's time zone.
time_series_adjusted_temperatures = []
time_series_adjusted_humidities = []
time_series_temperature_values = []
time_series_humidity_values = []
for record in temperatures:
local_timedate_series = arrow.get(record[0], "YYYY-MM-DD HH:mm")
time_series_adjusted_temperatures.append(local_timedate_series.format('YYYY-MM-DD HH:mm'))
time_series_temperature_values.append(round(record[2],2))
for record in humidities:
local_timedate_series = arrow.get(record[0], "YYYY-MM-DD HH:mm")
time_series_adjusted_humidities.append(local_timedate_series.format('YYYY-MM-DD HH:mm')) #Best to pass datetime in text
#so that Plotly respects it
time_series_humidity_values.append(round(record[2],2))
# Create new record tables so that datetimes are adjusted back to the user browser's time zone. temp = Scatter(
time_series_adjusted_temperatures = [] x=time_series_adjusted_temperatures,
time_series_adjusted_humidities = [] y=time_series_temperature_values,
time_series_temperature_values = [] name='Temperature',
time_series_humidity_values = [] mode='lines',
line=Line(color='red')
)
hum = Scatter(
x=time_series_adjusted_humidities,
y=time_series_humidity_values,
name='Humidity',
line=Line(color='aqua')
)
for record in temperatures: data = Data([temp, hum])
local_timedate_series = arrow.get(record[0], "YYYY-MM-DD HH:mm")
time_series_adjusted_temperatures.append(local_timedate_series.format('YYYY-MM-DD HH:mm'))
time_series_temperature_values.append(round(record[2],2))
for record in humidities: layout = Layout(
local_timedate_series = arrow.get(record[0], "YYYY-MM-DD HH:mm") title="Temperature and Humidity",
time_series_adjusted_humidities.append(local_timedate_series.format('YYYY-MM-DD HH:mm')) #Best to pass datetime in text xaxis=XAxis(
#so that Plotly respects it type='date',
time_series_humidity_values.append(round(record[2],2)) autorange=True
),
yaxis=YAxis(
title='Fahrenheit / Percent',
type='linear',
autorange=True
),
)
fig = Figure(data=data, layout=layout)
graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
temp = Scatter( ## Duration of significant heat increases
x=time_series_adjusted_temperatures, # Timestep from raw database values for temperature
y=time_series_temperature_values, timestep_minutes = (datetime.datetime.strptime(temperatures[1][0], "%Y-%m-%d %H:%M:%S")-datetime.datetime.strptime(temperatures[0][0], "%Y-%m-%d %H:%M:%S")).seconds/60
name='Temperature', # Calculate minutes for each streak
mode='lines', streak_minutes = streak_lengths(time_series_temperature_values)*timestep_minutes
line=Line(color='red')
)
hum = Scatter(
x=time_series_adjusted_humidities,
y=time_series_humidity_values,
name='Humidity',
line=Line(color='aqua')
)
data = Data([temp, hum]) # Send output to page
return render_template("history.html", timezone = timezone,
layout = Layout( graphJSON = graphJSON,
title="Temperature and Humidity", total_minutes = sum(streak_minutes),
xaxis=XAxis( range_hours = range_hours
type='date', )
autorange=True # Calculate streak lengths (https://stackoverflow.com/a/20614650/2152245)
), def streak_lengths(temps):
yaxis=YAxis( if len(temps) < 2:
title='Fahrenheit / Percent', return len(temps)
type='linear', else:
autorange=True start, streaks = -1, []
), for idx, (x, y) in enumerate(zip(temps, temps[1:])):
) if x > y:
streaks.append(idx - start)
fig = Figure(data=data, layout=layout) start = idx
graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) else:
streaks.append(idx - start + 1)
return render_template("history.html", timezone = timezone, long_streaks = [x for x in streaks if x > 3]
graphJSON = graphJSON, return long_streaks
)
def get_records(): def get_records():
from_date_str = request.args.get('from',time.strftime("%Y-%m-%d 00:00")) #Get the from date value from the URL from_date_str = request.args.get('from',time.strftime("%Y-%m-%d 00:00")) #Get the from date value from the URL
to_date_str = request.args.get('to',time.strftime("%Y-%m-%d %H:%M")) #Get the to date value from the URL to_date_str = request.args.get('to',time.strftime("%Y-%m-%d %H:%M")) #Get the to date value from the URL
timezone = request.args.get('timezone','Etc/UTC'); timezone = request.args.get('timezone','Etc/UTC');
range_h_form = request.args.get('range_h',''); #This will return a string, if field range_h exists in the request range_h_form = request.args.get('range_h',''); #This will return a string, if field range_h exists in the request
range_h_int = "nan" #initialise this variable with not a number range_h_int = "nan" #initialise this variable with not a number
print "REQUEST:" print "REQUEST:"
print request.args print request.args
try: try:
range_h_int = int(range_h_form) range_h_int = int(range_h_form)
except: except:
print "range_h_form not a number" print "range_h_form not a number"
print "Received from browser: %s, %s, %s, %s" % (from_date_str, to_date_str, timezone, range_h_int) print "Received from browser: %s, %s, %s, %s" % (from_date_str, to_date_str, timezone, range_h_int)
if not validate_date(from_date_str): # Validate date before sending it to the DB if not validate_date(from_date_str): # Validate date before sending it to the DB
from_date_str = time.strftime("%Y-%m-%d 00:00") from_date_str = time.strftime("%Y-%m-%d 00:00")
if not validate_date(to_date_str): if not validate_date(to_date_str):
to_date_str = time.strftime("%Y-%m-%d %H:%M") # Validate date before sending it to the DB to_date_str = time.strftime("%Y-%m-%d %H:%M") # Validate date before sending it to the DB
print '2. From: %s, to: %s, timezone: %s' % (from_date_str,to_date_str,timezone) print '2. From: %s, to: %s, timezone: %s' % (from_date_str,to_date_str,timezone)
# Create datetime object so that we can convert to UTC from the browser's local time # Create datetime object so that we can convert to UTC from the browser's local time
from_date_obj = datetime.datetime.strptime(from_date_str,'%Y-%m-%d %H:%M') from_date_obj = datetime.datetime.strptime(from_date_str,'%Y-%m-%d %H:%M')
to_date_obj = datetime.datetime.strptime(to_date_str,'%Y-%m-%d %H:%M') to_date_obj = datetime.datetime.strptime(to_date_str,'%Y-%m-%d %H:%M')
# If range_h is defined, we don't need the from and to times # If range_h is defined, we don't need the from and to times
if isinstance(range_h_int,int): if isinstance(range_h_int,int):
arrow_time_from = arrow.utcnow().replace(hours=-range_h_int) arrow_time_from = arrow.utcnow().replace(hours=-range_h_int)
arrow_time_to = arrow.utcnow() arrow_time_to = arrow.utcnow()
from_date_utc = arrow_time_from.strftime("%Y-%m-%d %H:%M") from_date_utc = arrow_time_from.strftime("%Y-%m-%d %H:%M")
to_date_utc = arrow_time_to.strftime("%Y-%m-%d %H:%M") to_date_utc = arrow_time_to.strftime("%Y-%m-%d %H:%M")
from_date_str = arrow_time_from.to(timezone).strftime("%Y-%m-%d %H:%M") from_date_str = arrow_time_from.to(timezone).strftime("%Y-%m-%d %H:%M")
to_date_str = arrow_time_to.to(timezone).strftime("%Y-%m-%d %H:%M") to_date_str = arrow_time_to.to(timezone).strftime("%Y-%m-%d %H:%M")
else: else:
#Convert datetimes to UTC so we can retrieve the appropriate records from the database #Convert datetimes to UTC so we can retrieve the appropriate records from the database
from_date_utc = arrow.get(from_date_obj, timezone).to('Etc/UTC').strftime("%Y-%m-%d %H:%M") from_date_utc = arrow.get(from_date_obj, timezone).to('Etc/UTC').strftime("%Y-%m-%d %H:%M")
to_date_utc = arrow.get(to_date_obj, timezone).to('Etc/UTC').strftime("%Y-%m-%d %H:%M") to_date_utc = arrow.get(to_date_obj, timezone).to('Etc/UTC').strftime("%Y-%m-%d %H:%M")
conn = sqlite3.connect('pi_temp.db') conn = sqlite3.connect('pi_temp.db')
curs = conn.cursor() curs = conn.cursor()
curs.execute("SELECT * FROM temperatures WHERE rDateTime BETWEEN ? AND ?", (from_date_utc.format('YYYY-MM-DD HH:mm'), to_date_utc.format('YYYY-MM-DD HH:mm'))) curs.execute("SELECT * FROM temperatures WHERE rDateTime BETWEEN ? AND ?", (from_date_utc.format('YYYY-MM-DD HH:mm'), to_date_utc.format('YYYY-MM-DD HH:mm')))
temperatures = curs.fetchall() temperatures = curs.fetchall()
curs.execute("SELECT * FROM humidities WHERE rDateTime BETWEEN ? AND ?", (from_date_utc.format('YYYY-MM-DD HH:mm'), to_date_utc.format('YYYY-MM-DD HH:mm'))) curs.execute("SELECT * FROM humidities WHERE rDateTime BETWEEN ? AND ?", (from_date_utc.format('YYYY-MM-DD HH:mm'), to_date_utc.format('YYYY-MM-DD HH:mm')))
humidities = curs.fetchall() humidities = curs.fetchall()
conn.close() conn.close()
return [temperatures, humidities, timezone, from_date_str, to_date_str] return [temperatures, humidities, timezone, from_date_str, to_date_str, range_h_int]
def validate_date(d): def validate_date(d):
try: try:

View File

@ -34,32 +34,32 @@
<body> <body>
<div class="container"> <div class="container">
<div class="row"> <div class="row">
<form id="datetime_range" action="/history" method="GET"> <form id="datetime_range" action="/history" method="GET">
<!-- <div class="row"> --> <!-- <div class="row"> -->
<div class="three columns"> <div class="three columns">
<label for="from">From date</label> <label for="from">From date</label>
<input class="u-full-width" id="datetimepicker1" type="text" value="{{from_date}}" name="from"> <input class="u-full-width" id="datetimepicker1" type="text" value="{{from_date}}" name="from">
</div> </div>
<!-- </div> --> <!-- </div> -->
<!-- <div class="row"> --> <!-- <div class="row"> -->
<div class="three columns"> <div class="three columns">
<label for="to">To date</label> <label for="to">To date</label>
<input class="u-full-width" id="datetimepicker2" type="text" value="{{to_date}}" name="to"> <input class="u-full-width" id="datetimepicker2" type="text" value="{{to_date}}" name="to">
</div> </div>
<!-- </div> --> <!-- </div> -->
<!-- <div class="row"> --> <!-- <div class="row"> -->
<div class="two columns"> <div class="two columns">
<input type="hidden" class="timezone" name="timezone" /> <input type="hidden" class="timezone" name="timezone" />
<input class="button-primary" type="submit" value="Submit" style="position:relative; top: 28px" id="submit_button" /> <input class="button-primary" type="submit" value="Submit" style="position:relative; top: 28px" id="submit_button" />
</div> </div>
<!-- </div> --> <!-- </div> -->
</form> </form>
</div> </div>
<div class="row"> <div class="row">
<div class="eleven columns"> <div class="eleven columns">
<div class="one column"> <div class="one column">
<a href="/">Live</a> <a href="/">Live</a>
</div> </div>
<form id="range_select" action = "/history" method="GET"> <form id="range_select" action = "/history" method="GET">
<input type="hidden" class="timezone" name="timezone" /> <input type="hidden" class="timezone" name="timezone" />
<div class="one column"> <div class="one column">
@ -77,6 +77,9 @@
</form> </form>
</div> </div>
</div> </div>
Furnace averaging {{ "%.2f" % (total_minutes/range_hours) }} minutes/hr ({{ total_minutes }} minutes total).
<div class='row' id='plotly-plot'></div> <div class='row' id='plotly-plot'></div>
</body> </body>