c19e9b92e177cfac69d57eadd6f9ba9cca5d0a6a
[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 mean(temperature) from sensors where ... group by mod(timestamp, resolution)
96         # func.avg(...)
97         #
98         # from https://stackoverflow.com/questions/4342370/grouping-into-interval-of-5-minutes-within-a-time-range
99         # SELECT
100         #    timestamp,  -- not sure about that
101         #        name,
102         #            count(b.name)
103         #            FROM time a, id 
104         #            WHERE …
105         #            GROUP BY 
106         #            UNIX_TIMESTAMP(timestamp) DIV 300, name
107     return query.all()
108
109
110 def convert_to_c3(result):
111     c3result = defaultdict(list)
112     for row in result:
113         c3result[row.sensor_id].append(row.value)
114         dt = row.timestamp.strftime('%Y-%m-%d %H:%M:%S')
115         c3result[row.sensor_id + '_x'].append(dt)
116     return c3result
117
118
119 def sensordata(sensor_id=None, sensor_type=None):
120     begin = request.args.get('begin', None, parse_datetime)
121     end = request.args.get('end', None, parse_datetime)
122     mode = request.args.get('mode', 'full')
123     format = request.args.get('format', 'default')
124
125     result = select_sensordata(sensor_id, sensor_type, begin, end, mode)
126
127     if format == 'c3':
128         return convert_to_c3(result)
129     return result
130
131
132 def currentairtemperature(apikey, cityid):
133     """Retruns the tuple temperature, datetime (as float, datetime) in case of success, otherwise None, None."""
134     try:
135         weatherdata = openweathermap_json(apikey, cityid)
136         return weatherdata['main']['temp'], datetime.datetime.fromtimestamp(weatherdata['dt'])
137     except OpenWeatherMapError:
138         return None, None
139
140
141 def currentwatertemperature(sensorid):
142     result = Sensors.query.filter_by(sensor_id=sensorid).order_by(Sensors.timestamp.desc()).first()
143     return result.value, result.timestamp
144
145
146 @app.route('/api/<version>/sensors/')
147 def sensors(version):
148     """List all sensors found in the database"""
149     result = db.session.query(Sensors.sensor_id, Sensors.sensor_name, Sensors.value_type).distinct().all()
150     return jsonify(result)
151
152
153 @app.route('/api/<version>/sensor/id/<sensor_id>')
154 def sensorid(version, sensor_id):
155     """Return all data for a specific sensor
156
157     URL parameters:
158     begin=<datetime>, optional, format like "2018-05-19T21:07:53"
159     end=<datetime>, optional, format like "2018-05-19T21:07:53"
160     mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
161     format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
162     """
163     result = sensordata(sensor_id=sensor_id)
164     return jsonify(result)
165
166
167 @app.route('/api/<version>/sensor/type/<sensor_type>')
168 def sensortype(version, sensor_type):
169     """Return all data for a specific sensor type
170
171     URL parameters:
172     begin=<datetime>, optional, format like "2018-05-19T21:07:53"
173     end=<datetime>, optional, format like "2018-05-19T21:07:53"
174     mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
175     format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
176     """
177     result = sensordata(sensor_type=sensor_type)
178     return jsonify(result)
179
180
181 @app.route('/data/', defaults={'timespan': 1})
182 @app.route("/data/<int:timespan>", methods=['GET'])
183 def data(timespan):
184     granularity = 5 * timespan               # (every) minute(s) per day
185     samples = 60/granularity * 24 * timespan # per hour over whole timespan
186     s4m   = []
187     s4m_x = []
188     s5m   = []
189     s5m_x = []
190     end   = time.time()
191     start = end - samples * granularity * 60
192
193     for i in range(int(samples)):
194         s4m.append(uniform(-10,30))
195         s5m.append(uniform(-10,30))
196         s4mt = uniform(start, end)
197         s5mt = uniform(start, end)
198         s4m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s4mt)))
199         s5m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s5mt)))
200
201     data = {
202         '0316a2193bff':   s4m,
203         '0316a2193bff_x': s4m_x,
204         '0316a21383ff':   s5m,
205         '0316a21383ff_x': s5m_x,
206         }
207
208     return jsonify(data)
209
210
211 @app.route("/")
212 def index():
213     airvalue, airtime     = currentairtemperature(apikey, cityid)
214     watervalue, watertime = currentwatertemperature(mainsensor)
215
216     return render_template(
217         'seepark_web.html',
218         apikey=apikey,
219         watervalue=watervalue,
220         watertime=watertime,
221         airvalue=airvalue,
222         airtime=airtime,
223     )