-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
301 lines (197 loc) · 10.3 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
# Run the application (as long as is named app.py) with:
# $ flask run --host=0.0.0.0
import requests
from flask import Flask, render_template
#from threading import Thread
#from apscheduler.schedulers.background import BackgroundScheduler, BlockingScheduler
from datetime import datetime
import pytz
import time
app = Flask(__name__)
hist_Hora = []
hist_CO2 = []
hist_PM10 = []
hist_PM25 = []
hist_Temperatura = []
hist_Humedad = []
hist_PersonasIn = []
hist_PersonasOut = []
hist_Personas = []
show_Hora = ["Iniciando..."]
show_CO2 = [-1]
show_PM10 = [-1]
show_PM25 = [-1]
CO2_msg = ""
PM10_msg = ""
PM25_msg = ""
#################################### READ HOPU DATA
def get_datetime():
# datetime object containing current date and time
# dd/mm/YY H:M:S
dt = datetime.now(pytz.timezone("Europe/Madrid"))
date = dt.strftime("%d/%m/%Y")
time = dt.strftime("%H:%M:%S")
hora = dt.strftime("%H:%M")
global hist_Hora
hist_Hora.append( hora )
# 1. Iniciar sesion en el APIRest de Hopu
# Obtener access token y refress token
def API_get_token():
url = "https://fiware.hopu.eu/keycloak/auth/realms/fiware-server/protocol/openid-connect/token"
headers = {"Content-Type": "application/x-www-form-urlencoded"}
data = "username=julgonzalez&password=vZnAWE7FexwgEqwT&grant_type=password&client_id=fiware-login"
response = requests.post(url, data = data, headers = headers).json()
access_token = response["access_token"]
#refresh_token = response["refresh_token"]
return access_token
def API_get_device_status(access_token):
global operationalStatus
url = "https://fiware.hopu.eu/orion/v2/entities?limit=1000&attrs=*,dateModified&options=count,keyValues"
headers = {"fiware-service": "Device", "fiware-servicepath": "/ctcon", "Authorization": "Bearer "+access_token}
response = requests.get(url, headers = headers).json()[0]
operationalStatus = response["operationalStatus"]
def API_get_calidad_aire(access_token):
global hist_CO2, hist_PM10, hist_PM25, hist_Temperatura, hist_Humedad
url = "https://fiware.hopu.eu/orion/v2/entities?limit=1000&attrs=*,dateModified&options=keyValues"
headers = {"fiware-service": "AirQuality", "fiware-servicepath": "/ctcon", "Authorization": "Bearer "+access_token}
response = requests.get(url, headers = headers).json()[0]
hist_CO2.append( response["CO2"] )
hist_PM10.append( response["PM10"] )
hist_PM25.append( response["PM25"] )
hist_Temperatura.append( response["temperature"] )
hist_Humedad.append( response["humidity"] )
def API_get_presencia(access_token):
global hist_PersonasIn, hist_PersonasOut, hist_Personas
url = "https://fiware.hopu.eu/orion/v2/entities?limit=1000&attrs=*,dateModified&options=count,keyValues"
headers = {"fiware-service": "PeopleCounting", "fiware-servicepath": "/ctcon", "Authorization": "Bearer "+access_token}
response = requests.get(url, headers = headers).json()[0]
hist_PersonasIn.append( response["numberOfIncoming"] )
hist_PersonasOut.append( response["numberOfOutgoing"] )
hist_Personas.append( response["numberOfIncoming"] - response["numberOfOutgoing"] )
####################################
def get_CO2_msg(pred_CO2_20mins):
start_msg = "PREDICCIÓN DE CO2 EN NIVEL "
advice_1 = " (IDA 1). NINGUNA ACCIÓN REQUERIDA."
advice_2 = " (IDA 2). SE RECOMIENDA VENTILAR LA OFICINA EN LOS PRÓXIMOS 15 MINUTOS"
advice_3 = " (IDA 3). SE DEBE VENTILAR LA OFICINA EN ESTE MOMENTO"
if pred_CO2_20mins < 500: return start_msg + "OPTIMO" + advice_1
elif pred_CO2_20mins >= 500 and pred_CO2_20mins < 900: return start_msg + "BUENO" + advice_1
elif pred_CO2_20mins >= 900 and pred_CO2_20mins < 1200: return start_msg + "ACEPTABLE" + advice_2
elif pred_CO2_20mins >= 1200: return start_msg + "DESACONSEJADO" + advice_3
def get_PM10_msg(pred_PM10_20mins):
start_msg = "PREDICCIÓN DE PARTÍCULAS EN SUSPENSIÓN INFERIORES A 10 MICRAS EN NIVEL "
advice_1 = ". NINGUNA ACCIÓN REQUERIDA."
advice_2 = ". CESEN CUALQUIER POSIBLE ACTIVIDAD GENERADORA DE POLVO EN LOS PRÓXIMOS 15 MINUTOS. REVISEN EL SISTEMA DE CLIMATIZACIÓN Y VENTILACIÓN EN LAS PRÓXIMAS 48 HORAS"
advice_3 = ". CESEN CUALQUIER POSIBLE ACTIVIDAD GENERADORA DE POLVO EN ESTE MOMENTO. REVISEN EL SISTEMA DE CLIMATIZACIÓN Y VENTILACIÓN EN LAS PRÓXIMAS 24 HORAS"
if pred_PM10_20mins < 20: return start_msg + "OPTIMO" + advice_1
elif pred_PM10_20mins >= 20 and pred_PM10_20mins < 40: return start_msg + "BUENO" + advice_1
elif pred_PM10_20mins >= 40 and pred_PM10_20mins < 60: return start_msg + "ACEPTABLE" + advice_2
elif pred_PM10_20mins >= 60: return start_msg + "DESACONSEJADO" + advice_3
def get_PM25_msg(pred_PM25_20mins):
start_msg = "PREDICCIÓN DE PARTÍCULAS EN SUSPENSIÓN INFERIORES A 2,5 MICRAS EN NIVEL "
advice_1 = ". NINGUNA ACCIÓN REQUERIDA."
advice_2 = ". CESEN CUALQUIER POSIBLE ACTIVIDAD GENERADORA DE POLVO EN LOS PRÓXIMOS 15 MINUTOS. REVISEN EL SISTEMA DE CLIMATIZACIÓN Y VENTILACIÓN EN LAS PRÓXIMAS 48 HORAS"
advice_3 = ". CESEN CUALQUIER POSIBLE ACTIVIDAD GENERADORA DE POLVO EN ESTE MOMENTO. REVISEN EL SISTEMA DE CLIMATIZACIÓN Y VENTILACIÓN EN LAS PRÓXIMAS 24 HORAS"
if pred_PM25_20mins < 20: return start_msg + "OPTIMO" + advice_1
elif pred_PM25_20mins >= 20 and pred_PM25_20mins < 40: return start_msg + "BUENO" + advice_1
elif pred_PM25_20mins >= 40 and pred_PM25_20mins < 60: return start_msg + "ACEPTABLE" + advice_2
elif pred_PM25_20mins >= 60: return start_msg + "DESACONSEJADO" + advice_3
def get_predictions(observed_array, n_points_to_predict):
value_observed_ultimo = observed_array[-1]
value_observed_penult = observed_array[-2]
incremento = value_observed_ultimo - value_observed_penult # Pos->crece; Neg->decrece
predictions = []
current = value_observed_ultimo
for i in range(n_points_to_predict):
new = current + incremento # + ruido
predictions.append(new)
current = new
return predictions
def get_ml_predictions():
global hist_Hora, hist_PM25, hist_PM10, hist_CO2
global show_Hora, show_PM25, show_PM10, show_CO2
global CO2_msg, PM10_msg, PM25_msg
if len(hist_Hora) >= 4:
#### ENOUGH DATA -> DO ML PREDICTION
show_Hora = hist_Hora[-4:] + ["+5 mins", "+10 mins", "+15 mins", "+20 mins"]
show_PM25 = hist_PM25[-4:] + get_predictions(hist_PM25[-4:], 4)
show_PM10 = hist_PM10[-4:] + get_predictions(hist_PM10[-4:], 4)
show_CO2 = hist_CO2[-4:] + get_predictions(hist_CO2[-4:], 4)
CO2_msg = get_CO2_msg(show_CO2[-1])
PM10_msg = get_PM10_msg(show_PM10[-1])
PM25_msg = get_PM25_msg(show_PM25[-1])
print("ML prediction done")
else:
#### NO ENOUGH DATA -> ERROR MSG
print("NO ENOUGH DATA FOR DOING ML PREDICTIONS")
show_Hora = hist_Hora
show_PM25 = hist_PM25
show_PM10 = hist_PM10
show_CO2 = hist_CO2
PM25_msg = "No ha transcurrido el suficienciente tiempo (<15 mins) para predecir las partículas inferiores a 2,5 micra."
PM10_msg = "No ha transcurrido el suficienciente tiempo (<15 mins) para predecir las partículas inferiores a 10 micras."
CO2_msg = "No ha transcurrido el suficienciente tiempo (<15 mins) para predecir el CO2."
#################################### ENDPOINTS
@app.route('/refresh') # Se llamara cada 5 minutos desde fuera (https://updown.io/)
def fill_data_from_HOPU_and_do_ML():
get_datetime() # Aqui se guardan historicos horas
####### fill data from HOPU and save it into tmp/data.csv as a new row
access_token = API_get_token()
API_get_device_status(access_token)
API_get_calidad_aire(access_token) # Aqui se guardan historicos calidad aire
API_get_presencia(access_token) # Aqui se guardan historicos personas
####### Get last 4 rows from tmp/data.csv and do ML predictions
get_ml_predictions()
return "Ok"
@app.route('/')
def web_endpoint():
global show_Hora, show_PM25, show_PM10, show_CO2
global CO2_msg, PM10_msg, PM25_msg
data={
"x_labels": show_Hora,
"CO2": show_CO2, #[120, 153, 213, 230, 240, 220, 180, 120],
"CO2_msg": CO2_msg,
"PM10": show_PM10, #[8, 10, 20, 26, 27, 22, 13, 11],
"PM10_msg": PM10_msg,
"PM25": show_PM25, #[6, 8, 18, 23, 24, 18, 10, 8],
"PM25_msg": PM25_msg
}
return render_template('frontend.html', **data)
@app.route('/data')
def seeData():
global hist_Hora, hist_PM25, hist_PM10, hist_CO2
global hist_Temperatura, hist_Humedad
global hist_Personas, hist_PersonasIn, hist_PersonasOut
MAX = 1000
data = {
"hora": hist_Hora[:MAX],
"CO2": hist_CO2 [:MAX],
"PM10": hist_PM10[:MAX],
"PM25": hist_PM25[:MAX],
"Temp": hist_Temperatura[:MAX],
"Hume": hist_Humedad[:MAX],
"Personas": hist_Personas[:MAX],
"PerIn": hist_PersonasIn[:MAX],
"PerOut": hist_PersonasOut[:MAX]
}
return data
"""
def updater():
# https://apscheduler.readthedocs.io/en/3.x/userguide.html#choosing-the-right-scheduler-job-store-s-executor-s-and-trigger-s
# scheduler = BackgroundScheduler(timezone='Europe/Madrid') # Default timezone is "utc"
scheduler = BlockingScheduler(timezone='Europe/Madrid') # Default timezone is "utc"
#scheduler.add_job(fill_data_from_HOPU_and_do_ML, 'interval', seconds=5)
#scheduler.add_job(fill_data_from_HOPU_and_do_ML, 'cron', day_of_week='*', hour='*', minute='*')
#scheduler.add_job(fill_data_from_HOPU_and_do_ML, 'cron', day_of_week='mon-fri', hour='7-20', minute='*/5')
scheduler.add_job(fill_data_from_HOPU_and_do_ML, 'cron', day_of_week='*', hour='*', minute='*')
scheduler.start()
def updater2():
while True:
fill_data_from_HOPU_and_do_ML()
time.sleep(4) # 5*60 = 5 minutes
updater_thread = Thread(target=updater2)
updater_thread.start()
"""
#if __name__ == '__main__':
# MAIN
# START APP: flask run --host=0.0.0.0