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
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'
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)
61 query = query.filter(Sensors.timestamp >= begin)
63 query = query.filter(Sensors.timestamp <= end)
66 mode = request.args.get('mode', 'full')
67 if mode == 'consolidated':
68 if begin is None or end is None:
71 # copied from munin/master/_bin/munin-cgi-graph.in
78 duration = (end - begin).total_seconds()
81 resolution = resolutions['day']
82 elif duration < 7 * day:
83 resolution = resolutions['week']
84 elif duration < 31 * day:
85 resolution = resolutions['month']
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
91 format = request.args.get('format', 'default')
93 c3result = defaultdict(list)
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)
102 def currentairtemperature(apikey, cityid):
103 """Retruns the tuple temperature, datetime (as float, datetime) in case of success, otherwise None, None."""
105 weatherdata = openweathermap_json(apikey, cityid)
106 return weatherdata['main']['temp'], datetime.datetime.fromtimestamp(weatherdata['dt'])
107 except OpenWeatherMapError:
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
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)
123 @app.route('/api/<version>/sensor/id/<sensor_id>')
124 def sensorid(version, sensor_id):
125 """Return all data for a specific sensor
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
133 result = select_sensordata(Sensors.sensor_id == sensor_id)
134 return jsonify([row._asdict() for row in result])
137 @app.route('/api/<version>/sensor/type/<sensor_type>')
138 def sensortype(version, sensor_type):
139 """Return all data for a specific sensor type
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
147 result = select_sensordata(Sensors.value_type == sensor_type)
148 return jsonify(result)
151 @app.route('/data/', defaults={'timespan': 1})
152 @app.route("/data/<int:timespan>", methods=['GET'])
154 granularity = 5 * timespan # (every) minute(s) per day
155 samples = 60/granularity * 24 * timespan # per hour over whole timespan
161 start = end - samples * granularity * 60
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)))
173 '0316a2193bff_x': s4m_x,
175 '0316a21383ff_x': s5m_x,
183 airvalue, airtime = currentairtemperature(apikey, cityid)
184 watervalue, watertime = currentwatertemperature(mainsensor)
186 return render_template(
189 watervalue=watervalue,