1 from random import uniform
7 from collections import defaultdict
8 from flask import Flask, render_template, jsonify, request
10 from flask_sqlalchemy import SQLAlchemy, inspect
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
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)
26 def parse_datetime(date_str):
27 return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S')
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)
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')
45 app.json_encoder = JSONEncoder
46 app.config['SQLALCHEMY_DATABASE_URI'] = get_sqlalchemy_database_uri(config)
47 app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
52 class Sensors(db.Model):
53 __tablename__ = 'sensors'
55 # https://stackoverflow.com/a/37350445
57 return {c.key: getattr(self, c.key)
58 for c in inspect(self).mapper.column_attrs}
60 def select_sensordata(initial_where):
61 query = Sensors.query.filter(initial_where)
62 begin = request.args.get('begin', None, parse_datetime)
63 end = request.args.get('end', None, parse_datetime)
65 query = query.filter(Sensors.timestamp >= begin)
67 query = query.filter(Sensors.timestamp <= end)
70 mode = request.args.get('mode', 'full')
71 if mode == 'consolidated':
72 if begin is None or end is None:
75 # copied from munin/master/_bin/munin-cgi-graph.in
82 duration = (end - begin).total_seconds()
85 resolution = resolutions['day']
86 elif duration < 7 * day:
87 resolution = resolutions['week']
88 elif duration < 31 * day:
89 resolution = resolutions['month']
91 resolution = resolutions['year']
92 # TODO: filter out samples from 'result'
93 # like loop over results and skip if timestamp(n+1)-timestamp(n)<resolution
95 format = request.args.get('format', 'default')
97 c3result = defaultdict(list)
99 c3result[row.sensor_id].append(row.value)
100 dt = row.timestamp.strftime('%Y-%m-%d %H:%M:%S')
101 c3result[row.sensor_id + '_x'].append(dt)
104 return [row.to_dict() for row in result]
107 def currentairtemperature(apikey, cityid):
108 """Retruns the tuple temperature, datetime (as float, datetime) in case of success, otherwise None, None."""
110 weatherdata = openweathermap_json(apikey, cityid)
111 return weatherdata['main']['temp'], datetime.datetime.fromtimestamp(weatherdata['dt'])
112 except OpenWeatherMapError:
116 def currentwatertemperature(sensorid):
117 result = Sensors.query.filter_by(sensor_id=sensorid).order_by(Sensors.timestamp.desc()).first()
118 return result.value, result.timestamp
121 @app.route('/api/<version>/sensors/')
122 def sensors(version):
123 """List all sensors found in the database"""
124 result = db.session.query(Sensors.sensor_id, Sensors.sensor_name, Sensors.value_type).distinct().all()
125 return jsonify(result)
128 @app.route('/api/<version>/sensor/id/<sensor_id>')
129 def sensorid(version, sensor_id):
130 """Return all data for a specific sensor
133 begin=<datetime>, optional, format like "2018-05-19T21:07:53"
134 end=<datetime>, optional, format like "2018-05-19T21:07:53"
135 mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
136 format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
138 result = select_sensordata(Sensors.sensor_id == sensor_id)
139 return jsonify(result)
142 @app.route('/api/<version>/sensor/type/<sensor_type>')
143 def sensortype(version, sensor_type):
144 """Return all data for a specific sensor type
147 begin=<datetime>, optional, format like "2018-05-19T21:07:53"
148 end=<datetime>, optional, format like "2018-05-19T21:07:53"
149 mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
150 format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
152 result = select_sensordata(Sensors.value_type == sensor_type)
153 return jsonify(result)
156 @app.route('/data/', defaults={'timespan': 1})
157 @app.route("/data/<int:timespan>", methods=['GET'])
159 granularity = 5 * timespan # (every) minute(s) per day
160 samples = 60/granularity * 24 * timespan # per hour over whole timespan
166 start = end - samples * granularity * 60
168 for i in range(int(samples)):
169 s4m.append(uniform(-10,30))
170 s5m.append(uniform(-10,30))
171 s4mt = uniform(start, end)
172 s5mt = uniform(start, end)
173 s4m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s4mt)))
174 s5m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s5mt)))
178 '0316a2193bff_x': s4m_x,
180 '0316a21383ff_x': s5m_x,
188 airvalue, airtime = currentairtemperature(apikey, cityid)
189 watervalue, watertime = currentwatertemperature(mainsensor)
191 return render_template(
194 watervalue=watervalue,