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