@@ 10-549 (lines=540) @@ | ||
7 | from decimal import * |
|
8 | ||
9 | ||
10 | class Reporting: |
|
11 | @staticmethod |
|
12 | def __init__(): |
|
13 | pass |
|
14 | ||
15 | @staticmethod |
|
16 | def on_options(req, resp): |
|
17 | resp.status = falcon.HTTP_200 |
|
18 | ||
19 | #################################################################################################################### |
|
20 | # PROCEDURES |
|
21 | # Step 1: valid parameters |
|
22 | # Step 2: query the tenant |
|
23 | # Step 3: query energy categories |
|
24 | # Step 4: query associated sensors |
|
25 | # Step 5: query associated points |
|
26 | # Step 6: query base period energy input |
|
27 | # Step 7: query reporting period energy input |
|
28 | # Step 8: query tariff data |
|
29 | # Step 9: query associated sensors and points data |
|
30 | # Step 10: construct the report |
|
31 | #################################################################################################################### |
|
32 | @staticmethod |
|
33 | def on_get(req, resp): |
|
34 | print(req.params) |
|
35 | tenant_id = req.params.get('tenantid') |
|
36 | period_type = req.params.get('periodtype') |
|
37 | base_start_datetime_local = req.params.get('baseperiodstartdatetime') |
|
38 | base_end_datetime_local = req.params.get('baseperiodenddatetime') |
|
39 | reporting_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
|
40 | reporting_end_datetime_local = req.params.get('reportingperiodenddatetime') |
|
41 | ||
42 | ################################################################################################################ |
|
43 | # Step 1: valid parameters |
|
44 | ################################################################################################################ |
|
45 | if tenant_id is None: |
|
46 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_TENANT_ID') |
|
47 | else: |
|
48 | tenant_id = str.strip(tenant_id) |
|
49 | if not tenant_id.isdigit() or int(tenant_id) <= 0: |
|
50 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_TENANT_ID') |
|
51 | ||
52 | if period_type is None: |
|
53 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
|
54 | else: |
|
55 | period_type = str.strip(period_type) |
|
56 | if period_type not in ['hourly', 'daily', 'monthly', 'yearly']: |
|
57 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
|
58 | ||
59 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
|
60 | if config.utc_offset[0] == '-': |
|
61 | timezone_offset = -timezone_offset |
|
62 | ||
63 | base_start_datetime_utc = None |
|
64 | if base_start_datetime_local is not None and len(str.strip(base_start_datetime_local)) > 0: |
|
65 | base_start_datetime_local = str.strip(base_start_datetime_local) |
|
66 | try: |
|
67 | base_start_datetime_utc = datetime.strptime(base_start_datetime_local, |
|
68 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
69 | timedelta(minutes=timezone_offset) |
|
70 | except ValueError: |
|
71 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
72 | description="API.INVALID_BASE_PERIOD_BEGINS_DATETIME") |
|
73 | ||
74 | base_end_datetime_utc = None |
|
75 | if base_end_datetime_local is not None and len(str.strip(base_end_datetime_local)) > 0: |
|
76 | base_end_datetime_local = str.strip(base_end_datetime_local) |
|
77 | try: |
|
78 | base_end_datetime_utc = datetime.strptime(base_end_datetime_local, |
|
79 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
80 | timedelta(minutes=timezone_offset) |
|
81 | except ValueError: |
|
82 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
83 | description="API.INVALID_BASE_PERIOD_ENDS_DATETIME") |
|
84 | ||
85 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
|
86 | base_start_datetime_utc >= base_end_datetime_utc: |
|
87 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
88 | description='API.INVALID_BASE_PERIOD_ENDS_DATETIME') |
|
89 | ||
90 | if reporting_start_datetime_local is None: |
|
91 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
92 | description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME") |
|
93 | else: |
|
94 | reporting_start_datetime_local = str.strip(reporting_start_datetime_local) |
|
95 | try: |
|
96 | reporting_start_datetime_utc = datetime.strptime(reporting_start_datetime_local, |
|
97 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
98 | timedelta(minutes=timezone_offset) |
|
99 | except ValueError: |
|
100 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
101 | description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME") |
|
102 | ||
103 | if reporting_end_datetime_local is None: |
|
104 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
105 | description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME") |
|
106 | else: |
|
107 | reporting_end_datetime_local = str.strip(reporting_end_datetime_local) |
|
108 | try: |
|
109 | reporting_end_datetime_utc = datetime.strptime(reporting_end_datetime_local, |
|
110 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
111 | timedelta(minutes=timezone_offset) |
|
112 | except ValueError: |
|
113 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
114 | description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME") |
|
115 | ||
116 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
|
117 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
118 | description='API.INVALID_REPORTING_PERIOD_ENDS_DATETIME') |
|
119 | ||
120 | ################################################################################################################ |
|
121 | # Step 2: query the tenant |
|
122 | ################################################################################################################ |
|
123 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
|
124 | cursor_system = cnx_system.cursor() |
|
125 | ||
126 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
|
127 | cursor_energy = cnx_energy.cursor() |
|
128 | ||
129 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
|
130 | cursor_historical = cnx_historical.cursor() |
|
131 | ||
132 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
133 | " FROM tbl_tenants " |
|
134 | " WHERE id = %s ", (tenant_id,)) |
|
135 | row_tenant = cursor_system.fetchone() |
|
136 | if row_tenant is None: |
|
137 | if cursor_system: |
|
138 | cursor_system.close() |
|
139 | if cnx_system: |
|
140 | cnx_system.disconnect() |
|
141 | ||
142 | if cursor_energy: |
|
143 | cursor_energy.close() |
|
144 | if cnx_energy: |
|
145 | cnx_energy.disconnect() |
|
146 | ||
147 | if cnx_historical: |
|
148 | cnx_historical.close() |
|
149 | if cursor_historical: |
|
150 | cursor_historical.disconnect() |
|
151 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.TENANT_NOT_FOUND') |
|
152 | ||
153 | tenant = dict() |
|
154 | tenant['id'] = row_tenant[0] |
|
155 | tenant['name'] = row_tenant[1] |
|
156 | tenant['area'] = row_tenant[2] |
|
157 | tenant['cost_center_id'] = row_tenant[3] |
|
158 | ||
159 | ################################################################################################################ |
|
160 | # Step 3: query energy categories |
|
161 | ################################################################################################################ |
|
162 | energy_category_set = set() |
|
163 | # query energy categories in base period |
|
164 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
165 | " FROM tbl_tenant_input_category_hourly " |
|
166 | " WHERE tenant_id = %s " |
|
167 | " AND start_datetime_utc >= %s " |
|
168 | " AND start_datetime_utc < %s ", |
|
169 | (tenant['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
170 | rows_energy_categories = cursor_energy.fetchall() |
|
171 | if rows_energy_categories is not None or len(rows_energy_categories) > 0: |
|
172 | for row_energy_category in rows_energy_categories: |
|
173 | energy_category_set.add(row_energy_category[0]) |
|
174 | ||
175 | # query energy categories in reporting period |
|
176 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
177 | " FROM tbl_tenant_input_category_hourly " |
|
178 | " WHERE tenant_id = %s " |
|
179 | " AND start_datetime_utc >= %s " |
|
180 | " AND start_datetime_utc < %s ", |
|
181 | (tenant['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
182 | rows_energy_categories = cursor_energy.fetchall() |
|
183 | if rows_energy_categories is not None or len(rows_energy_categories) > 0: |
|
184 | for row_energy_category in rows_energy_categories: |
|
185 | energy_category_set.add(row_energy_category[0]) |
|
186 | ||
187 | # query all energy categories in base period and reporting period |
|
188 | cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e " |
|
189 | " FROM tbl_energy_categories " |
|
190 | " ORDER BY id ", ) |
|
191 | rows_energy_categories = cursor_system.fetchall() |
|
192 | if rows_energy_categories is None or len(rows_energy_categories) == 0: |
|
193 | if cursor_system: |
|
194 | cursor_system.close() |
|
195 | if cnx_system: |
|
196 | cnx_system.disconnect() |
|
197 | ||
198 | if cursor_energy: |
|
199 | cursor_energy.close() |
|
200 | if cnx_energy: |
|
201 | cnx_energy.disconnect() |
|
202 | ||
203 | if cnx_historical: |
|
204 | cnx_historical.close() |
|
205 | if cursor_historical: |
|
206 | cursor_historical.disconnect() |
|
207 | raise falcon.HTTPError(falcon.HTTP_404, |
|
208 | title='API.NOT_FOUND', |
|
209 | description='API.ENERGY_CATEGORY_NOT_FOUND') |
|
210 | energy_category_dict = dict() |
|
211 | for row_energy_category in rows_energy_categories: |
|
212 | if row_energy_category[0] in energy_category_set: |
|
213 | energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1], |
|
214 | "unit_of_measure": row_energy_category[2], |
|
215 | "kgce": row_energy_category[3], |
|
216 | "kgco2e": row_energy_category[4]} |
|
217 | ||
218 | ################################################################################################################ |
|
219 | # Step 4: query associated sensors |
|
220 | ################################################################################################################ |
|
221 | point_list = list() |
|
222 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
223 | " FROM tbl_tenants t, tbl_sensors s, tbl_tenants_sensors ts, " |
|
224 | " tbl_points p, tbl_sensors_points sp " |
|
225 | " WHERE t.id = %s AND t.id = ts.tenant_id AND ts.sensor_id = s.id " |
|
226 | " AND s.id = sp.sensor_id AND sp.point_id = p.id " |
|
227 | " ORDER BY p.id ", (tenant['id'], )) |
|
228 | rows_points = cursor_system.fetchall() |
|
229 | if rows_points is not None and len(rows_points) > 0: |
|
230 | for row in rows_points: |
|
231 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
232 | ||
233 | ################################################################################################################ |
|
234 | # Step 5: query associated points |
|
235 | ################################################################################################################ |
|
236 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
237 | " FROM tbl_tenants t, tbl_tenants_points tp, tbl_points p " |
|
238 | " WHERE t.id = %s AND t.id = tp.tenant_id AND tp.point_id = p.id " |
|
239 | " ORDER BY p.id ", (tenant['id'], )) |
|
240 | rows_points = cursor_system.fetchall() |
|
241 | if rows_points is not None and len(rows_points) > 0: |
|
242 | for row in rows_points: |
|
243 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
244 | ||
245 | ################################################################################################################ |
|
246 | # Step 6: query base period energy input |
|
247 | ################################################################################################################ |
|
248 | base = dict() |
|
249 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
250 | for energy_category_id in energy_category_set: |
|
251 | base[energy_category_id] = dict() |
|
252 | base[energy_category_id]['timestamps'] = list() |
|
253 | base[energy_category_id]['sub_averages'] = list() |
|
254 | base[energy_category_id]['sub_maximums'] = list() |
|
255 | base[energy_category_id]['average'] = None |
|
256 | base[energy_category_id]['maximum'] = None |
|
257 | base[energy_category_id]['factor'] = None |
|
258 | ||
259 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
260 | " FROM tbl_tenant_input_category_hourly " |
|
261 | " WHERE tenant_id = %s " |
|
262 | " AND energy_category_id = %s " |
|
263 | " AND start_datetime_utc >= %s " |
|
264 | " AND start_datetime_utc < %s " |
|
265 | " ORDER BY start_datetime_utc ", |
|
266 | (tenant['id'], |
|
267 | energy_category_id, |
|
268 | base_start_datetime_utc, |
|
269 | base_end_datetime_utc)) |
|
270 | rows_tenant_hourly = cursor_energy.fetchall() |
|
271 | ||
272 | rows_tenant_periodically, \ |
|
273 | base[energy_category_id]['average'], \ |
|
274 | base[energy_category_id]['maximum'] = \ |
|
275 | utilities.averaging_hourly_data_by_period(rows_tenant_hourly, |
|
276 | base_start_datetime_utc, |
|
277 | base_end_datetime_utc, |
|
278 | period_type) |
|
279 | base[energy_category_id]['factor'] = \ |
|
280 | (base[energy_category_id]['average'] / base[energy_category_id]['maximum'] |
|
281 | if (base[energy_category_id]['average'] is not None and |
|
282 | base[energy_category_id]['maximum'] is not None and |
|
283 | base[energy_category_id]['maximum'] > Decimal(0.0)) |
|
284 | else None) |
|
285 | ||
286 | for row_tenant_periodically in rows_tenant_periodically: |
|
287 | current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
288 | timedelta(minutes=timezone_offset) |
|
289 | if period_type == 'hourly': |
|
290 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
291 | elif period_type == 'daily': |
|
292 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
293 | elif period_type == 'monthly': |
|
294 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
295 | elif period_type == 'yearly': |
|
296 | current_datetime = current_datetime_local.strftime('%Y') |
|
297 | ||
298 | base[energy_category_id]['timestamps'].append(current_datetime) |
|
299 | base[energy_category_id]['sub_averages'].append(row_tenant_periodically[1]) |
|
300 | base[energy_category_id]['sub_maximums'].append(row_tenant_periodically[2]) |
|
301 | ||
302 | ################################################################################################################ |
|
303 | # Step 7: query reporting period energy input |
|
304 | ################################################################################################################ |
|
305 | reporting = dict() |
|
306 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
307 | for energy_category_id in energy_category_set: |
|
308 | reporting[energy_category_id] = dict() |
|
309 | reporting[energy_category_id]['timestamps'] = list() |
|
310 | reporting[energy_category_id]['sub_averages'] = list() |
|
311 | reporting[energy_category_id]['sub_maximums'] = list() |
|
312 | reporting[energy_category_id]['average'] = None |
|
313 | reporting[energy_category_id]['maximum'] = None |
|
314 | reporting[energy_category_id]['factor'] = None |
|
315 | ||
316 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
317 | " FROM tbl_tenant_input_category_hourly " |
|
318 | " WHERE tenant_id = %s " |
|
319 | " AND energy_category_id = %s " |
|
320 | " AND start_datetime_utc >= %s " |
|
321 | " AND start_datetime_utc < %s " |
|
322 | " ORDER BY start_datetime_utc ", |
|
323 | (tenant['id'], |
|
324 | energy_category_id, |
|
325 | reporting_start_datetime_utc, |
|
326 | reporting_end_datetime_utc)) |
|
327 | rows_tenant_hourly = cursor_energy.fetchall() |
|
328 | ||
329 | rows_tenant_periodically, \ |
|
330 | reporting[energy_category_id]['average'], \ |
|
331 | reporting[energy_category_id]['maximum'] = \ |
|
332 | utilities.averaging_hourly_data_by_period(rows_tenant_hourly, |
|
333 | reporting_start_datetime_utc, |
|
334 | reporting_end_datetime_utc, |
|
335 | period_type) |
|
336 | reporting[energy_category_id]['factor'] = \ |
|
337 | (reporting[energy_category_id]['average'] / reporting[energy_category_id]['maximum'] |
|
338 | if (reporting[energy_category_id]['average'] is not None and |
|
339 | reporting[energy_category_id]['maximum'] is not None and |
|
340 | reporting[energy_category_id]['maximum'] > Decimal(0.0)) |
|
341 | else None) |
|
342 | ||
343 | for row_tenant_periodically in rows_tenant_periodically: |
|
344 | current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
345 | timedelta(minutes=timezone_offset) |
|
346 | if period_type == 'hourly': |
|
347 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
348 | elif period_type == 'daily': |
|
349 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
350 | elif period_type == 'monthly': |
|
351 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
352 | elif period_type == 'yearly': |
|
353 | current_datetime = current_datetime_local.strftime('%Y') |
|
354 | ||
355 | reporting[energy_category_id]['timestamps'].append(current_datetime) |
|
356 | reporting[energy_category_id]['sub_averages'].append(row_tenant_periodically[1]) |
|
357 | reporting[energy_category_id]['sub_maximums'].append(row_tenant_periodically[2]) |
|
358 | ||
359 | ################################################################################################################ |
|
360 | # Step 8: query tariff data |
|
361 | ################################################################################################################ |
|
362 | parameters_data = dict() |
|
363 | parameters_data['names'] = list() |
|
364 | parameters_data['timestamps'] = list() |
|
365 | parameters_data['values'] = list() |
|
366 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
367 | for energy_category_id in energy_category_set: |
|
368 | energy_category_tariff_dict = utilities.get_energy_category_tariffs(tenant['cost_center_id'], |
|
369 | energy_category_id, |
|
370 | reporting_start_datetime_utc, |
|
371 | reporting_end_datetime_utc) |
|
372 | tariff_timestamp_list = list() |
|
373 | tariff_value_list = list() |
|
374 | for k, v in energy_category_tariff_dict.items(): |
|
375 | # convert k from utc to local |
|
376 | k = k + timedelta(minutes=timezone_offset) |
|
377 | tariff_timestamp_list.append(k.isoformat()[0:19][0:19]) |
|
378 | tariff_value_list.append(v) |
|
379 | ||
380 | parameters_data['names'].append('TARIFF-' + energy_category_dict[energy_category_id]['name']) |
|
381 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
382 | parameters_data['values'].append(tariff_value_list) |
|
383 | ||
384 | ################################################################################################################ |
|
385 | # Step 9: query associated sensors and points data |
|
386 | ################################################################################################################ |
|
387 | for point in point_list: |
|
388 | point_values = [] |
|
389 | point_timestamps = [] |
|
390 | if point['object_type'] == 'ANALOG_VALUE': |
|
391 | query = (" SELECT utc_date_time, actual_value " |
|
392 | " FROM tbl_analog_value " |
|
393 | " WHERE point_id = %s " |
|
394 | " AND utc_date_time BETWEEN %s AND %s " |
|
395 | " ORDER BY utc_date_time ") |
|
396 | cursor_historical.execute(query, (point['id'], |
|
397 | reporting_start_datetime_utc, |
|
398 | reporting_end_datetime_utc)) |
|
399 | rows = cursor_historical.fetchall() |
|
400 | ||
401 | if rows is not None and len(rows) > 0: |
|
402 | for row in rows: |
|
403 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
404 | timedelta(minutes=timezone_offset) |
|
405 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
406 | point_timestamps.append(current_datetime) |
|
407 | point_values.append(row[1]) |
|
408 | ||
409 | elif point['object_type'] == 'ENERGY_VALUE': |
|
410 | query = (" SELECT utc_date_time, actual_value " |
|
411 | " FROM tbl_energy_value " |
|
412 | " WHERE point_id = %s " |
|
413 | " AND utc_date_time BETWEEN %s AND %s " |
|
414 | " ORDER BY utc_date_time ") |
|
415 | cursor_historical.execute(query, (point['id'], |
|
416 | reporting_start_datetime_utc, |
|
417 | reporting_end_datetime_utc)) |
|
418 | rows = cursor_historical.fetchall() |
|
419 | ||
420 | if rows is not None and len(rows) > 0: |
|
421 | for row in rows: |
|
422 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
423 | timedelta(minutes=timezone_offset) |
|
424 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
425 | point_timestamps.append(current_datetime) |
|
426 | point_values.append(row[1]) |
|
427 | elif point['object_type'] == 'DIGITAL_VALUE': |
|
428 | query = (" SELECT utc_date_time, actual_value " |
|
429 | " FROM tbl_digital_value " |
|
430 | " WHERE point_id = %s " |
|
431 | " AND utc_date_time BETWEEN %s AND %s ") |
|
432 | cursor_historical.execute(query, (point['id'], |
|
433 | reporting_start_datetime_utc, |
|
434 | reporting_end_datetime_utc)) |
|
435 | rows = cursor_historical.fetchall() |
|
436 | ||
437 | if rows is not None and len(rows) > 0: |
|
438 | for row in rows: |
|
439 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
440 | timedelta(minutes=timezone_offset) |
|
441 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
442 | point_timestamps.append(current_datetime) |
|
443 | point_values.append(row[1]) |
|
444 | ||
445 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
|
446 | parameters_data['timestamps'].append(point_timestamps) |
|
447 | parameters_data['values'].append(point_values) |
|
448 | ||
449 | ################################################################################################################ |
|
450 | # Step 10: construct the report |
|
451 | ################################################################################################################ |
|
452 | if cursor_system: |
|
453 | cursor_system.close() |
|
454 | if cnx_system: |
|
455 | cnx_system.disconnect() |
|
456 | ||
457 | if cursor_energy: |
|
458 | cursor_energy.close() |
|
459 | if cnx_energy: |
|
460 | cnx_energy.disconnect() |
|
461 | ||
462 | result = dict() |
|
463 | ||
464 | result['tenant'] = dict() |
|
465 | result['tenant']['name'] = tenant['name'] |
|
466 | result['tenant']['area'] = tenant['area'] |
|
467 | ||
468 | result['base_period'] = dict() |
|
469 | result['base_period']['names'] = list() |
|
470 | result['base_period']['units'] = list() |
|
471 | result['base_period']['timestamps'] = list() |
|
472 | result['base_period']['sub_averages'] = list() |
|
473 | result['base_period']['sub_maximums'] = list() |
|
474 | result['base_period']['averages'] = list() |
|
475 | result['base_period']['maximums'] = list() |
|
476 | result['base_period']['factors'] = list() |
|
477 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
478 | for energy_category_id in energy_category_set: |
|
479 | result['base_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
480 | result['base_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
481 | result['base_period']['timestamps'].append(base[energy_category_id]['timestamps']) |
|
482 | result['base_period']['sub_averages'].append(base[energy_category_id]['sub_averages']) |
|
483 | result['base_period']['sub_maximums'].append(base[energy_category_id]['sub_maximums']) |
|
484 | result['base_period']['averages'].append(base[energy_category_id]['average']) |
|
485 | result['base_period']['maximums'].append(base[energy_category_id]['maximum']) |
|
486 | result['base_period']['factors'].append(base[energy_category_id]['factor']) |
|
487 | ||
488 | result['reporting_period'] = dict() |
|
489 | result['reporting_period']['names'] = list() |
|
490 | result['reporting_period']['energy_category_ids'] = list() |
|
491 | result['reporting_period']['units'] = list() |
|
492 | result['reporting_period']['timestamps'] = list() |
|
493 | result['reporting_period']['sub_averages'] = list() |
|
494 | result['reporting_period']['sub_maximums'] = list() |
|
495 | result['reporting_period']['averages'] = list() |
|
496 | result['reporting_period']['averages_per_unit_area'] = list() |
|
497 | result['reporting_period']['averages_increment_rate'] = list() |
|
498 | result['reporting_period']['maximums'] = list() |
|
499 | result['reporting_period']['maximums_per_unit_area'] = list() |
|
500 | result['reporting_period']['maximums_increment_rate'] = list() |
|
501 | result['reporting_period']['factors'] = list() |
|
502 | result['reporting_period']['factors_increment_rate'] = list() |
|
503 | ||
504 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
505 | for energy_category_id in energy_category_set: |
|
506 | result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
507 | result['reporting_period']['energy_category_ids'].append(energy_category_id) |
|
508 | result['reporting_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
509 | result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps']) |
|
510 | result['reporting_period']['sub_averages'].append(reporting[energy_category_id]['sub_averages']) |
|
511 | result['reporting_period']['sub_maximums'].append(reporting[energy_category_id]['sub_maximums']) |
|
512 | result['reporting_period']['averages'].append(reporting[energy_category_id]['average']) |
|
513 | result['reporting_period']['averages_per_unit_area'].append( |
|
514 | reporting[energy_category_id]['average'] / tenant['area'] |
|
515 | if reporting[energy_category_id]['average'] is not None and |
|
516 | tenant['area'] is not None and |
|
517 | tenant['area'] > Decimal(0.0) |
|
518 | else None) |
|
519 | result['reporting_period']['averages_increment_rate'].append( |
|
520 | (reporting[energy_category_id]['average'] - base[energy_category_id]['average']) / |
|
521 | base[energy_category_id]['average'] if (base[energy_category_id]['average'] is not None and |
|
522 | base[energy_category_id]['average'] > Decimal(0.0)) |
|
523 | else None) |
|
524 | result['reporting_period']['maximums'].append(reporting[energy_category_id]['maximum']) |
|
525 | result['reporting_period']['maximums_increment_rate'].append( |
|
526 | (reporting[energy_category_id]['maximum'] - base[energy_category_id]['maximum']) / |
|
527 | base[energy_category_id]['maximum'] if (base[energy_category_id]['maximum'] is not None and |
|
528 | base[energy_category_id]['maximum'] > Decimal(0.0)) |
|
529 | else None) |
|
530 | result['reporting_period']['maximums_per_unit_area'].append( |
|
531 | reporting[energy_category_id]['maximum'] / tenant['area'] |
|
532 | if reporting[energy_category_id]['maximum'] is not None and |
|
533 | tenant['area'] is not None and |
|
534 | tenant['area'] > Decimal(0.0) |
|
535 | else None) |
|
536 | result['reporting_period']['factors'].append(reporting[energy_category_id]['factor']) |
|
537 | result['reporting_period']['factors_increment_rate'].append( |
|
538 | (reporting[energy_category_id]['factor'] - base[energy_category_id]['factor']) / |
|
539 | base[energy_category_id]['factor'] if (base[energy_category_id]['factor'] is not None and |
|
540 | base[energy_category_id]['factor'] > Decimal(0.0)) |
|
541 | else None) |
|
542 | ||
543 | result['parameters'] = { |
|
544 | "names": parameters_data['names'], |
|
545 | "timestamps": parameters_data['timestamps'], |
|
546 | "values": parameters_data['values'] |
|
547 | } |
|
548 | ||
549 | resp.body = json.dumps(result) |
|
550 |
@@ 10-549 (lines=540) @@ | ||
7 | from decimal import * |
|
8 | ||
9 | ||
10 | class Reporting: |
|
11 | @staticmethod |
|
12 | def __init__(): |
|
13 | pass |
|
14 | ||
15 | @staticmethod |
|
16 | def on_options(req, resp): |
|
17 | resp.status = falcon.HTTP_200 |
|
18 | ||
19 | #################################################################################################################### |
|
20 | # PROCEDURES |
|
21 | # Step 1: valid parameters |
|
22 | # Step 2: query the space |
|
23 | # Step 3: query energy categories |
|
24 | # Step 4: query associated sensors |
|
25 | # Step 5: query associated points |
|
26 | # Step 6: query base period energy input |
|
27 | # Step 7: query reporting period energy input |
|
28 | # Step 8: query tariff data |
|
29 | # Step 9: query associated sensors and points data |
|
30 | # Step 10: construct the report |
|
31 | #################################################################################################################### |
|
32 | @staticmethod |
|
33 | def on_get(req, resp): |
|
34 | print(req.params) |
|
35 | space_id = req.params.get('spaceid') |
|
36 | period_type = req.params.get('periodtype') |
|
37 | base_start_datetime_local = req.params.get('baseperiodstartdatetime') |
|
38 | base_end_datetime_local = req.params.get('baseperiodenddatetime') |
|
39 | reporting_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
|
40 | reporting_end_datetime_local = req.params.get('reportingperiodenddatetime') |
|
41 | ||
42 | ################################################################################################################ |
|
43 | # Step 1: valid parameters |
|
44 | ################################################################################################################ |
|
45 | if space_id is None: |
|
46 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_SPACE_ID') |
|
47 | else: |
|
48 | space_id = str.strip(space_id) |
|
49 | if not space_id.isdigit() or int(space_id) <= 0: |
|
50 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_SPACE_ID') |
|
51 | ||
52 | if period_type is None: |
|
53 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
|
54 | else: |
|
55 | period_type = str.strip(period_type) |
|
56 | if period_type not in ['hourly', 'daily', 'monthly', 'yearly']: |
|
57 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
|
58 | ||
59 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
|
60 | if config.utc_offset[0] == '-': |
|
61 | timezone_offset = -timezone_offset |
|
62 | ||
63 | base_start_datetime_utc = None |
|
64 | if base_start_datetime_local is not None and len(str.strip(base_start_datetime_local)) > 0: |
|
65 | base_start_datetime_local = str.strip(base_start_datetime_local) |
|
66 | try: |
|
67 | base_start_datetime_utc = datetime.strptime(base_start_datetime_local, |
|
68 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
69 | timedelta(minutes=timezone_offset) |
|
70 | except ValueError: |
|
71 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
72 | description="API.INVALID_BASE_PERIOD_BEGINS_DATETIME") |
|
73 | ||
74 | base_end_datetime_utc = None |
|
75 | if base_end_datetime_local is not None and len(str.strip(base_end_datetime_local)) > 0: |
|
76 | base_end_datetime_local = str.strip(base_end_datetime_local) |
|
77 | try: |
|
78 | base_end_datetime_utc = datetime.strptime(base_end_datetime_local, |
|
79 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
80 | timedelta(minutes=timezone_offset) |
|
81 | except ValueError: |
|
82 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
83 | description="API.INVALID_BASE_PERIOD_ENDS_DATETIME") |
|
84 | ||
85 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
|
86 | base_start_datetime_utc >= base_end_datetime_utc: |
|
87 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
88 | description='API.INVALID_BASE_PERIOD_ENDS_DATETIME') |
|
89 | ||
90 | if reporting_start_datetime_local is None: |
|
91 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
92 | description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME") |
|
93 | else: |
|
94 | reporting_start_datetime_local = str.strip(reporting_start_datetime_local) |
|
95 | try: |
|
96 | reporting_start_datetime_utc = datetime.strptime(reporting_start_datetime_local, |
|
97 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
98 | timedelta(minutes=timezone_offset) |
|
99 | except ValueError: |
|
100 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
101 | description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME") |
|
102 | ||
103 | if reporting_end_datetime_local is None: |
|
104 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
105 | description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME") |
|
106 | else: |
|
107 | reporting_end_datetime_local = str.strip(reporting_end_datetime_local) |
|
108 | try: |
|
109 | reporting_end_datetime_utc = datetime.strptime(reporting_end_datetime_local, |
|
110 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
111 | timedelta(minutes=timezone_offset) |
|
112 | except ValueError: |
|
113 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
114 | description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME") |
|
115 | ||
116 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
|
117 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
118 | description='API.INVALID_REPORTING_PERIOD_ENDS_DATETIME') |
|
119 | ||
120 | ################################################################################################################ |
|
121 | # Step 2: query the space |
|
122 | ################################################################################################################ |
|
123 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
|
124 | cursor_system = cnx_system.cursor() |
|
125 | ||
126 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
|
127 | cursor_energy = cnx_energy.cursor() |
|
128 | ||
129 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
|
130 | cursor_historical = cnx_historical.cursor() |
|
131 | ||
132 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
133 | " FROM tbl_spaces " |
|
134 | " WHERE id = %s ", (space_id,)) |
|
135 | row_space = cursor_system.fetchone() |
|
136 | if row_space is None: |
|
137 | if cursor_system: |
|
138 | cursor_system.close() |
|
139 | if cnx_system: |
|
140 | cnx_system.disconnect() |
|
141 | ||
142 | if cursor_energy: |
|
143 | cursor_energy.close() |
|
144 | if cnx_energy: |
|
145 | cnx_energy.disconnect() |
|
146 | ||
147 | if cnx_historical: |
|
148 | cnx_historical.close() |
|
149 | if cursor_historical: |
|
150 | cursor_historical.disconnect() |
|
151 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.SPACE_NOT_FOUND') |
|
152 | ||
153 | space = dict() |
|
154 | space['id'] = row_space[0] |
|
155 | space['name'] = row_space[1] |
|
156 | space['area'] = row_space[2] |
|
157 | space['cost_center_id'] = row_space[3] |
|
158 | ||
159 | ################################################################################################################ |
|
160 | # Step 3: query energy categories |
|
161 | ################################################################################################################ |
|
162 | energy_category_set = set() |
|
163 | # query energy categories in base period |
|
164 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
165 | " FROM tbl_space_input_category_hourly " |
|
166 | " WHERE space_id = %s " |
|
167 | " AND start_datetime_utc >= %s " |
|
168 | " AND start_datetime_utc < %s ", |
|
169 | (space['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
170 | rows_energy_categories = cursor_energy.fetchall() |
|
171 | if rows_energy_categories is not None or len(rows_energy_categories) > 0: |
|
172 | for row_energy_category in rows_energy_categories: |
|
173 | energy_category_set.add(row_energy_category[0]) |
|
174 | ||
175 | # query energy categories in reporting period |
|
176 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
177 | " FROM tbl_space_input_category_hourly " |
|
178 | " WHERE space_id = %s " |
|
179 | " AND start_datetime_utc >= %s " |
|
180 | " AND start_datetime_utc < %s ", |
|
181 | (space['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
182 | rows_energy_categories = cursor_energy.fetchall() |
|
183 | if rows_energy_categories is not None or len(rows_energy_categories) > 0: |
|
184 | for row_energy_category in rows_energy_categories: |
|
185 | energy_category_set.add(row_energy_category[0]) |
|
186 | ||
187 | # query all energy categories in base period and reporting period |
|
188 | cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e " |
|
189 | " FROM tbl_energy_categories " |
|
190 | " ORDER BY id ", ) |
|
191 | rows_energy_categories = cursor_system.fetchall() |
|
192 | if rows_energy_categories is None or len(rows_energy_categories) == 0: |
|
193 | if cursor_system: |
|
194 | cursor_system.close() |
|
195 | if cnx_system: |
|
196 | cnx_system.disconnect() |
|
197 | ||
198 | if cursor_energy: |
|
199 | cursor_energy.close() |
|
200 | if cnx_energy: |
|
201 | cnx_energy.disconnect() |
|
202 | ||
203 | if cnx_historical: |
|
204 | cnx_historical.close() |
|
205 | if cursor_historical: |
|
206 | cursor_historical.disconnect() |
|
207 | raise falcon.HTTPError(falcon.HTTP_404, |
|
208 | title='API.NOT_FOUND', |
|
209 | description='API.ENERGY_CATEGORY_NOT_FOUND') |
|
210 | energy_category_dict = dict() |
|
211 | for row_energy_category in rows_energy_categories: |
|
212 | if row_energy_category[0] in energy_category_set: |
|
213 | energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1], |
|
214 | "unit_of_measure": row_energy_category[2], |
|
215 | "kgce": row_energy_category[3], |
|
216 | "kgco2e": row_energy_category[4]} |
|
217 | ||
218 | ################################################################################################################ |
|
219 | # Step 4: query associated sensors |
|
220 | ################################################################################################################ |
|
221 | point_list = list() |
|
222 | cursor_system.execute(" SELECT po.id, po.name, po.units, po.object_type " |
|
223 | " FROM tbl_spaces sp, tbl_sensors se, tbl_spaces_sensors spse, " |
|
224 | " tbl_points po, tbl_sensors_points sepo " |
|
225 | " WHERE sp.id = %s AND sp.id = spse.space_id AND spse.sensor_id = se.id " |
|
226 | " AND se.id = sepo.sensor_id AND sepo.point_id = po.id " |
|
227 | " ORDER BY po.id ", (space['id'], )) |
|
228 | rows_points = cursor_system.fetchall() |
|
229 | if rows_points is not None and len(rows_points) > 0: |
|
230 | for row in rows_points: |
|
231 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
232 | ||
233 | ################################################################################################################ |
|
234 | # Step 5: query associated points |
|
235 | ################################################################################################################ |
|
236 | cursor_system.execute(" SELECT po.id, po.name, po.units, po.object_type " |
|
237 | " FROM tbl_spaces sp, tbl_spaces_points sppo, tbl_points po " |
|
238 | " WHERE sp.id = %s AND sp.id = sppo.space_id AND sppo.point_id = po.id " |
|
239 | " ORDER BY po.id ", (space['id'], )) |
|
240 | rows_points = cursor_system.fetchall() |
|
241 | if rows_points is not None and len(rows_points) > 0: |
|
242 | for row in rows_points: |
|
243 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
244 | ||
245 | ################################################################################################################ |
|
246 | # Step 6: query base period energy input |
|
247 | ################################################################################################################ |
|
248 | base = dict() |
|
249 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
250 | for energy_category_id in energy_category_set: |
|
251 | base[energy_category_id] = dict() |
|
252 | base[energy_category_id]['timestamps'] = list() |
|
253 | base[energy_category_id]['sub_averages'] = list() |
|
254 | base[energy_category_id]['sub_maximums'] = list() |
|
255 | base[energy_category_id]['average'] = None |
|
256 | base[energy_category_id]['maximum'] = None |
|
257 | base[energy_category_id]['factor'] = None |
|
258 | ||
259 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
260 | " FROM tbl_space_input_category_hourly " |
|
261 | " WHERE space_id = %s " |
|
262 | " AND energy_category_id = %s " |
|
263 | " AND start_datetime_utc >= %s " |
|
264 | " AND start_datetime_utc < %s " |
|
265 | " ORDER BY start_datetime_utc ", |
|
266 | (space['id'], |
|
267 | energy_category_id, |
|
268 | base_start_datetime_utc, |
|
269 | base_end_datetime_utc)) |
|
270 | rows_space_hourly = cursor_energy.fetchall() |
|
271 | ||
272 | rows_space_periodically, \ |
|
273 | base[energy_category_id]['average'], \ |
|
274 | base[energy_category_id]['maximum'] = \ |
|
275 | utilities.averaging_hourly_data_by_period(rows_space_hourly, |
|
276 | base_start_datetime_utc, |
|
277 | base_end_datetime_utc, |
|
278 | period_type) |
|
279 | base[energy_category_id]['factor'] = \ |
|
280 | (base[energy_category_id]['average'] / base[energy_category_id]['maximum'] |
|
281 | if (base[energy_category_id]['average'] is not None and |
|
282 | base[energy_category_id]['maximum'] is not None and |
|
283 | base[energy_category_id]['maximum'] > Decimal(0.0)) |
|
284 | else None) |
|
285 | ||
286 | for row_space_periodically in rows_space_periodically: |
|
287 | current_datetime_local = row_space_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
288 | timedelta(minutes=timezone_offset) |
|
289 | if period_type == 'hourly': |
|
290 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
291 | elif period_type == 'daily': |
|
292 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
293 | elif period_type == 'monthly': |
|
294 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
295 | elif period_type == 'yearly': |
|
296 | current_datetime = current_datetime_local.strftime('%Y') |
|
297 | ||
298 | base[energy_category_id]['timestamps'].append(current_datetime) |
|
299 | base[energy_category_id]['sub_averages'].append(row_space_periodically[1]) |
|
300 | base[energy_category_id]['sub_maximums'].append(row_space_periodically[2]) |
|
301 | ||
302 | ################################################################################################################ |
|
303 | # Step 7: query reporting period energy input |
|
304 | ################################################################################################################ |
|
305 | reporting = dict() |
|
306 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
307 | for energy_category_id in energy_category_set: |
|
308 | reporting[energy_category_id] = dict() |
|
309 | reporting[energy_category_id]['timestamps'] = list() |
|
310 | reporting[energy_category_id]['sub_averages'] = list() |
|
311 | reporting[energy_category_id]['sub_maximums'] = list() |
|
312 | reporting[energy_category_id]['average'] = None |
|
313 | reporting[energy_category_id]['maximum'] = None |
|
314 | reporting[energy_category_id]['factor'] = None |
|
315 | ||
316 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
317 | " FROM tbl_space_input_category_hourly " |
|
318 | " WHERE space_id = %s " |
|
319 | " AND energy_category_id = %s " |
|
320 | " AND start_datetime_utc >= %s " |
|
321 | " AND start_datetime_utc < %s " |
|
322 | " ORDER BY start_datetime_utc ", |
|
323 | (space['id'], |
|
324 | energy_category_id, |
|
325 | reporting_start_datetime_utc, |
|
326 | reporting_end_datetime_utc)) |
|
327 | rows_space_hourly = cursor_energy.fetchall() |
|
328 | ||
329 | rows_space_periodically, \ |
|
330 | reporting[energy_category_id]['average'], \ |
|
331 | reporting[energy_category_id]['maximum'] = \ |
|
332 | utilities.averaging_hourly_data_by_period(rows_space_hourly, |
|
333 | reporting_start_datetime_utc, |
|
334 | reporting_end_datetime_utc, |
|
335 | period_type) |
|
336 | reporting[energy_category_id]['factor'] = \ |
|
337 | (reporting[energy_category_id]['average'] / reporting[energy_category_id]['maximum'] |
|
338 | if (reporting[energy_category_id]['average'] is not None and |
|
339 | reporting[energy_category_id]['maximum'] is not None and |
|
340 | reporting[energy_category_id]['maximum'] > Decimal(0.0)) |
|
341 | else None) |
|
342 | ||
343 | for row_space_periodically in rows_space_periodically: |
|
344 | current_datetime_local = row_space_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
345 | timedelta(minutes=timezone_offset) |
|
346 | if period_type == 'hourly': |
|
347 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
348 | elif period_type == 'daily': |
|
349 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
350 | elif period_type == 'monthly': |
|
351 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
352 | elif period_type == 'yearly': |
|
353 | current_datetime = current_datetime_local.strftime('%Y') |
|
354 | ||
355 | reporting[energy_category_id]['timestamps'].append(current_datetime) |
|
356 | reporting[energy_category_id]['sub_averages'].append(row_space_periodically[1]) |
|
357 | reporting[energy_category_id]['sub_maximums'].append(row_space_periodically[2]) |
|
358 | ||
359 | ################################################################################################################ |
|
360 | # Step 8: query tariff data |
|
361 | ################################################################################################################ |
|
362 | parameters_data = dict() |
|
363 | parameters_data['names'] = list() |
|
364 | parameters_data['timestamps'] = list() |
|
365 | parameters_data['values'] = list() |
|
366 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
367 | for energy_category_id in energy_category_set: |
|
368 | energy_category_tariff_dict = utilities.get_energy_category_tariffs(space['cost_center_id'], |
|
369 | energy_category_id, |
|
370 | reporting_start_datetime_utc, |
|
371 | reporting_end_datetime_utc) |
|
372 | tariff_timestamp_list = list() |
|
373 | tariff_value_list = list() |
|
374 | for k, v in energy_category_tariff_dict.items(): |
|
375 | # convert k from utc to local |
|
376 | k = k + timedelta(minutes=timezone_offset) |
|
377 | tariff_timestamp_list.append(k.isoformat()[0:19][0:19]) |
|
378 | tariff_value_list.append(v) |
|
379 | ||
380 | parameters_data['names'].append('TARIFF-' + energy_category_dict[energy_category_id]['name']) |
|
381 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
382 | parameters_data['values'].append(tariff_value_list) |
|
383 | ||
384 | ################################################################################################################ |
|
385 | # Step 9: query associated sensors and points data |
|
386 | ################################################################################################################ |
|
387 | for point in point_list: |
|
388 | point_values = [] |
|
389 | point_timestamps = [] |
|
390 | if point['object_type'] == 'ANALOG_VALUE': |
|
391 | query = (" SELECT utc_date_time, actual_value " |
|
392 | " FROM tbl_analog_value " |
|
393 | " WHERE point_id = %s " |
|
394 | " AND utc_date_time BETWEEN %s AND %s " |
|
395 | " ORDER BY utc_date_time ") |
|
396 | cursor_historical.execute(query, (point['id'], |
|
397 | reporting_start_datetime_utc, |
|
398 | reporting_end_datetime_utc)) |
|
399 | rows = cursor_historical.fetchall() |
|
400 | ||
401 | if rows is not None and len(rows) > 0: |
|
402 | for row in rows: |
|
403 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
404 | timedelta(minutes=timezone_offset) |
|
405 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
406 | point_timestamps.append(current_datetime) |
|
407 | point_values.append(row[1]) |
|
408 | ||
409 | elif point['object_type'] == 'ENERGY_VALUE': |
|
410 | query = (" SELECT utc_date_time, actual_value " |
|
411 | " FROM tbl_energy_value " |
|
412 | " WHERE point_id = %s " |
|
413 | " AND utc_date_time BETWEEN %s AND %s " |
|
414 | " ORDER BY utc_date_time ") |
|
415 | cursor_historical.execute(query, (point['id'], |
|
416 | reporting_start_datetime_utc, |
|
417 | reporting_end_datetime_utc)) |
|
418 | rows = cursor_historical.fetchall() |
|
419 | ||
420 | if rows is not None and len(rows) > 0: |
|
421 | for row in rows: |
|
422 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
423 | timedelta(minutes=timezone_offset) |
|
424 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
425 | point_timestamps.append(current_datetime) |
|
426 | point_values.append(row[1]) |
|
427 | elif point['object_type'] == 'DIGITAL_VALUE': |
|
428 | query = (" SELECT utc_date_time, actual_value " |
|
429 | " FROM tbl_digital_value " |
|
430 | " WHERE point_id = %s " |
|
431 | " AND utc_date_time BETWEEN %s AND %s ") |
|
432 | cursor_historical.execute(query, (point['id'], |
|
433 | reporting_start_datetime_utc, |
|
434 | reporting_end_datetime_utc)) |
|
435 | rows = cursor_historical.fetchall() |
|
436 | ||
437 | if rows is not None and len(rows) > 0: |
|
438 | for row in rows: |
|
439 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
440 | timedelta(minutes=timezone_offset) |
|
441 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
442 | point_timestamps.append(current_datetime) |
|
443 | point_values.append(row[1]) |
|
444 | ||
445 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
|
446 | parameters_data['timestamps'].append(point_timestamps) |
|
447 | parameters_data['values'].append(point_values) |
|
448 | ||
449 | ################################################################################################################ |
|
450 | # Step 10: construct the report |
|
451 | ################################################################################################################ |
|
452 | if cursor_system: |
|
453 | cursor_system.close() |
|
454 | if cnx_system: |
|
455 | cnx_system.disconnect() |
|
456 | ||
457 | if cursor_energy: |
|
458 | cursor_energy.close() |
|
459 | if cnx_energy: |
|
460 | cnx_energy.disconnect() |
|
461 | ||
462 | result = dict() |
|
463 | ||
464 | result['space'] = dict() |
|
465 | result['space']['name'] = space['name'] |
|
466 | result['space']['area'] = space['area'] |
|
467 | ||
468 | result['base_period'] = dict() |
|
469 | result['base_period']['names'] = list() |
|
470 | result['base_period']['units'] = list() |
|
471 | result['base_period']['timestamps'] = list() |
|
472 | result['base_period']['sub_averages'] = list() |
|
473 | result['base_period']['sub_maximums'] = list() |
|
474 | result['base_period']['averages'] = list() |
|
475 | result['base_period']['maximums'] = list() |
|
476 | result['base_period']['factors'] = list() |
|
477 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
478 | for energy_category_id in energy_category_set: |
|
479 | result['base_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
480 | result['base_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
481 | result['base_period']['timestamps'].append(base[energy_category_id]['timestamps']) |
|
482 | result['base_period']['sub_averages'].append(base[energy_category_id]['sub_averages']) |
|
483 | result['base_period']['sub_maximums'].append(base[energy_category_id]['sub_maximums']) |
|
484 | result['base_period']['averages'].append(base[energy_category_id]['average']) |
|
485 | result['base_period']['maximums'].append(base[energy_category_id]['maximum']) |
|
486 | result['base_period']['factors'].append(base[energy_category_id]['factor']) |
|
487 | ||
488 | result['reporting_period'] = dict() |
|
489 | result['reporting_period']['names'] = list() |
|
490 | result['reporting_period']['energy_category_ids'] = list() |
|
491 | result['reporting_period']['units'] = list() |
|
492 | result['reporting_period']['timestamps'] = list() |
|
493 | result['reporting_period']['sub_averages'] = list() |
|
494 | result['reporting_period']['sub_maximums'] = list() |
|
495 | result['reporting_period']['averages'] = list() |
|
496 | result['reporting_period']['averages_per_unit_area'] = list() |
|
497 | result['reporting_period']['averages_increment_rate'] = list() |
|
498 | result['reporting_period']['maximums'] = list() |
|
499 | result['reporting_period']['maximums_per_unit_area'] = list() |
|
500 | result['reporting_period']['maximums_increment_rate'] = list() |
|
501 | result['reporting_period']['factors'] = list() |
|
502 | result['reporting_period']['factors_increment_rate'] = list() |
|
503 | ||
504 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
505 | for energy_category_id in energy_category_set: |
|
506 | result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
507 | result['reporting_period']['energy_category_ids'].append(energy_category_id) |
|
508 | result['reporting_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
509 | result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps']) |
|
510 | result['reporting_period']['sub_averages'].append(reporting[energy_category_id]['sub_averages']) |
|
511 | result['reporting_period']['sub_maximums'].append(reporting[energy_category_id]['sub_maximums']) |
|
512 | result['reporting_period']['averages'].append(reporting[energy_category_id]['average']) |
|
513 | result['reporting_period']['averages_per_unit_area'].append( |
|
514 | reporting[energy_category_id]['average'] / space['area'] |
|
515 | if reporting[energy_category_id]['average'] is not None and |
|
516 | space['area'] is not None and |
|
517 | space['area'] > Decimal(0.0) |
|
518 | else None) |
|
519 | result['reporting_period']['averages_increment_rate'].append( |
|
520 | (reporting[energy_category_id]['average'] - base[energy_category_id]['average']) / |
|
521 | base[energy_category_id]['average'] if (base[energy_category_id]['average'] is not None and |
|
522 | base[energy_category_id]['average'] > Decimal(0.0)) |
|
523 | else None) |
|
524 | result['reporting_period']['maximums'].append(reporting[energy_category_id]['maximum']) |
|
525 | result['reporting_period']['maximums_increment_rate'].append( |
|
526 | (reporting[energy_category_id]['maximum'] - base[energy_category_id]['maximum']) / |
|
527 | base[energy_category_id]['maximum'] if (base[energy_category_id]['maximum'] is not None and |
|
528 | base[energy_category_id]['maximum'] > Decimal(0.0)) |
|
529 | else None) |
|
530 | result['reporting_period']['maximums_per_unit_area'].append( |
|
531 | reporting[energy_category_id]['maximum'] / space['area'] |
|
532 | if reporting[energy_category_id]['maximum'] is not None and |
|
533 | space['area'] is not None and |
|
534 | space['area'] > Decimal(0.0) |
|
535 | else None) |
|
536 | result['reporting_period']['factors'].append(reporting[energy_category_id]['factor']) |
|
537 | result['reporting_period']['factors_increment_rate'].append( |
|
538 | (reporting[energy_category_id]['factor'] - base[energy_category_id]['factor']) / |
|
539 | base[energy_category_id]['factor'] if (base[energy_category_id]['factor'] is not None and |
|
540 | base[energy_category_id]['factor'] > Decimal(0.0)) |
|
541 | else None) |
|
542 | ||
543 | result['parameters'] = { |
|
544 | "names": parameters_data['names'], |
|
545 | "timestamps": parameters_data['timestamps'], |
|
546 | "values": parameters_data['values'] |
|
547 | } |
|
548 | ||
549 | resp.body = json.dumps(result) |
|
550 |