1 from random import uniform
7 from flask import Flask, render_template, jsonify, request
9 from sqlalchemy import create_engine
13 from seeparklib.openweathermap import openweathermap_json, OpenWeatherMapError
16 class JSONEncoder(flask.json.JSONEncoder):
17 def default(self, object):
18 if isinstance(object, datetime.datetime):
19 return object.isoformat()
20 return super().default(object)
23 def parse_datetime(date_str):
24 return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S')
28 app.json_encoder = JSONEncoder
29 config = configparser.ConfigParser()
30 config.read(os.environ['SEEPARKINI'])
31 apikey = config.get('openweathermap', 'apikey')
32 cityid = config.get('openweathermap', 'cityid')
35 def open_engine(config):
36 user = config.get('database', 'user')
37 pwd = config.get('database', 'password')
38 host = config.get('database', 'hostname')
39 db = config.get('database', 'database')
40 engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db), echo=False)
44 def select_sensordata(initial_where, initial_sql_args):
45 engine = open_engine(config)
46 with engine.connect() as conn:
47 where = [initial_where]
48 sql_args = [initial_sql_args]
51 if 'begin' in request.args:
52 where.append('timestamp>=%s')
53 begin = request.args.get('begin', None, parse_datetime)
54 sql_args.append(begin)
55 if 'end' in request.args:
56 where.append('timestamp<=%s')
57 end = request.args.get('end', None, parse_datetime)
59 sql = 'select * from sensors where {} order by id'.format(' and '.join(where))
60 cursor = conn.execute(sql, *sql_args)
61 result = [dict(row) for row in cursor]
63 mode = request.args.get('mode', 'full')
64 if mode == 'consolidated':
65 if begin is None or end is None:
68 # copied from munin/master/_bin/munin-cgi-graph.in
75 duration = (end - begin).total_seconds()
78 resolution = resolutions['day']
79 elif duration < 7 * day:
80 resolution = resolutions['week']
81 elif duration < 31 * day:
82 resolution = resolutions['month']
84 resolution = resolutions['year']
85 # TODO: filter out samples from 'result'
86 # like loop over results and skip if timestamp(n+1)-timestamp(n)<resolution
88 format = request.args.get('format', 'default')
92 if not row['sensor_id'] in c3result:
93 c3result[row['sensor_id']] = list()
94 c3result[row['sensor_id']].append(row['value'])
95 if not row['sensor_id'] + '_x' in c3result:
96 c3result[row['sensor_id'] + '_x'] = list()
97 dt = row['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
98 c3result[row['sensor_id'] + '_x'].append(dt)
103 def currentairtemperature(apikey, cityid):
104 """Retruns the tuple temperature, datetime (as float, datetime) in case of success, otherwise None, None."""
106 weatherdata = openweathermap_json(apikey, cityid)
107 return weatherdata['main']['temp'], datetime.datetime.fromtimestamp(weatherdata['dt'])
108 except OpenWeatherMapError:
112 def currentwatertemperature(sensorid):
113 engine = open_engine(config)
114 with engine.connect() as conn:
115 cursor = conn.execute('select value, timestamp from sensors where sensor_id=%s order by timestamp desc limit 1', sensorid)
116 result = [dict(row) for row in cursor]
117 return result[0]['value'], result[0]['timestamp']
120 @app.route('/api/<version>/sensors/')
121 def sensors(version):
122 """List all sensors found in the database"""
123 engine = open_engine(config)
124 with engine.connect() as conn:
125 cursor = conn.execute('select distinct sensor_id, sensor_name, value_type from sensors')
126 result = [dict(row) for row in cursor]
127 return jsonify(result)
130 @app.route('/api/<version>/sensor/id/<sensor_id>')
131 def sensorid(version, sensor_id):
132 """Return all data for a specific sensor
135 begin=<datetime>, optional, format like "2018-05-19T21:07:53"
136 end=<datetime>, optional, format like "2018-05-19T21:07:53"
137 mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
138 format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
140 result = select_sensordata('sensor_id=%s', sensor_id)
141 return jsonify(result)
144 @app.route('/api/<version>/sensor/type/<sensor_type>')
145 def sensortype(version, sensor_type):
146 """Return all data for a specific sensor type
149 begin=<datetime>, optional, format like "2018-05-19T21:07:53"
150 end=<datetime>, optional, format like "2018-05-19T21:07:53"
151 mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
152 format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
154 result = select_sensordata('value_type=%s', sensor_type)
155 return jsonify(result)
158 @app.route('/data/', defaults={'timespan': 1})
159 @app.route("/data/<int:timespan>", methods=['GET'])
161 granularity = 5 * timespan # (every) minute(s) per day
162 samples = 60/granularity * 24 * timespan # per hour over whole timespan
168 start = end - samples * granularity * 60
170 for i in range(int(samples)):
171 s4m.append(uniform(-10,30))
172 s5m.append(uniform(-10,30))
173 s4mt = uniform(start, end)
174 s5mt = uniform(start, end)
175 s4m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s4mt)))
176 s5m_x.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(s5mt)))
180 '0316a2193bff_x': s4m_x,
182 '0316a21383ff_x': s5m_x,
190 airvalue, airtime = currentairtemperature(apikey, cityid)
191 watervalue, watertime = currentwatertemperature('0316a21383ff') # config? mainwatertemp?
193 return render_template(
196 watervalue=watervalue,