X-Git-Url: https://git.toastfreeware.priv.at/chrisu/seepark.git/blobdiff_plain/9e63b0e1f5dc5740df2fe78a6feaae5a0020733c..0f86faa33947d135ae246cca70082d32e89a9f5d:/web/seepark_web.py?ds=inline diff --git a/web/seepark_web.py b/web/seepark_web.py index c966321..00d122f 100644 --- a/web/seepark_web.py +++ b/web/seepark_web.py @@ -1,25 +1,26 @@ -from random import uniform import datetime import time import configparser import os import sys from collections import defaultdict -from flask import Flask, render_template, jsonify, request +from flask import Flask, render_template, jsonify, request, abort, Response import flask.json from flask_sqlalchemy import SQLAlchemy, inspect -app_path = os.path.dirname(os.path.realpath(__file__)) -lib_path = os.path.join(app_path, '..') -sys.path.append(lib_path) -from seeparklib.openweathermap import openweathermap_json, OpenWeatherMapError +# 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) @@ -39,7 +40,7 @@ config = configparser.ConfigParser() config.read(os.environ['SEEPARKINI']) apikey = config.get('openweathermap', 'apikey') cityid = config.get('openweathermap', 'cityid') -mainsensor = config.get('temperature', 'mainsensor') +mainsensor = config.get('webapp', 'mainsensor') app = Flask(__name__) app.json_encoder = JSONEncoder @@ -52,65 +53,129 @@ db.reflect(app=app) class Sensors(db.Model): __tablename__ = 'sensors' - # https://stackoverflow.com/a/37350445 - def to_dict(self): - return {c.key: getattr(self, c.key) - for c in inspect(self).mapper.column_attrs} -def select_sensordata(initial_where): - query = Sensors.query.filter(initial_where) - begin = request.args.get('begin', None, parse_datetime) - end = request.args.get('end', None, parse_datetime) +class OpenWeatherMap(db.Model): + __tablename__ = 'openweathermap' + + +def select_sensordata(sensor_id, sensor_type, begin, end, mode): + query = Sensors.query + if sensor_id is not None: + query = query.filter(Sensors.sensor_id == sensor_id) + if sensor_type is not None: + query = query.filter(Sensors.value_type == sensor_type) if begin is not None: query = query.filter(Sensors.timestamp >= begin) if end is not None: query = query.filter(Sensors.timestamp <= end) - result = query.all() + if mode == 'consolidated' and begin is not None and end is not None: + # copied from munin/master/_bin/munin-cgi-graph.in + # interval in seconds for data points + resolutions = dict( + day = 300, + week = 1800, + month = 7200, + year = 86400, + ) + duration = (end - begin).total_seconds() + day = 60 * 60 * 24 + if duration <= day: + resolution = resolutions['day'] + elif duration <= 7 * day: + resolution = resolutions['week'] + elif duration <= 31 * day: + resolution = resolutions['month'] + else: + resolution = resolutions['year'] + # TODO: filter out samples from 'result' + # something like + # select to_seconds(datetime) DIV (60*60*24) as interval_id, min(datetime), max(datetime), min(temp), avg(temp), max(temp), count(temp) from openweathermap group by interval_id order by interval_id; + return query.all() - mode = request.args.get('mode', 'full') - if mode == 'consolidated': - if begin is None or end is None: - pass + +def select_openweatherdata(cityid, begin, end, mode): + query = OpenWeatherMap.query.filter(OpenWeatherMap.cityid == cityid) + if begin is not None: + query = query.filter(OpenWeatherMap.datetime >= begin) + if end is not None: + query = query.filter(OpenWeatherMap.datetime <= end) + if mode == 'consolidated' and begin is not None and end is not None: + # copied from munin/master/_bin/munin-cgi-graph.in + # interval in seconds for data points + resolutions = dict( + day = 300, + week = 1800, + month = 7200, + year = 86400, + ) + duration = (end - begin).total_seconds() + day = 60 * 60 * 24 + if duration < day: + resolution = resolutions['day'] + elif duration < 7 * day: + resolution = resolutions['week'] + elif duration < 31 * day: + resolution = resolutions['month'] else: - # copied from munin/master/_bin/munin-cgi-graph.in - resolutions = dict( - day = 300, - week = 1800, - month = 7200, - year = 86400, - ) - duration = (end - begin).total_seconds() - day = 60 * 60 * 24 - if duration < day: - resolution = resolutions['day'] - elif duration < 7 * day: - resolution = resolutions['week'] - elif duration < 31 * day: - resolution = resolutions['month'] - else: - resolution = resolutions['year'] - # TODO: filter out samples from 'result' - # like loop over results and skip if timestamp(n+1)-timestamp(n), optional. return all rows (default) or with lower resolution (for charts) format=, optional. return result as returned by sqlalchemy (default) or formatted for c3.js """ - result = select_sensordata(Sensors.sensor_id == sensor_id) + result = sensordata(sensor_id=sensor_id) return jsonify(result) @@ -149,43 +214,27 @@ def sensortype(version, sensor_type): mode=, optional. return all rows (default) or with lower resolution (for charts) format=, optional. return result as returned by sqlalchemy (default) or formatted for c3.js """ - result = select_sensordata(Sensors.value_type == sensor_type) + result = sensordata(sensor_type=sensor_type) + return jsonify(result) + + +@app.route('/api//openweathermap/cities') +def openweathermap_cities(version): + """List all city IDs found in the database""" + result = db.session.query(OpenWeatherMap.cityid).distinct().all() return jsonify(result) -@app.route('/data/', defaults={'timespan': 1}) -@app.route("/data/", methods=['GET']) -def data(timespan): - granularity = 5 * timespan # (every) minute(s) per day - samples = 60/granularity * 24 * timespan # per hour over whole timespan - s4m = [] - s4m_x = [] - s5m = [] - s5m_x = [] - end = time.time() - start = end - samples * granularity * 60 - - for i in range(int(samples)): - s4m.append(uniform(-10,30)) - s5m.append(uniform(-10,30)) - s4mt = uniform(start, end) - s5mt = uniform(start, end) - s4m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s4mt))) - s5m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s5mt))) - - data = { - '0316a2193bff': s4m, - '0316a2193bff_x': s4m_x, - '0316a21383ff': s5m, - '0316a21383ff_x': s5m_x, - } - - return jsonify(data) +@app.route('/api//openweathermap/city/') +def openweathermap_city(version, cityid): + """List all data found for a city""" + result = openweathermapdata(cityid=cityid) + return jsonify(result) @app.route("/") def index(): - airvalue, airtime = currentairtemperature(apikey, cityid) + airvalue, airtime = currentairtemperature(cityid) watervalue, watertime = currentwatertemperature(mainsensor) return render_template(