add mode=<full|consolidated> request argument to sensor endpoint
[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 from flask import Flask, render_template, jsonify, request
7 import flask.json
8 from sqlalchemy import create_engine
9
10
11 class JSONEncoder(flask.json.JSONEncoder):
12     def default(self, object):
13         if isinstance(object, datetime.datetime):
14             return object.isoformat()
15         return super().default(object)
16
17
18 def parse_datetime(date_str):
19     return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S')
20
21
22 app = Flask(__name__)
23 app.json_encoder = JSONEncoder
24 config = configparser.ConfigParser()
25 config.read(os.environ['SEEPARKINI'])
26 apikey = config.get('openweathermap', 'apikey')
27
28
29 def open_engine(config):
30     user = config.get('database', 'user')
31     pwd = config.get('database', 'password')
32     host = config.get('database', 'hostname')
33     db = config.get('database', 'database')
34     engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db), echo=False)
35     return engine
36
37
38 @app.route('/api/<version>/sensors/')
39 def sensors(version):
40     """List all sensors found in the database"""
41     engine = open_engine(config)
42     with engine.connect() as conn:
43         cursor = conn.execute('select distinct sensor_id, sensor_name, value_type from sensors')
44         result = [dict(row) for row in cursor]
45         return jsonify(result)
46
47
48 @app.route('/api/<version>/sensor/<sensor_id>')
49 def sensor(version, sensor_id):
50     """Return all sensor data
51
52     URL parameters:
53     begin=<datetime>, optional, format like "2018-05-19T21:07:53"
54     end=<datetime>, optional, format like "2018-05-19T21:07:53"
55     mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
56     """
57     engine = open_engine(config)
58     with engine.connect() as conn:
59         where = ['sensor_id=%s']
60         sql_args = [sensor_id]
61         begin = None
62         end = None
63         if 'begin' in request.args:
64             where.append('timestamp>=%s')
65             begin = request.args.get('begin', None, parse_datetime)
66             sql_args.append(begin)
67         if 'end' in request.args:
68             where.append('timestamp<=%s')
69             end = request.args.get('end', None, parse_datetime)
70             sql_args.append(end)
71         sql = 'select * from sensors where {} order by id'.format(' and '.join(where))
72         cursor = conn.execute(sql, *sql_args)
73         result = [dict(row) for row in cursor]
74
75         mode = request.args.get('mode', 'full')
76         if mode == 'consolidated':
77             if begin is None or end is None:
78                 pass
79             else:
80                 # copied from munin/master/_bin/munin-cgi-graph.in
81                 resolutions = dict(
82                     day   =   300,
83                     week  =  1800,
84                     month =  7200,
85                     year  = 86400,
86                 )
87                 duration = (end - begin).total_seconds()
88                 day = 60 * 60 * 24
89                 if duration < day:
90                     resolution = resolutions['day']
91                 elif duration < 7 * day:
92                     resolution = resolutions['week']
93                 elif duration < 31 * day:
94                     resolution = resolutions['month']
95                 else:
96                     resolution = resolutions['year']
97                 # TODO: filter out samples from 'result'
98                 # like loop over results and skip if timestamp(n+1)-timestamp(n)<resolution
99
100         return jsonify(result)
101
102
103 @app.route('/data/', defaults={'timespan': 1})
104 @app.route("/data/<int:timespan>", methods=['GET'])
105 def data(timespan):
106     granularity = 5 * timespan               # (every) minute(s) per day
107     samples = 60/granularity * 24 * timespan # per hour over whole timespan
108     s4m   = []
109     s4m_x = []
110     s5m   = []
111     s5m_x = []
112     end   = time.time()
113     start = end - samples * granularity * 60
114
115     for i in range(int(samples)):
116         s4m.append(uniform(-10,30))
117         s5m.append(uniform(-10,30))
118         s4mt = uniform(start, end)
119         s5mt = uniform(start, end)
120         s4m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s4mt)))
121         s5m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s5mt)))
122
123     data = {
124         '0316a2193bff':   s4m,
125         '0316a2193bff_x': s4m_x,
126         '0316a21383ff':   s5m,
127         '0316a21383ff_x': s5m_x,
128         }
129
130     return jsonify(data)
131
132
133 @app.route("/")
134 def index():
135     return render_template('seepark_web.html', apikey=apikey)
136