fc28fdead7f895951f9fd03ccf72ddbf573d83b4
[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(initial_where):
65     query = Sensors.query.filter(initial_where)
66     begin = request.args.get('begin', None, parse_datetime)
67     end = request.args.get('end', None, parse_datetime)
68     if begin is not None:
69         query = query.filter(Sensors.timestamp >= begin)
70     if end is not None:
71         query = query.filter(Sensors.timestamp <= end)
72     result = query.all()
73
74     mode = request.args.get('mode', 'full')
75     if mode == 'consolidated':
76         if begin is None or end is None:
77             pass
78         else:
79             # copied from munin/master/_bin/munin-cgi-graph.in
80             resolutions = dict(
81                 day   =   300,
82                 week  =  1800,
83                 month =  7200,
84                 year  = 86400,
85             )
86             duration = (end - begin).total_seconds()
87             day = 60 * 60 * 24
88             if duration < day:
89                 resolution = resolutions['day']
90             elif duration < 7 * day:
91                 resolution = resolutions['week']
92             elif duration < 31 * day:
93                 resolution = resolutions['month']
94             else:
95                 resolution = resolutions['year']
96             # TODO: filter out samples from 'result'
97             # like loop over results and skip if timestamp(n+1)-timestamp(n)<resolution
98
99     format = request.args.get('format', 'default')
100     if format == 'c3':
101         c3result = defaultdict(list)
102         for row in result:
103             c3result[row.sensor_id].append(row.value)
104             dt = row.timestamp.strftime('%Y-%m-%d %H:%M:%S')
105             c3result[row.sensor_id + '_x'].append(dt)
106         return c3result
107     else:
108         return result
109
110
111 def currentairtemperature(apikey, cityid):
112     """Retruns the tuple temperature, datetime (as float, datetime) in case of success, otherwise None, None."""
113     try:
114         weatherdata = openweathermap_json(apikey, cityid)
115         return weatherdata['main']['temp'], datetime.datetime.fromtimestamp(weatherdata['dt'])
116     except OpenWeatherMapError:
117         return None, None
118
119
120 def currentwatertemperature(sensorid):
121     result = Sensors.query.filter_by(sensor_id=sensorid).order_by(Sensors.timestamp.desc()).first()
122     return result.value, result.timestamp
123
124
125 @app.route('/api/<version>/sensors/')
126 def sensors(version):
127     """List all sensors found in the database"""
128     result = db.session.query(Sensors.sensor_id, Sensors.sensor_name, Sensors.value_type).distinct().all()
129     return jsonify(result)
130
131
132 @app.route('/api/<version>/sensor/id/<sensor_id>')
133 def sensorid(version, sensor_id):
134     """Return all data for a specific sensor
135
136     URL parameters:
137     begin=<datetime>, optional, format like "2018-05-19T21:07:53"
138     end=<datetime>, optional, format like "2018-05-19T21:07:53"
139     mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
140     format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
141     """
142     result = select_sensordata(Sensors.sensor_id == sensor_id)
143     return jsonify(result)
144
145
146 @app.route('/api/<version>/sensor/type/<sensor_type>')
147 def sensortype(version, sensor_type):
148     """Return all data for a specific sensor type
149
150     URL parameters:
151     begin=<datetime>, optional, format like "2018-05-19T21:07:53"
152     end=<datetime>, optional, format like "2018-05-19T21:07:53"
153     mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
154     format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
155     """
156     result = select_sensordata(Sensors.value_type == sensor_type)
157     return jsonify(result)
158
159
160 @app.route('/data/', defaults={'timespan': 1})
161 @app.route("/data/<int:timespan>", methods=['GET'])
162 def data(timespan):
163     granularity = 5 * timespan               # (every) minute(s) per day
164     samples = 60/granularity * 24 * timespan # per hour over whole timespan
165     s4m   = []
166     s4m_x = []
167     s5m   = []
168     s5m_x = []
169     end   = time.time()
170     start = end - samples * granularity * 60
171
172     for i in range(int(samples)):
173         s4m.append(uniform(-10,30))
174         s5m.append(uniform(-10,30))
175         s4mt = uniform(start, end)
176         s5mt = uniform(start, end)
177         s4m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s4mt)))
178         s5m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s5mt)))
179
180     data = {
181         '0316a2193bff':   s4m,
182         '0316a2193bff_x': s4m_x,
183         '0316a21383ff':   s5m,
184         '0316a21383ff_x': s5m_x,
185         }
186
187     return jsonify(data)
188
189
190 @app.route("/")
191 def index():
192     airvalue, airtime     = currentairtemperature(apikey, cityid)
193     watervalue, watertime = currentwatertemperature(mainsensor)
194
195     return render_template(
196         'seepark_web.html',
197         apikey=apikey,
198         watervalue=watervalue,
199         watertime=watertime,
200         airvalue=airvalue,
201         airtime=airtime,
202     )