Add a working SQL example to group measurements into time slots.
[chrisu/seepark.git] / web / seepark_web.py
1 from random import uniform
2 import datetime
3 import time
4 import configparser
5 import os
6 import sys
7 from collections import defaultdict
8 from flask import Flask, render_template, jsonify, request
9 import flask.json
10 from flask_sqlalchemy import SQLAlchemy, inspect
11
12
13 app_path = os.path.dirname(os.path.realpath(__file__))
14 lib_path = os.path.join(app_path, '..')
15 sys.path.append(lib_path)
16 from seeparklib.openweathermap import openweathermap_json, OpenWeatherMapError
17
18
19 # https://stackoverflow.com/a/37350445
20 def sqlalchemy_model_to_dict(model):
21     return {c.key: getattr(model, c.key)
22         for c in inspect(model).mapper.column_attrs}
23
24
25 class JSONEncoder(flask.json.JSONEncoder):
26     def default(self, object):
27         if isinstance(object, datetime.datetime):
28             return object.isoformat()
29         elif isinstance(object, db.Model):
30             return sqlalchemy_model_to_dict(object)
31         return super().default(object)
32
33
34 def parse_datetime(date_str):
35     return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S')
36
37
38 def get_sqlalchemy_database_uri(config):
39     user = config.get('database', 'user')
40     pwd = config.get('database', 'password')
41     host = config.get('database', 'hostname')
42     db = config.get('database', 'database')
43     return 'mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db)
44
45
46 config = configparser.ConfigParser()
47 config.read(os.environ['SEEPARKINI'])
48 apikey = config.get('openweathermap', 'apikey')
49 cityid = config.get('openweathermap', 'cityid')
50 mainsensor = config.get('temperature', 'mainsensor')
51
52 app = Flask(__name__)
53 app.json_encoder = JSONEncoder
54 app.config['SQLALCHEMY_DATABASE_URI'] = get_sqlalchemy_database_uri(config)
55 app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
56 db = SQLAlchemy(app)
57 db.reflect(app=app)
58
59
60 class Sensors(db.Model):
61     __tablename__ = 'sensors'
62
63
64 def select_sensordata(sensor_id, sensor_type, begin, end, mode):
65     query = Sensors.query
66     if sensor_id is not None:
67         query = query.filter(Sensors.sensor_id == sensor_id)
68     if sensor_type is not None:
69         query = query.filter(Sensors.value_type == sensor_type)
70     if begin is not None:
71         query = query.filter(Sensors.timestamp >= begin)
72     if end is not None:
73         query = query.filter(Sensors.timestamp <= end)
74     if mode == 'consolidated' and begin is None and end is None:
75         # copied from munin/master/_bin/munin-cgi-graph.in
76         # interval in seconds for data points
77         resolutions = dict(
78             day   =   300,
79             week  =  1800,
80             month =  7200,
81             year  = 86400,
82         )
83         duration = (end - begin).total_seconds()
84         day = 60 * 60 * 24
85         if duration < day:
86             resolution = resolutions['day']
87         elif duration < 7 * day:
88             resolution = resolutions['week']
89         elif duration < 31 * day:
90             resolution = resolutions['month']
91         else:
92             resolution = resolutions['year']
93         # TODO: filter out samples from 'result'
94         # something like 
95         # 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;
96     return query.all()
97
98
99 def convert_to_c3(result):
100     c3result = defaultdict(list)
101     for row in result:
102         c3result[row.sensor_id].append(row.value)
103         dt = row.timestamp.strftime('%Y-%m-%d %H:%M:%S')
104         c3result[row.sensor_id + '_x'].append(dt)
105     return c3result
106
107
108 def sensordata(sensor_id=None, sensor_type=None):
109     begin = request.args.get('begin', None, parse_datetime)
110     end = request.args.get('end', None, parse_datetime)
111     mode = request.args.get('mode', 'full')
112     format = request.args.get('format', 'default')
113
114     result = select_sensordata(sensor_id, sensor_type, begin, end, mode)
115
116     if format == 'c3':
117         return convert_to_c3(result)
118     return result
119
120
121 def currentairtemperature(apikey, cityid):
122     """Retruns the tuple temperature, datetime (as float, datetime) in case of success, otherwise None, None."""
123     try:
124         url, weatherdata = openweathermap_json(apikey, cityid)
125         return weatherdata['main']['temp'], datetime.datetime.fromtimestamp(weatherdata['dt'])
126     except OpenWeatherMapError:
127         return None, None
128
129
130 def currentwatertemperature(sensorid):
131     result = Sensors.query.filter_by(sensor_id=sensorid).order_by(Sensors.timestamp.desc()).first()
132     return result.value, result.timestamp
133
134
135 @app.route('/api/<version>/sensors/')
136 def sensors(version):
137     """List all sensors found in the database"""
138     result = db.session.query(Sensors.sensor_id, Sensors.sensor_name, Sensors.value_type).distinct().all()
139     return jsonify(result)
140
141
142 @app.route('/api/<version>/sensor/id/<sensor_id>')
143 def sensorid(version, sensor_id):
144     """Return all data for a specific sensor
145
146     URL parameters:
147     begin=<datetime>, optional, format like "2018-05-19T21:07:53"
148     end=<datetime>, optional, format like "2018-05-19T21:07:53"
149     mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
150     format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
151     """
152     result = sensordata(sensor_id=sensor_id)
153     return jsonify(result)
154
155
156 @app.route('/api/<version>/sensor/type/<sensor_type>')
157 def sensortype(version, sensor_type):
158     """Return all data for a specific sensor type
159
160     URL parameters:
161     begin=<datetime>, optional, format like "2018-05-19T21:07:53"
162     end=<datetime>, optional, format like "2018-05-19T21:07:53"
163     mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
164     format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
165     """
166     result = sensordata(sensor_type=sensor_type)
167     return jsonify(result)
168
169
170 @app.route('/data/', defaults={'timespan': 1})
171 @app.route("/data/<int:timespan>", methods=['GET'])
172 def data(timespan):
173     granularity = 5 * timespan               # (every) minute(s) per day
174     samples = 60/granularity * 24 * timespan # per hour over whole timespan
175     s4m   = []
176     s4m_x = []
177     s5m   = []
178     s5m_x = []
179     end   = time.time()
180     start = end - samples * granularity * 60
181
182     for i in range(int(samples)):
183         s4m.append(uniform(-10,30))
184         s5m.append(uniform(-10,30))
185         s4mt = uniform(start, end)
186         s5mt = uniform(start, end)
187         s4m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s4mt)))
188         s5m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s5mt)))
189
190     data = {
191         '0316a2193bff':   s4m,
192         '0316a2193bff_x': s4m_x,
193         '0316a21383ff':   s5m,
194         '0316a21383ff_x': s5m_x,
195         }
196
197     return jsonify(data)
198
199
200 @app.route("/")
201 def index():
202     airvalue, airtime     = currentairtemperature(apikey, cityid)
203     watervalue, watertime = currentwatertemperature(mainsensor)
204
205     return render_template(
206         'seepark_web.html',
207         apikey=apikey,
208         watervalue=watervalue,
209         watertime=watertime,
210         airvalue=airvalue,
211         airtime=airtime,
212     )