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