+import collections
import datetime
+import itertools
import time
import configparser
import os
from flask import Flask, render_template, jsonify, request, abort, Response, make_response
import flask.json
-from flask_sqlalchemy import SQLAlchemy, inspect
-from sqlalchemy import func
+from flask_sqlalchemy import SQLAlchemy
+from sqlalchemy import func, inspect
MONTH_DE = [
'Jänner',
'Sonntag']
-# https://stackoverflow.com/a/37350445
-def sqlalchemy_model_to_dict(model):
- return {c.key: getattr(model, c.key)
- for c in inspect(model).mapper.column_attrs}
-
-
-class JSONEncoder(flask.json.JSONEncoder):
- def default(self, object):
- if isinstance(object, datetime.datetime):
- return object.isoformat()
- elif isinstance(object, db.Model):
- return sqlalchemy_model_to_dict(object)
- return super().default(object)
-
-
def parse_datetime(date_str):
return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S')
+def ntimes(it, n):
+ for v in it:
+ yield from itertools.repeat(v, n)
+
+
def get_sqlalchemy_database_uri(config):
user = config.get('database', 'user')
pwd = config.get('database', 'password')
mainsensor = config.get('webapp', 'mainsensor')
app = Flask(__name__)
-app.json_encoder = JSONEncoder
app.config['SQLALCHEMY_DATABASE_URI'] = get_sqlalchemy_database_uri(config)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
-db.reflect(app=app)
+with app.app_context():
+ db.reflect()
class Sensors(db.Model):
return query.all()
+def sensordata_to_xy(sensordata):
+ sensordata = list(sensordata)
+ x = np.array([d.timestamp for d in sensordata])
+ y = np.array([d.value for d in sensordata])
+ return x, y
+
+
def select_sensordata_grouped(sensor_id, sensor_type, begin, end):
# determine resolution (interval in seconds for data points)
resolution = calc_grouping_resolution(begin, end)
return query.all()
+def openweatherdata_to_xy(openweatherdata):
+ openweatherdata = list(openweatherdata)
+ x = np.array([d.datetime for d in openweatherdata])
+ y = np.array([d.temp for d in openweatherdata])
+ return x, y
+
+
def select_openweatherdata_grouped(cityid, begin, end):
# determine resolution (interval in seconds for data points)
resolution = calc_grouping_resolution(begin, end)
return result.value, result.timestamp
-def add_month(date):
- return (date + datetime.timedelta(days=42)).replace(day=1)
+def first_of_month(date, month):
+ date = date.replace(day=1)
+ if month == 0:
+ return date
+ if month == 1:
+ return (date + datetime.timedelta(days=42)).replace(day=1)
+ if month == -1:
+ return (date - datetime.timedelta(days=1)).replace(day=1)
+ assert False
@app.route('/api/<version>/sensors/')
"""Return all data for a specific sensor
URL parameters:
- begin=<datetime>, optional, format like "2018-05-19T21:07:53"
- end=<datetime>, optional, format like "2018-05-19T21:07:53"
- mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
- format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
+
+ * ``begin=<datetime>``, optional, format like ``2018-05-19T21:07:53``
+ * ``end=<datetime>``, optional, format like ``2018-05-19T21:07:53``
+ * ``mode=<full|consolidated>``, optional. return all rows (default) or with lower resolution (for charts)
+ * ``format=<default|c3>``, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
"""
result = sensordata(sensor_id=sensor_id)
return jsonify(result)
"""Return all data for a specific sensor type
URL parameters:
- begin=<datetime>, optional, format like "2018-05-19T21:07:53"
- end=<datetime>, optional, format like "2018-05-19T21:07:53"
- mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
- format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
+
+ * ``begin=<datetime>``, optional, format like ``2018-05-19T21:07:53``
+ * ``end=<datetime>``, optional, format like ``2018-05-19T21:07:53``
+ * ``mode=<full|consolidated>``, optional. return all rows (default) or with lower resolution (for charts)
+ * ``format=<default|c3>``, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
"""
result = sensordata(sensor_type=sensor_type)
return jsonify(result)
return jsonify({"value": value, "timestamp": timestamp})
-@app.route('/report/<int:year>-<int:month>')
+@app.route('/report/<int(fixed_digits=4):year>/<int(fixed_digits=2):month>')
def report(year, month):
+ """Report for given year (4 digits) and month (2 digits)
+ """
+ paper_size = (29.7 / 2.54, 21. / 2.54) # A4
begin = datetime.datetime(year, month, 1)
- end = add_month(begin)
- data = list(select_sensordata(mainsensor, 'Wassertemperatur', begin, end))
- x = np.array([d.timestamp for d in data])
- y = np.array([d.value for d in data])
+ end = first_of_month(begin, 1)
+
+ water_data = sensordata_to_xy(select_sensordata(mainsensor, 'Wassertemperatur', begin, end))
+ air_data = openweatherdata_to_xy(select_openweatherdata(cityid, begin, end))
+
+ report_times = [datetime.time(10), datetime.time(15)]
+ report_data = {'Wasser': water_data, 'Luft': air_data}
days_datetime = []
d = begin
while d < end:
days_datetime.append(d)
d = d + datetime.timedelta(1)
- days_str = [d.strftime('%d') for d in days_datetime]
binary_pdf = io.BytesIO()
with PdfPages(binary_pdf) as pdf:
- a4 = (21./2.54, 29.7/2.54)
- title = 'Seepark Wassertemperatur {} {}'.format(MONTH_DE[begin.month-1], begin.year)
- report_times = [datetime.time(10), datetime.time(15)]
-
- # table
- plt.figure(figsize=a4)
- columns = ['Datum']
- for t in report_times:
- columns.append('Wassertemperatur {} Uhr'.format(t.hour))
- cells = []
- for d in days_datetime:
- cell = ['{}, {}. {}'.format(DAY_OF_WEEK_DE[d.weekday()], d.day, MONTH_DE[d.month-1])]
- for t in report_times:
- report_datetime = datetime.datetime.combine(d.date(), t)
- closest_index = np.argmin(np.abs(x - report_datetime))
- if abs(x[closest_index] - report_datetime) > datetime.timedelta(hours=1):
- cell.append('N/A')
- else:
- value = y[closest_index]
- cell.append('{:.1f}° C'.format(value))
- cells.append(cell)
-
- ax = plt.gca()
- ax.table(cellText=cells, colLabels=columns,
- loc='upper left')
- ax.axis('off')
- plt.title(title)
- plt.subplots_adjust(left=0.1, right=0.9) # do not cut row labels
- pdf.savefig()
+ title = 'Seepark Obsteig {} {}'.format(MONTH_DE[begin.month-1], begin.year)
# graphic
- plt.figure(figsize=a4)
- plt.plot(x, y)
- plt.xticks(days_datetime, days_str, rotation='vertical')
- plt.xlabel('Tag')
- plt.ylabel('Temparatur in °C')
+ plt.figure(figsize=paper_size)
+ report_colors = []
+ for label, data in sorted(report_data.items(), reverse=True):
+ x, y = data
+ lines = plt.plot(x, y, label=label)
+ report_colors.append(lines[0].get_color())
+ plt.xticks(days_datetime, [''] * len(days_datetime))
+ plt.ylabel('Temperatur in °C')
plt.axis(xmin=begin, xmax=end)
+ plt.legend()
plt.grid()
plt.title(title)
+
+ # table
+ columns = []
+ for d in days_datetime:
+ columns.append('{}.'.format(d.day))
+ rows = []
+ for label in sorted(report_data.keys(), reverse=True):
+ for t in report_times:
+ rows.append('{:02d}:{:02d} {} °C'.format(t.hour, t.minute, label))
+ cells = []
+ for label, data in sorted(report_data.items(), reverse=True):
+ for t in report_times:
+ row_cells = []
+ x, y = data
+ for d in days_datetime:
+ report_datetime = datetime.datetime.combine(d.date(), t)
+ if len(x) == 0:
+ cell = 'N/A'
+ else:
+ closest_index = np.argmin(np.abs(x - report_datetime))
+ if abs(x[closest_index] - report_datetime) > datetime.timedelta(hours=1):
+ cell = 'N/A'
+ else:
+ value = y[closest_index]
+ cell = '{:.1f}'.format(value)
+ row_cells.append(cell)
+ cells.append(row_cells)
+ row_colors = list(ntimes(report_colors + ['w'], len(report_times)))
+ table = plt.table(cellText=cells, colLabels=columns, rowLabels=rows, rowColours=row_colors, loc='bottom')
+ table.scale(xscale=1, yscale=2)
+ plt.title(title)
+ plt.subplots_adjust(left=0.15, right=0.97, bottom=0.3) # do not cut row labels
pdf.savefig()
pdf_info = pdf.infodict()
pdf_info['Title'] = title
pdf_info['Author'] = 'Chrisu Jähnl'
- pdf_info['Subject'] = 'Wassertemperatur'
- pdf_info['Keywords'] = 'Seepark Wassertemperatur'
+ pdf_info['Subject'] = 'Temperaturen'
+ pdf_info['Keywords'] = 'Seepark Obsteig'
pdf_info['CreationDate'] = datetime.datetime.now()
pdf_info['ModDate'] = datetime.datetime.today()
def index():
airvalue, airtime = currentairtemperature(cityid)
watervalue, watertime = currentwatertemperature(mainsensor)
+ this_month = first_of_month(datetime.date.today(), 0)
+ last_month = first_of_month(this_month, -1)
return render_template(
'seepark_web.html',
watertime=watertime,
airvalue=airvalue,
airtime=airtime,
+ this_month=this_month,
+ last_month=last_month
)