-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
418 lines (352 loc) · 13 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
from flask import Flask, render_template, send_file, request
import mysql.connector
import pytz
import tzlocal
import bme280
import smbus2
from w1thermsensor import W1ThermSensor
from pms5003 import PMS5003
import json
import os
import datetime
import time
import threading
def load_configs(c):
d = {}
for key, value in c.items():
if type(value) == str and value.startswith('$'):
d[key] = os.environ.get(value[1:])
elif type(value) == str and \
(value.startswith('i$') or value.startswith('I$')):
d[key] = int(os.environ.get(value[2:]))
elif type(value) == dict:
d[key] = load_configs(value)
else:
d[key] = value
return d
with open('configs.json') as file:
configs = json.load(file)
configs = load_configs(configs)
with open('version.json') as file:
current_version = json.load(file)['version']
app = Flask(__name__)
bme280_port = 1
bme280_address = 0x76
bme280_bus = None
w1_sensor = None
pms5003 = None
ds18b20_values = {
"temperature": None
}
ds18b20_loaded = None
bme280_values = {
"temperature": None,
"humidity": None,
"pressure": None
}
bme280_loaded = None
pms5003_values = {
"pm1.0": None,
"pm2.5": None,
"pm10": None
}
pms5003_loaded = None
stats = None
stats_loaded = None
started = datetime.datetime.now()
def load_ds18b20():
try:
w1_sensor = W1ThermSensor()
except Exception:
w1_sensor = None
return w1_sensor
def load_bme280():
try:
bme280_bus = smbus2.SMBus(bme280_port)
bme280.load_calibration_params(bme280_bus, bme280_address)
except Exception:
bme280_bus = None
return bme280_bus
def load_pms5003():
try:
pms5003 = PMS5003(**configs["pms5003"])
except Exception:
pms5003 = None
return pms5003
def measure():
global ds18b20_values, ds18b20_loaded, bme280_values, bme280_loaded, pms5003_values, pms5003_loaded
ds18b20 = load_ds18b20()
bme280_bus = load_bme280()
pms5003 = load_pms5003()
while True:
try:
ds18b20_temperature = ds18b20.get_temperature()
ds18b20_values = {
"temperature": ds18b20_temperature
}
ds18b20_loaded = datetime.datetime.now()
except Exception:
if ds18b20_loaded is not None and (datetime.datetime.now() - ds18b20_loaded).seconds > 60:
ds18b20_values = {
"temperature": None
}
ds18b20_loaded = None
if ds18b20_loaded is not None and (datetime.datetime.now() - ds18b20_loaded).seconds > 10:
ds18b20 = load_ds18b20()
try:
bme280_data = bme280.sample(bme280_bus, bme280_address)
bme280_humidity = bme280_data.humidity
bme280_pressure = bme280_data.pressure
bme280_temperature = bme280_data.temperature
bme280_values = {
"temperature": bme280_temperature,
"humidity": bme280_humidity,
"pressure": bme280_pressure
}
bme280_loaded = datetime.datetime.now()
except Exception:
if bme280_loaded is not None and (datetime.datetime.now() - bme280_loaded).seconds > 60:
bme280_values = {
"temperature": None,
"humidity": None,
"pressure": None
}
bme280_loaded = None
if bme280_loaded is not None and (datetime.datetime.now() - bme280_loaded).seconds > 10:
bme280_bus = load_bme280()
try:
pms5003.reset()
pms5003_data = pms5003.read()
pms5003_1_0 = pms5003_data.pm_ug_per_m3(1)
pms5003_2_5 = pms5003_data.pm_ug_per_m3(2.5)
pms5003_10 = pms5003_data.pm_ug_per_m3(10)
pms5003_values = {
"pm1.0": pms5003_1_0,
"pm2.5": pms5003_2_5,
"pm10": pms5003_10
}
pms5003_loaded = datetime.datetime.now()
except Exception:
if pms5003_loaded is not None and (datetime.datetime.now() - pms5003_loaded).seconds > 60:
pms5003_values = {
"pm1.0": None,
"pm2.5": None,
"pm10": None
}
pms5003_loaded = None
if pms5003_loaded is not None and (datetime.datetime.now() - pms5003_loaded).seconds > 10:
pms5003 = load_pms5003()
time.sleep(2)
def load_stats():
global stats, stats_loaded
while True:
try:
tz_name = str(tzlocal.get_localzone())
tz = pytz.timezone(tz_name)
db = mysql.connector.connect(**configs['mysql'])
cursor = db.cursor(dictionary=True)
sql = 'SELECT COUNT(id) FROM readings'
cursor.execute(sql)
result = cursor.fetchall()
rows_count = result[0]['COUNT(id)']
res = {
"status": "ok",
"readings_count": rows_count,
}
check = {
"ds18b20": {
"temperature": "ds18b20_temperature"
},
"bme280": {
"temperature": "bme280_temperature",
"humidity": "bme280_humidity",
"pressure": "bme280_pressure"
},
"pms5003": {
"pm1.0": "pms5003_pm_1_0",
"pm2.5": "pms5003_pm_2_5",
"pm10": "pms5003_pm_10"
}
}
for sensor, values in check.items():
res[sensor] = {}
for key, name in values.items():
sql = f'SELECT id, {name}, read_time FROM readings WHERE {name} = (SELECT MIN({name}) FROM readings);'
cursor.execute(sql)
result = cursor.fetchall()
dt = tz.localize(result[0]['read_time'])
iso = dt.isoformat()
date = iso
min_value = {
"id": result[0]["id"],
"read_time": date,
"value": result[0][name]
}
sql = f'SELECT id, {name}, read_time FROM readings WHERE {name} = (SELECT MAX({name}) FROM readings);'
cursor.execute(sql)
result = cursor.fetchall()
dt = tz.localize(result[0]['read_time'])
iso = dt.isoformat()
date = iso
max_value = {
"id": result[0]["id"],
"read_time": date,
"value": result[0][name]
}
sql = f'SELECT AVG({name}) FROM readings'
cursor.execute(sql)
result = cursor.fetchall()
avg_value = {
'value': result[0][f'AVG({name})']
}
amp_value = {
'value': max_value['value'] - min_value['value']
}
res[sensor][key] = {
"min": min_value,
"max": max_value,
"avg": avg_value,
"amp": amp_value
}
cursor.close()
db.close()
stats = res
except Exception:
if stats_loaded is not None and (datetime.datetime.now() - stats_loaded).seconds > 5 * 60:
stats = None
stats_loaded = None
time.sleep(30)
continue
time.sleep(2 * 60)
@app.before_request
def start_threads():
app.before_request_funcs[None].remove(start_threads)
measure_thread = threading.Thread(target=measure)
stats_thread = threading.Thread(target=load_stats)
measure_thread.start()
stats_thread.start()
@app.route('/favicon.ico')
def favicon():
return send_file('static/img/icon.ico')
@app.route('/manifest.json')
def manifest():
return send_file('static/manifest.json')
@app.route('/manifest_pl.json')
def manifest_pl():
return send_file('static/manifest_pl.json')
@app.route('/')
def index():
return render_template('index.html', version=current_version)
@app.route('/api/current_reading')
def current_reading_api():
global ds18b20_values, ds18b20_loaded, bme280_values, bme280_loaded, pms5003_values, pms5003_loaded
while (ds18b20_loaded is None or bme280_loaded is None or pms5003_loaded is None) \
and (datetime.datetime.now() - started).seconds < 20:
time.sleep(1)
tz_name = str(tzlocal.get_localzone())
tz = pytz.timezone(tz_name)
dt = tz.localize(datetime.datetime.now())
iso = dt.isoformat()
ds18b20_date = tz.localize(ds18b20_loaded).isoformat() if ds18b20_loaded is not None else None
bme280_date = tz.localize(bme280_loaded).isoformat() if bme280_loaded is not None else None
pms5003_date = tz.localize(pms5003_loaded).isoformat() if pms5003_loaded is not None else None
return {
"status": "ok",
"date": iso,
"ds18b20": ds18b20_values,
"bme280": bme280_values,
"pms5003": pms5003_values,
"ds18b20_date": ds18b20_date,
"bme280_date": bme280_date,
"pms5003_date": pms5003_date
}
@app.route('/api/archive_readings/count')
def count_archive_readings_api():
db = mysql.connector.connect(**configs['mysql'])
cursor = db.cursor()
sql = 'SELECT COUNT(id) FROM readings'
cursor.execute(sql)
result = cursor.fetchall()
cursor.close()
db.close()
return {'rows_count': result[0][0]}
@app.route('/api/archive_readings')
def archive_readings_api():
try:
start_id = request.args.get('startId')
try:
limit = int(request.args.get('limit'))
except Exception:
limit = None
# reverse_direction = request.args.get('reverseDirection') == "true"
try:
start_date = request.args.get('startDate')
start_date = datetime.datetime.fromisoformat(start_date)
except Exception:
start_date = None
try:
end_date = request.args.get('endDate')
end_date = datetime.datetime.fromisoformat(end_date)
except Exception:
end_date = None
db = mysql.connector.connect(**configs['mysql'])
cursor = db.cursor(dictionary=True)
if start_date is None and end_date is None:
if start_id is None and limit is None:
sql = 'SELECT * FROM readings'
# if reverse_direction:
# sql += ' ORDER BY id DESC'
cursor.execute(sql)
elif start_id is not None and limit is None:
sql = 'SELECT * FROM readings WHERE id >= %s'
# if reverse_direction:
# sql += ' ORDER BY id DESC'
cursor.execute(sql, (start_id, ))
elif start_id is None and limit is not None:
sql = 'SELECT * FROM readings LIMIT %s'
# if reverse_direction:
# sql = 'SELECT * FROM readings ORDER BY id DESC LIMIT %s'
cursor.execute(sql, (limit, ))
else:
sql = 'SELECT * FROM readings WHERE id >= %s LIMIT %s'
# if reverse_direction:
# sql = 'SELECT * FROM readings WHERE id >= %s ORDER BY id DESC LIMIT %s'
cursor.execute(sql, (start_id, limit))
else:
if start_date is None and end_date is None:
sql = 'SELECT * FROM readings'
cursor.execute(sql)
elif start_date is not None and end_date is None:
sql = 'SELECT * FROM readings WHERE read_time >= %s'
cursor.execute(sql, (start_date, ))
elif start_date is None and end_date is not None:
sql = 'SELECT * FROM readings WHERE read_time <= %s'
cursor.execute(sql, (end_date, ))
else:
sql = 'SELECT * FROM readings WHERE read_time BETWEEN %s AND %s'
cursor.execute(sql, (start_date, end_date, ))
result = cursor.fetchall()
cursor.close()
db.close()
tz_name = str(tzlocal.get_localzone())
tz = pytz.timezone(tz_name)
for i in range(len(result)):
dt = tz.localize(result[i]['read_time'])
iso = dt.isoformat()
result[i]['read_time'] = iso
return json.dumps(result)
except Exception:
return "error"
@app.route('/api/stats')
def stats_api():
global stats, started
while stats is None and (datetime.datetime.now() - started).seconds < 60:
time.sleep(1)
if stats is None:
return {"status": "error"}
return stats
if __name__ == '__main__':
if 'flask' in configs.keys():
app.run(**configs['flask'])
else:
app.run()