Total Complexity | 115 |
Total Lines | 596 |
Duplicated Lines | 4.03 % |
Changes | 0 |
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like reports.spaceenergyitem often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | import falcon |
||
2 | import simplejson as json |
||
3 | import mysql.connector |
||
4 | import config |
||
5 | from datetime import datetime, timedelta, timezone |
||
6 | from core import utilities |
||
7 | from decimal import Decimal |
||
8 | import excelexporters.spaceenergyitem |
||
9 | |||
10 | |||
11 | class Reporting: |
||
12 | @staticmethod |
||
13 | def __init__(): |
||
14 | pass |
||
15 | |||
16 | @staticmethod |
||
17 | def on_options(req, resp): |
||
18 | resp.status = falcon.HTTP_200 |
||
19 | |||
20 | #################################################################################################################### |
||
21 | # PROCEDURES |
||
22 | # Step 1: valid parameters |
||
23 | # Step 2: query the space |
||
24 | # Step 3: query energy items |
||
25 | # Step 4: query associated sensors |
||
26 | # Step 5: query associated points |
||
27 | # Step 6: query child spaces |
||
28 | # Step 7: query base period energy input |
||
29 | # Step 8: query reporting period energy input |
||
30 | # Step 9: query tariff data |
||
31 | # Step 10: query associated sensors and points data |
||
32 | # Step 11: query child spaces energy input |
||
33 | # Step 12: construct the report |
||
34 | #################################################################################################################### |
||
35 | @staticmethod |
||
36 | def on_get(req, resp): |
||
37 | print(req.params) |
||
38 | space_id = req.params.get('spaceid') |
||
39 | period_type = req.params.get('periodtype') |
||
40 | base_start_datetime_local = req.params.get('baseperiodstartdatetime') |
||
41 | base_end_datetime_local = req.params.get('baseperiodenddatetime') |
||
42 | reporting_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
||
43 | reporting_end_datetime_local = req.params.get('reportingperiodenddatetime') |
||
44 | |||
45 | ################################################################################################################ |
||
46 | # Step 1: valid parameters |
||
47 | ################################################################################################################ |
||
48 | if space_id is None: |
||
49 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_SPACE_ID') |
||
50 | else: |
||
51 | space_id = str.strip(space_id) |
||
52 | if not space_id.isdigit() or int(space_id) <= 0: |
||
53 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_SPACE_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 space |
||
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, area, cost_center_id " |
||
136 | " FROM tbl_spaces " |
||
137 | " WHERE id = %s ", (space_id,)) |
||
138 | row_space = cursor_system.fetchone() |
||
139 | if row_space 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, title='API.NOT_FOUND', description='API.SPACE_NOT_FOUND') |
||
155 | |||
156 | space = dict() |
||
157 | space['id'] = row_space[0] |
||
158 | space['name'] = row_space[1] |
||
159 | space['area'] = row_space[2] |
||
160 | space['cost_center_id'] = row_space[3] |
||
161 | |||
162 | ################################################################################################################ |
||
163 | # Step 3: query energy items |
||
164 | ################################################################################################################ |
||
165 | energy_item_set = set() |
||
166 | # query energy items in base period |
||
167 | cursor_energy.execute(" SELECT DISTINCT(energy_item_id) " |
||
168 | " FROM tbl_space_input_item_hourly " |
||
169 | " WHERE space_id = %s " |
||
170 | " AND start_datetime_utc >= %s " |
||
171 | " AND start_datetime_utc < %s ", |
||
172 | (space['id'], base_start_datetime_utc, base_end_datetime_utc)) |
||
173 | rows_energy_items = cursor_energy.fetchall() |
||
174 | if rows_energy_items is not None or len(rows_energy_items) > 0: |
||
175 | for row_item in rows_energy_items: |
||
176 | energy_item_set.add(row_item[0]) |
||
177 | |||
178 | # query energy items in reporting period |
||
179 | cursor_energy.execute(" SELECT DISTINCT(energy_item_id) " |
||
180 | " FROM tbl_space_input_item_hourly " |
||
181 | " WHERE space_id = %s " |
||
182 | " AND start_datetime_utc >= %s " |
||
183 | " AND start_datetime_utc < %s ", |
||
184 | (space['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
||
185 | rows_energy_items = cursor_energy.fetchall() |
||
186 | if rows_energy_items is not None or len(rows_energy_items) > 0: |
||
187 | for row_item in rows_energy_items: |
||
188 | energy_item_set.add(row_item[0]) |
||
189 | |||
190 | # query all energy items in base period and reporting period |
||
191 | cursor_system.execute(" SELECT ei.id, ei.name, ei.energy_category_id, " |
||
192 | " ec.name AS energy_category_name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
||
193 | " FROM tbl_energy_items ei, tbl_energy_categories ec " |
||
194 | " WHERE ei.energy_category_id = ec.id " |
||
195 | " ORDER BY ei.id ", ) |
||
196 | rows_energy_items = cursor_system.fetchall() |
||
197 | if rows_energy_items is None or len(rows_energy_items) == 0: |
||
198 | if cursor_system: |
||
199 | cursor_system.close() |
||
200 | if cnx_system: |
||
201 | cnx_system.disconnect() |
||
202 | |||
203 | if cursor_energy: |
||
204 | cursor_energy.close() |
||
205 | if cnx_energy: |
||
206 | cnx_energy.disconnect() |
||
207 | |||
208 | if cnx_historical: |
||
209 | cnx_historical.close() |
||
210 | if cursor_historical: |
||
211 | cursor_historical.disconnect() |
||
212 | raise falcon.HTTPError(falcon.HTTP_404, |
||
213 | title='API.NOT_FOUND', |
||
214 | description='API.ENERGY_ITEM_NOT_FOUND') |
||
215 | energy_item_dict = dict() |
||
216 | for row_energy_item in rows_energy_items: |
||
217 | if row_energy_item[0] in energy_item_set: |
||
218 | energy_item_dict[row_energy_item[0]] = {"name": row_energy_item[1], |
||
219 | "energy_category_id": row_energy_item[2], |
||
220 | "energy_category_name": row_energy_item[3], |
||
221 | "unit_of_measure": row_energy_item[4], |
||
222 | "kgce": row_energy_item[5], |
||
223 | "kgco2e": row_energy_item[6]} |
||
224 | |||
225 | ################################################################################################################ |
||
226 | # Step 4: query associated sensors |
||
227 | ################################################################################################################ |
||
228 | point_list = list() |
||
229 | cursor_system.execute(" SELECT po.id, po.name, po.units, po.object_type " |
||
230 | " FROM tbl_spaces sp, tbl_sensors se, tbl_spaces_sensors spse, " |
||
231 | " tbl_points po, tbl_sensors_points sepo " |
||
232 | " WHERE sp.id = %s AND sp.id = spse.space_id AND spse.sensor_id = se.id " |
||
233 | " AND se.id = sepo.sensor_id AND sepo.point_id = po.id " |
||
234 | " ORDER BY po.id ", (space['id'], )) |
||
235 | rows_points = cursor_system.fetchall() |
||
236 | if rows_points is not None and len(rows_points) > 0: |
||
237 | for row in rows_points: |
||
238 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
||
239 | |||
240 | ################################################################################################################ |
||
241 | # Step 5: query associated points |
||
242 | ################################################################################################################ |
||
243 | cursor_system.execute(" SELECT po.id, po.name, po.units, po.object_type " |
||
244 | " FROM tbl_spaces sp, tbl_spaces_points sppo, tbl_points po " |
||
245 | " WHERE sp.id = %s AND sp.id = sppo.space_id AND sppo.point_id = po.id " |
||
246 | " ORDER BY po.id ", (space['id'], )) |
||
247 | rows_points = cursor_system.fetchall() |
||
248 | if rows_points is not None and len(rows_points) > 0: |
||
249 | for row in rows_points: |
||
250 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
||
251 | |||
252 | ################################################################################################################ |
||
253 | # Step 6: query child spaces |
||
254 | ################################################################################################################ |
||
255 | child_space_list = list() |
||
256 | cursor_system.execute(" SELECT id, name " |
||
257 | " FROM tbl_spaces " |
||
258 | " WHERE parent_space_id = %s " |
||
259 | " ORDER BY id ", (space['id'], )) |
||
260 | rows_child_spaces = cursor_system.fetchall() |
||
261 | if rows_child_spaces is not None and len(rows_child_spaces) > 0: |
||
262 | for row in rows_child_spaces: |
||
263 | child_space_list.append({"id": row[0], "name": row[1]}) |
||
264 | |||
265 | ################################################################################################################ |
||
266 | # Step 7: query base period energy input |
||
267 | ################################################################################################################ |
||
268 | base = dict() |
||
269 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
270 | for energy_item_id in energy_item_set: |
||
271 | base[energy_item_id] = dict() |
||
272 | base[energy_item_id]['timestamps'] = list() |
||
273 | base[energy_item_id]['values'] = list() |
||
274 | base[energy_item_id]['subtotal'] = Decimal(0.0) |
||
275 | |||
276 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
||
277 | " FROM tbl_space_input_item_hourly " |
||
278 | " WHERE space_id = %s " |
||
279 | " AND energy_item_id = %s " |
||
280 | " AND start_datetime_utc >= %s " |
||
281 | " AND start_datetime_utc < %s " |
||
282 | " ORDER BY start_datetime_utc ", |
||
283 | (space['id'], |
||
284 | energy_item_id, |
||
285 | base_start_datetime_utc, |
||
286 | base_end_datetime_utc)) |
||
287 | rows_space_hourly = cursor_energy.fetchall() |
||
288 | |||
289 | rows_space_periodically = utilities.aggregate_hourly_data_by_period(rows_space_hourly, |
||
290 | base_start_datetime_utc, |
||
291 | base_end_datetime_utc, |
||
292 | period_type) |
||
293 | for row_space_periodically in rows_space_periodically: |
||
294 | current_datetime_local = row_space_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
295 | timedelta(minutes=timezone_offset) |
||
296 | if period_type == 'hourly': |
||
297 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
298 | elif period_type == 'daily': |
||
299 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
||
300 | elif period_type == 'monthly': |
||
301 | current_datetime = current_datetime_local.strftime('%Y-%m') |
||
302 | elif period_type == 'yearly': |
||
303 | current_datetime = current_datetime_local.strftime('%Y') |
||
304 | |||
305 | actual_value = Decimal(0.0) if row_space_periodically[1] is None else row_space_periodically[1] |
||
306 | base[energy_item_id]['timestamps'].append(current_datetime) |
||
|
|||
307 | base[energy_item_id]['values'].append(actual_value) |
||
308 | base[energy_item_id]['subtotal'] += actual_value |
||
309 | |||
310 | ################################################################################################################ |
||
311 | # Step 8: query reporting period energy input |
||
312 | ################################################################################################################ |
||
313 | reporting = dict() |
||
314 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
315 | for energy_item_id in energy_item_set: |
||
316 | reporting[energy_item_id] = dict() |
||
317 | reporting[energy_item_id]['timestamps'] = list() |
||
318 | reporting[energy_item_id]['values'] = list() |
||
319 | reporting[energy_item_id]['subtotal'] = Decimal(0.0) |
||
320 | reporting[energy_item_id]['toppeak'] = Decimal(0.0) |
||
321 | reporting[energy_item_id]['onpeak'] = Decimal(0.0) |
||
322 | reporting[energy_item_id]['midpeak'] = Decimal(0.0) |
||
323 | reporting[energy_item_id]['offpeak'] = Decimal(0.0) |
||
324 | |||
325 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
||
326 | " FROM tbl_space_input_item_hourly " |
||
327 | " WHERE space_id = %s " |
||
328 | " AND energy_item_id = %s " |
||
329 | " AND start_datetime_utc >= %s " |
||
330 | " AND start_datetime_utc < %s " |
||
331 | " ORDER BY start_datetime_utc ", |
||
332 | (space['id'], |
||
333 | energy_item_id, |
||
334 | reporting_start_datetime_utc, |
||
335 | reporting_end_datetime_utc)) |
||
336 | rows_space_hourly = cursor_energy.fetchall() |
||
337 | |||
338 | rows_space_periodically = utilities.aggregate_hourly_data_by_period(rows_space_hourly, |
||
339 | reporting_start_datetime_utc, |
||
340 | reporting_end_datetime_utc, |
||
341 | period_type) |
||
342 | for row_space_periodically in rows_space_periodically: |
||
343 | current_datetime_local = row_space_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
344 | timedelta(minutes=timezone_offset) |
||
345 | if period_type == 'hourly': |
||
346 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
347 | elif period_type == 'daily': |
||
348 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
||
349 | elif period_type == 'monthly': |
||
350 | current_datetime = current_datetime_local.strftime('%Y-%m') |
||
351 | elif period_type == 'yearly': |
||
352 | current_datetime = current_datetime_local.strftime('%Y') |
||
353 | |||
354 | actual_value = Decimal(0.0) if row_space_periodically[1] is None else row_space_periodically[1] |
||
355 | reporting[energy_item_id]['timestamps'].append(current_datetime) |
||
356 | reporting[energy_item_id]['values'].append(actual_value) |
||
357 | reporting[energy_item_id]['subtotal'] += actual_value |
||
358 | |||
359 | energy_category_tariff_dict = \ |
||
360 | utilities.get_energy_category_peak_types(space['cost_center_id'], |
||
361 | energy_item_dict[energy_item_id]['energy_category_id'], |
||
362 | reporting_start_datetime_utc, |
||
363 | reporting_end_datetime_utc) |
||
364 | for row in rows_space_hourly: |
||
365 | peak_type = energy_category_tariff_dict.get(row[0], None) |
||
366 | if peak_type == 'toppeak': |
||
367 | reporting[energy_item_id]['toppeak'] += row[1] |
||
368 | elif peak_type == 'onpeak': |
||
369 | reporting[energy_item_id]['onpeak'] += row[1] |
||
370 | elif peak_type == 'midpeak': |
||
371 | reporting[energy_item_id]['midpeak'] += row[1] |
||
372 | elif peak_type == 'offpeak': |
||
373 | reporting[energy_item_id]['offpeak'] += row[1] |
||
374 | |||
375 | ################################################################################################################ |
||
376 | # Step 9: query tariff data |
||
377 | ################################################################################################################ |
||
378 | parameters_data = dict() |
||
379 | parameters_data['names'] = list() |
||
380 | parameters_data['timestamps'] = list() |
||
381 | parameters_data['values'] = list() |
||
382 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
383 | for energy_item_id in energy_item_set: |
||
384 | energy_category_tariff_dict = \ |
||
385 | utilities.get_energy_category_tariffs(space['cost_center_id'], |
||
386 | energy_item_dict[energy_item_id]['energy_category_id'], |
||
387 | reporting_start_datetime_utc, |
||
388 | reporting_end_datetime_utc) |
||
389 | tariff_timestamp_list = list() |
||
390 | tariff_value_list = list() |
||
391 | for k, v in energy_category_tariff_dict.items(): |
||
392 | # convert k from utc to local |
||
393 | k = k + timedelta(minutes=timezone_offset) |
||
394 | tariff_timestamp_list.append(k.isoformat()[0:19][0:19]) |
||
395 | tariff_value_list.append(v) |
||
396 | |||
397 | parameters_data['names'].append('TARIFF-' + energy_item_dict[energy_item_id]['name']) |
||
398 | parameters_data['timestamps'].append(tariff_timestamp_list) |
||
399 | parameters_data['values'].append(tariff_value_list) |
||
400 | |||
401 | ################################################################################################################ |
||
402 | # Step 10: query associated sensors and points data |
||
403 | ################################################################################################################ |
||
404 | for point in point_list: |
||
405 | point_values = [] |
||
406 | point_timestamps = [] |
||
407 | if point['object_type'] == 'ANALOG_VALUE': |
||
408 | query = (" SELECT utc_date_time, actual_value " |
||
409 | " FROM tbl_analog_value " |
||
410 | " WHERE point_id = %s " |
||
411 | " AND utc_date_time BETWEEN %s AND %s " |
||
412 | " ORDER BY utc_date_time ") |
||
413 | cursor_historical.execute(query, (point['id'], |
||
414 | reporting_start_datetime_utc, |
||
415 | reporting_end_datetime_utc)) |
||
416 | rows = cursor_historical.fetchall() |
||
417 | |||
418 | if rows is not None and len(rows) > 0: |
||
419 | for row in rows: |
||
420 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
421 | timedelta(minutes=timezone_offset) |
||
422 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
423 | point_timestamps.append(current_datetime) |
||
424 | point_values.append(row[1]) |
||
425 | |||
426 | elif point['object_type'] == 'ENERGY_VALUE': |
||
427 | query = (" SELECT utc_date_time, actual_value " |
||
428 | " FROM tbl_energy_value " |
||
429 | " WHERE point_id = %s " |
||
430 | " AND utc_date_time BETWEEN %s AND %s " |
||
431 | " ORDER BY utc_date_time ") |
||
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 | elif point['object_type'] == 'DIGITAL_VALUE': |
||
445 | query = (" SELECT utc_date_time, actual_value " |
||
446 | " FROM tbl_digital_value " |
||
447 | " WHERE point_id = %s " |
||
448 | " AND utc_date_time BETWEEN %s AND %s ") |
||
449 | cursor_historical.execute(query, (point['id'], |
||
450 | reporting_start_datetime_utc, |
||
451 | reporting_end_datetime_utc)) |
||
452 | rows = cursor_historical.fetchall() |
||
453 | |||
454 | if rows is not None and len(rows) > 0: |
||
455 | for row in rows: |
||
456 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
457 | timedelta(minutes=timezone_offset) |
||
458 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
459 | point_timestamps.append(current_datetime) |
||
460 | point_values.append(row[1]) |
||
461 | |||
462 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
||
463 | parameters_data['timestamps'].append(point_timestamps) |
||
464 | parameters_data['values'].append(point_values) |
||
465 | |||
466 | ################################################################################################################ |
||
467 | # Step 11: query child spaces energy input |
||
468 | ################################################################################################################ |
||
469 | child_space_data = dict() |
||
470 | |||
471 | View Code Duplication | if energy_item_set is not None and len(energy_item_set) > 0: |
|
472 | for energy_item_id in energy_item_set: |
||
473 | child_space_data[energy_item_id] = dict() |
||
474 | child_space_data[energy_item_id]['child_space_names'] = list() |
||
475 | child_space_data[energy_item_id]['subtotals'] = list() |
||
476 | |||
477 | for child_space in child_space_list: |
||
478 | child_space_data[energy_item_id]['child_space_names'].append(child_space['name']) |
||
479 | |||
480 | cursor_energy.execute(" SELECT SUM(actual_value) " |
||
481 | " FROM tbl_space_input_item_hourly " |
||
482 | " WHERE space_id = %s " |
||
483 | " AND energy_item_id = %s " |
||
484 | " AND start_datetime_utc >= %s " |
||
485 | " AND start_datetime_utc < %s " |
||
486 | " ORDER BY start_datetime_utc ", |
||
487 | (child_space['id'], |
||
488 | energy_item_id, |
||
489 | reporting_start_datetime_utc, |
||
490 | reporting_end_datetime_utc)) |
||
491 | row_subtotal = cursor_energy.fetchone() |
||
492 | |||
493 | subtotal = Decimal(0.0) if (row_subtotal is None or row_subtotal[0] is None) else row_subtotal[0] |
||
494 | child_space_data[energy_item_id]['subtotals'].append(subtotal) |
||
495 | |||
496 | ################################################################################################################ |
||
497 | # Step 12: construct the report |
||
498 | ################################################################################################################ |
||
499 | if cursor_system: |
||
500 | cursor_system.close() |
||
501 | if cnx_system: |
||
502 | cnx_system.disconnect() |
||
503 | |||
504 | if cursor_energy: |
||
505 | cursor_energy.close() |
||
506 | if cnx_energy: |
||
507 | cnx_energy.disconnect() |
||
508 | |||
509 | result = dict() |
||
510 | |||
511 | result['space'] = dict() |
||
512 | result['space']['name'] = space['name'] |
||
513 | result['space']['area'] = space['area'] |
||
514 | |||
515 | result['base_period'] = dict() |
||
516 | result['base_period']['names'] = list() |
||
517 | result['base_period']['units'] = list() |
||
518 | result['base_period']['timestamps'] = list() |
||
519 | result['base_period']['values'] = list() |
||
520 | result['base_period']['subtotals'] = list() |
||
521 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
522 | for energy_item_id in energy_item_set: |
||
523 | result['base_period']['names'].append(energy_item_dict[energy_item_id]['name']) |
||
524 | result['base_period']['units'].append(energy_item_dict[energy_item_id]['unit_of_measure']) |
||
525 | result['base_period']['timestamps'].append(base[energy_item_id]['timestamps']) |
||
526 | result['base_period']['values'].append(base[energy_item_id]['values']) |
||
527 | result['base_period']['subtotals'].append(base[energy_item_id]['subtotal']) |
||
528 | |||
529 | result['reporting_period'] = dict() |
||
530 | result['reporting_period']['names'] = list() |
||
531 | result['reporting_period']['energy_item_ids'] = list() |
||
532 | result['reporting_period']['energy_category_names'] = list() |
||
533 | result['reporting_period']['energy_category_ids'] = list() |
||
534 | result['reporting_period']['units'] = list() |
||
535 | result['reporting_period']['timestamps'] = list() |
||
536 | result['reporting_period']['values'] = list() |
||
537 | result['reporting_period']['subtotals'] = list() |
||
538 | result['reporting_period']['subtotals_per_unit_area'] = list() |
||
539 | result['reporting_period']['toppeaks'] = list() |
||
540 | result['reporting_period']['onpeaks'] = list() |
||
541 | result['reporting_period']['midpeaks'] = list() |
||
542 | result['reporting_period']['offpeaks'] = list() |
||
543 | result['reporting_period']['increment_rates'] = list() |
||
544 | |||
545 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
546 | for energy_item_id in energy_item_set: |
||
547 | result['reporting_period']['names'].append(energy_item_dict[energy_item_id]['name']) |
||
548 | result['reporting_period']['energy_item_ids'].append(energy_item_id) |
||
549 | result['reporting_period']['energy_category_names'].append( |
||
550 | energy_item_dict[energy_item_id]['energy_category_name']) |
||
551 | result['reporting_period']['energy_category_ids'].append( |
||
552 | energy_item_dict[energy_item_id]['energy_category_id']) |
||
553 | result['reporting_period']['units'].append(energy_item_dict[energy_item_id]['unit_of_measure']) |
||
554 | result['reporting_period']['timestamps'].append(reporting[energy_item_id]['timestamps']) |
||
555 | result['reporting_period']['values'].append(reporting[energy_item_id]['values']) |
||
556 | result['reporting_period']['subtotals'].append(reporting[energy_item_id]['subtotal']) |
||
557 | result['reporting_period']['subtotals_per_unit_area'].append( |
||
558 | reporting[energy_item_id]['subtotal'] / space['area'] if space['area'] > 0.0 else None) |
||
559 | result['reporting_period']['toppeaks'].append(reporting[energy_item_id]['toppeak']) |
||
560 | result['reporting_period']['onpeaks'].append(reporting[energy_item_id]['onpeak']) |
||
561 | result['reporting_period']['midpeaks'].append(reporting[energy_item_id]['midpeak']) |
||
562 | result['reporting_period']['offpeaks'].append(reporting[energy_item_id]['offpeak']) |
||
563 | result['reporting_period']['increment_rates'].append( |
||
564 | (reporting[energy_item_id]['subtotal'] - base[energy_item_id]['subtotal']) / |
||
565 | base[energy_item_id]['subtotal'] |
||
566 | if base[energy_item_id]['subtotal'] > 0.0 else None) |
||
567 | |||
568 | result['parameters'] = { |
||
569 | "names": parameters_data['names'], |
||
570 | "timestamps": parameters_data['timestamps'], |
||
571 | "values": parameters_data['values'] |
||
572 | } |
||
573 | |||
574 | result['child_space'] = dict() |
||
575 | result['child_space']['energy_item_names'] = list() # 1D array [energy item] |
||
576 | result['child_space']['units'] = list() # 1D array [energy item] |
||
577 | result['child_space']['child_space_names_array'] = list() # 2D array [energy item][child space] |
||
578 | result['child_space']['subtotals_array'] = list() # 2D array [energy item][child space] |
||
579 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
580 | for energy_item_id in energy_item_set: |
||
581 | result['child_space']['energy_item_names'].append(energy_item_dict[energy_item_id]['name']) |
||
582 | result['child_space']['units'].append(energy_item_dict[energy_item_id]['unit_of_measure']) |
||
583 | result['child_space']['child_space_names_array'].append( |
||
584 | child_space_data[energy_item_id]['child_space_names']) |
||
585 | result['child_space']['subtotals_array'].append( |
||
586 | child_space_data[energy_item_id]['subtotals']) |
||
587 | |||
588 | # export result to Excel file and then encode the file to base64 string |
||
589 | result['excel_bytes_base64'] = excelexporters.spaceenergyitem.export(result, |
||
590 | space['name'], |
||
591 | reporting_start_datetime_local, |
||
592 | reporting_end_datetime_local, |
||
593 | period_type) |
||
594 | |||
595 | resp.body = json.dumps(result) |
||
596 |