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