Conditions | 113 |
Total Lines | 554 |
Code Lines | 403 |
Lines | 24 |
Ratio | 4.33 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like reports.spaceenergyitem.Reporting.on_get() 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 |
||
34 | @staticmethod |
||
35 | def on_get(req, resp): |
||
36 | print(req.params) |
||
37 | space_id = req.params.get('spaceid') |
||
38 | period_type = req.params.get('periodtype') |
||
39 | base_start_datetime_local = req.params.get('baseperiodstartdatetime') |
||
40 | base_end_datetime_local = req.params.get('baseperiodenddatetime') |
||
41 | reporting_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
||
42 | reporting_end_datetime_local = req.params.get('reportingperiodenddatetime') |
||
43 | |||
44 | ################################################################################################################ |
||
45 | # Step 1: valid parameters |
||
46 | ################################################################################################################ |
||
47 | if space_id is None: |
||
48 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_SPACE_ID') |
||
49 | else: |
||
50 | space_id = str.strip(space_id) |
||
51 | if not space_id.isdigit() or int(space_id) <= 0: |
||
52 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_SPACE_ID') |
||
53 | |||
54 | if period_type is None: |
||
55 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
||
56 | else: |
||
57 | period_type = str.strip(period_type) |
||
58 | if period_type not in ['hourly', 'daily', 'monthly', 'yearly']: |
||
59 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
||
60 | |||
61 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
62 | if config.utc_offset[0] == '-': |
||
63 | timezone_offset = -timezone_offset |
||
64 | |||
65 | base_start_datetime_utc = None |
||
66 | if base_start_datetime_local is not None and len(str.strip(base_start_datetime_local)) > 0: |
||
67 | base_start_datetime_local = str.strip(base_start_datetime_local) |
||
68 | try: |
||
69 | base_start_datetime_utc = datetime.strptime(base_start_datetime_local, |
||
70 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
71 | timedelta(minutes=timezone_offset) |
||
72 | except ValueError: |
||
73 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
74 | description="API.INVALID_BASE_PERIOD_BEGINS_DATETIME") |
||
75 | |||
76 | base_end_datetime_utc = None |
||
77 | if base_end_datetime_local is not None and len(str.strip(base_end_datetime_local)) > 0: |
||
78 | base_end_datetime_local = str.strip(base_end_datetime_local) |
||
79 | try: |
||
80 | base_end_datetime_utc = datetime.strptime(base_end_datetime_local, |
||
81 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
82 | timedelta(minutes=timezone_offset) |
||
83 | except ValueError: |
||
84 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
85 | description="API.INVALID_BASE_PERIOD_ENDS_DATETIME") |
||
86 | |||
87 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
||
88 | base_start_datetime_utc >= base_end_datetime_utc: |
||
89 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
90 | description='API.INVALID_BASE_PERIOD_ENDS_DATETIME') |
||
91 | |||
92 | if reporting_start_datetime_local is None: |
||
93 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
94 | description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME") |
||
95 | else: |
||
96 | reporting_start_datetime_local = str.strip(reporting_start_datetime_local) |
||
97 | try: |
||
98 | reporting_start_datetime_utc = datetime.strptime(reporting_start_datetime_local, |
||
99 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
100 | timedelta(minutes=timezone_offset) |
||
101 | except ValueError: |
||
102 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
103 | description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME") |
||
104 | |||
105 | if reporting_end_datetime_local is None: |
||
106 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
107 | description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME") |
||
108 | else: |
||
109 | reporting_end_datetime_local = str.strip(reporting_end_datetime_local) |
||
110 | try: |
||
111 | reporting_end_datetime_utc = datetime.strptime(reporting_end_datetime_local, |
||
112 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
113 | timedelta(minutes=timezone_offset) |
||
114 | except ValueError: |
||
115 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
116 | description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME") |
||
117 | |||
118 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
||
119 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
120 | description='API.INVALID_REPORTING_PERIOD_ENDS_DATETIME') |
||
121 | |||
122 | ################################################################################################################ |
||
123 | # Step 2: query the space |
||
124 | ################################################################################################################ |
||
125 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
||
126 | cursor_system = cnx_system.cursor() |
||
127 | |||
128 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
||
129 | cursor_energy = cnx_energy.cursor() |
||
130 | |||
131 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
||
132 | cursor_historical = cnx_historical.cursor() |
||
133 | |||
134 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
||
135 | " FROM tbl_spaces " |
||
136 | " WHERE id = %s ", (space_id,)) |
||
137 | row_space = cursor_system.fetchone() |
||
138 | if row_space is None: |
||
139 | if cursor_system: |
||
140 | cursor_system.close() |
||
141 | if cnx_system: |
||
142 | cnx_system.disconnect() |
||
143 | |||
144 | if cursor_energy: |
||
145 | cursor_energy.close() |
||
146 | if cnx_energy: |
||
147 | cnx_energy.disconnect() |
||
148 | |||
149 | if cnx_historical: |
||
150 | cnx_historical.close() |
||
151 | if cursor_historical: |
||
152 | cursor_historical.disconnect() |
||
153 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.SPACE_NOT_FOUND') |
||
154 | |||
155 | space = dict() |
||
156 | space['id'] = row_space[0] |
||
157 | space['name'] = row_space[1] |
||
158 | space['area'] = row_space[2] |
||
159 | space['cost_center_id'] = row_space[3] |
||
160 | |||
161 | ################################################################################################################ |
||
162 | # Step 3: query energy items |
||
163 | ################################################################################################################ |
||
164 | energy_item_set = set() |
||
165 | # query energy items in base period |
||
166 | cursor_energy.execute(" SELECT DISTINCT(energy_item_id) " |
||
167 | " FROM tbl_space_input_item_hourly " |
||
168 | " WHERE space_id = %s " |
||
169 | " AND start_datetime_utc >= %s " |
||
170 | " AND start_datetime_utc < %s ", |
||
171 | (space['id'], base_start_datetime_utc, base_end_datetime_utc)) |
||
172 | rows_energy_items = cursor_energy.fetchall() |
||
173 | if rows_energy_items is not None or len(rows_energy_items) > 0: |
||
174 | for row_item in rows_energy_items: |
||
175 | energy_item_set.add(row_item[0]) |
||
176 | |||
177 | # query energy items in reporting period |
||
178 | cursor_energy.execute(" SELECT DISTINCT(energy_item_id) " |
||
179 | " FROM tbl_space_input_item_hourly " |
||
180 | " WHERE space_id = %s " |
||
181 | " AND start_datetime_utc >= %s " |
||
182 | " AND start_datetime_utc < %s ", |
||
183 | (space['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
||
184 | rows_energy_items = cursor_energy.fetchall() |
||
185 | if rows_energy_items is not None or len(rows_energy_items) > 0: |
||
186 | for row_item in rows_energy_items: |
||
187 | energy_item_set.add(row_item[0]) |
||
188 | |||
189 | # query all energy items in base period and reporting period |
||
190 | cursor_system.execute(" SELECT ei.id, ei.name, ei.energy_category_id, " |
||
191 | " ec.name AS energy_category_name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
||
192 | " FROM tbl_energy_items ei, tbl_energy_categories ec " |
||
193 | " WHERE ei.energy_category_id = ec.id " |
||
194 | " ORDER BY ei.id ", ) |
||
195 | rows_energy_items = cursor_system.fetchall() |
||
196 | if rows_energy_items is None or len(rows_energy_items) == 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_ITEM_NOT_FOUND') |
||
214 | energy_item_dict = dict() |
||
215 | for row_energy_item in rows_energy_items: |
||
216 | if row_energy_item[0] in energy_item_set: |
||
217 | energy_item_dict[row_energy_item[0]] = {"name": row_energy_item[1], |
||
218 | "energy_category_id": row_energy_item[2], |
||
219 | "energy_category_name": row_energy_item[3], |
||
220 | "unit_of_measure": row_energy_item[4], |
||
221 | "kgce": row_energy_item[5], |
||
222 | "kgco2e": row_energy_item[6]} |
||
223 | |||
224 | ################################################################################################################ |
||
225 | # Step 4: query associated sensors |
||
226 | ################################################################################################################ |
||
227 | point_list = list() |
||
228 | cursor_system.execute(" SELECT po.id, po.name, po.units, po.object_type " |
||
229 | " FROM tbl_spaces sp, tbl_sensors se, tbl_spaces_sensors spse, " |
||
230 | " tbl_points po, tbl_sensors_points sepo " |
||
231 | " WHERE sp.id = %s AND sp.id = spse.space_id AND spse.sensor_id = se.id " |
||
232 | " AND se.id = sepo.sensor_id AND sepo.point_id = po.id " |
||
233 | " ORDER BY po.id ", (space['id'], )) |
||
234 | rows_points = cursor_system.fetchall() |
||
235 | if rows_points is not None and len(rows_points) > 0: |
||
236 | for row in rows_points: |
||
237 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
||
238 | |||
239 | ################################################################################################################ |
||
240 | # Step 5: query associated points |
||
241 | ################################################################################################################ |
||
242 | cursor_system.execute(" SELECT po.id, po.name, po.units, po.object_type " |
||
243 | " FROM tbl_spaces sp, tbl_spaces_points sppo, tbl_points po " |
||
244 | " WHERE sp.id = %s AND sp.id = sppo.space_id AND sppo.point_id = po.id " |
||
245 | " ORDER BY po.id ", (space['id'], )) |
||
246 | rows_points = cursor_system.fetchall() |
||
247 | if rows_points is not None and len(rows_points) > 0: |
||
248 | for row in rows_points: |
||
249 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
||
250 | |||
251 | ################################################################################################################ |
||
252 | # Step 6: query child spaces |
||
253 | ################################################################################################################ |
||
254 | child_space_list = list() |
||
255 | cursor_system.execute(" SELECT id, name " |
||
256 | " FROM tbl_spaces " |
||
257 | " WHERE parent_space_id = %s " |
||
258 | " ORDER BY id ", (space['id'], )) |
||
259 | rows_child_spaces = cursor_system.fetchall() |
||
260 | if rows_child_spaces is not None and len(rows_child_spaces) > 0: |
||
261 | for row in rows_child_spaces: |
||
262 | child_space_list.append({"id": row[0], "name": row[1]}) |
||
263 | |||
264 | ################################################################################################################ |
||
265 | # Step 7: query base period energy input |
||
266 | ################################################################################################################ |
||
267 | base = dict() |
||
268 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
269 | for energy_item_id in energy_item_set: |
||
270 | base[energy_item_id] = dict() |
||
271 | base[energy_item_id]['timestamps'] = list() |
||
272 | base[energy_item_id]['values'] = list() |
||
273 | base[energy_item_id]['subtotal'] = Decimal(0.0) |
||
274 | |||
275 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
||
276 | " FROM tbl_space_input_item_hourly " |
||
277 | " WHERE space_id = %s " |
||
278 | " AND energy_item_id = %s " |
||
279 | " AND start_datetime_utc >= %s " |
||
280 | " AND start_datetime_utc < %s " |
||
281 | " ORDER BY start_datetime_utc ", |
||
282 | (space['id'], |
||
283 | energy_item_id, |
||
284 | base_start_datetime_utc, |
||
285 | base_end_datetime_utc)) |
||
286 | rows_space_hourly = cursor_energy.fetchall() |
||
287 | |||
288 | rows_space_periodically = utilities.aggregate_hourly_data_by_period(rows_space_hourly, |
||
289 | base_start_datetime_utc, |
||
290 | base_end_datetime_utc, |
||
291 | period_type) |
||
292 | for row_space_periodically in rows_space_periodically: |
||
293 | current_datetime_local = row_space_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
294 | timedelta(minutes=timezone_offset) |
||
295 | if period_type == 'hourly': |
||
296 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
297 | elif period_type == 'daily': |
||
298 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
||
299 | elif period_type == 'monthly': |
||
300 | current_datetime = current_datetime_local.strftime('%Y-%m') |
||
301 | elif period_type == 'yearly': |
||
302 | current_datetime = current_datetime_local.strftime('%Y') |
||
303 | |||
304 | actual_value = Decimal(0.0) if row_space_periodically[1] is None else row_space_periodically[1] |
||
305 | base[energy_item_id]['timestamps'].append(current_datetime) |
||
|
|||
306 | base[energy_item_id]['values'].append(actual_value) |
||
307 | base[energy_item_id]['subtotal'] += actual_value |
||
308 | |||
309 | ################################################################################################################ |
||
310 | # Step 8: query reporting period energy input |
||
311 | ################################################################################################################ |
||
312 | reporting = dict() |
||
313 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
314 | for energy_item_id in energy_item_set: |
||
315 | reporting[energy_item_id] = dict() |
||
316 | reporting[energy_item_id]['timestamps'] = list() |
||
317 | reporting[energy_item_id]['values'] = list() |
||
318 | reporting[energy_item_id]['subtotal'] = Decimal(0.0) |
||
319 | reporting[energy_item_id]['toppeak'] = Decimal(0.0) |
||
320 | reporting[energy_item_id]['onpeak'] = Decimal(0.0) |
||
321 | reporting[energy_item_id]['midpeak'] = Decimal(0.0) |
||
322 | reporting[energy_item_id]['offpeak'] = Decimal(0.0) |
||
323 | |||
324 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
||
325 | " FROM tbl_space_input_item_hourly " |
||
326 | " WHERE space_id = %s " |
||
327 | " AND energy_item_id = %s " |
||
328 | " AND start_datetime_utc >= %s " |
||
329 | " AND start_datetime_utc < %s " |
||
330 | " ORDER BY start_datetime_utc ", |
||
331 | (space['id'], |
||
332 | energy_item_id, |
||
333 | reporting_start_datetime_utc, |
||
334 | reporting_end_datetime_utc)) |
||
335 | rows_space_hourly = cursor_energy.fetchall() |
||
336 | |||
337 | rows_space_periodically = utilities.aggregate_hourly_data_by_period(rows_space_hourly, |
||
338 | reporting_start_datetime_utc, |
||
339 | reporting_end_datetime_utc, |
||
340 | period_type) |
||
341 | for row_space_periodically in rows_space_periodically: |
||
342 | current_datetime_local = row_space_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
343 | timedelta(minutes=timezone_offset) |
||
344 | if period_type == 'hourly': |
||
345 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
346 | elif period_type == 'daily': |
||
347 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
||
348 | elif period_type == 'monthly': |
||
349 | current_datetime = current_datetime_local.strftime('%Y-%m') |
||
350 | elif period_type == 'yearly': |
||
351 | current_datetime = current_datetime_local.strftime('%Y') |
||
352 | |||
353 | actual_value = Decimal(0.0) if row_space_periodically[1] is None else row_space_periodically[1] |
||
354 | reporting[energy_item_id]['timestamps'].append(current_datetime) |
||
355 | reporting[energy_item_id]['values'].append(actual_value) |
||
356 | reporting[energy_item_id]['subtotal'] += actual_value |
||
357 | |||
358 | energy_category_tariff_dict = \ |
||
359 | utilities.get_energy_category_peak_types(space['cost_center_id'], |
||
360 | energy_item_dict[energy_item_id]['energy_category_id'], |
||
361 | reporting_start_datetime_utc, |
||
362 | reporting_end_datetime_utc) |
||
363 | for row in rows_space_hourly: |
||
364 | peak_type = energy_category_tariff_dict.get(row[0], None) |
||
365 | if peak_type == 'toppeak': |
||
366 | reporting[energy_item_id]['toppeak'] += row[1] |
||
367 | elif peak_type == 'onpeak': |
||
368 | reporting[energy_item_id]['onpeak'] += row[1] |
||
369 | elif peak_type == 'midpeak': |
||
370 | reporting[energy_item_id]['midpeak'] += row[1] |
||
371 | elif peak_type == 'offpeak': |
||
372 | reporting[energy_item_id]['offpeak'] += row[1] |
||
373 | |||
374 | ################################################################################################################ |
||
375 | # Step 9: query tariff data |
||
376 | ################################################################################################################ |
||
377 | parameters_data = dict() |
||
378 | parameters_data['names'] = list() |
||
379 | parameters_data['timestamps'] = list() |
||
380 | parameters_data['values'] = list() |
||
381 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
382 | for energy_item_id in energy_item_set: |
||
383 | energy_category_tariff_dict = \ |
||
384 | utilities.get_energy_category_tariffs(space['cost_center_id'], |
||
385 | energy_item_dict[energy_item_id]['energy_category_id'], |
||
386 | reporting_start_datetime_utc, |
||
387 | reporting_end_datetime_utc) |
||
388 | tariff_timestamp_list = list() |
||
389 | tariff_value_list = list() |
||
390 | for k, v in energy_category_tariff_dict.items(): |
||
391 | # convert k from utc to local |
||
392 | k = k + timedelta(minutes=timezone_offset) |
||
393 | tariff_timestamp_list.append(k.isoformat()[0:19][0:19]) |
||
394 | tariff_value_list.append(v) |
||
395 | |||
396 | parameters_data['names'].append('TARIFF-' + energy_item_dict[energy_item_id]['name']) |
||
397 | parameters_data['timestamps'].append(tariff_timestamp_list) |
||
398 | parameters_data['values'].append(tariff_value_list) |
||
399 | |||
400 | ################################################################################################################ |
||
401 | # Step 10: query associated sensors and points data |
||
402 | ################################################################################################################ |
||
403 | for point in point_list: |
||
404 | point_values = [] |
||
405 | point_timestamps = [] |
||
406 | if point['object_type'] == 'ANALOG_VALUE': |
||
407 | query = (" SELECT utc_date_time, actual_value " |
||
408 | " FROM tbl_analog_value " |
||
409 | " WHERE point_id = %s " |
||
410 | " AND utc_date_time BETWEEN %s AND %s " |
||
411 | " ORDER BY utc_date_time ") |
||
412 | cursor_historical.execute(query, (point['id'], |
||
413 | reporting_start_datetime_utc, |
||
414 | reporting_end_datetime_utc)) |
||
415 | rows = cursor_historical.fetchall() |
||
416 | |||
417 | if rows is not None and len(rows) > 0: |
||
418 | for row in rows: |
||
419 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
420 | timedelta(minutes=timezone_offset) |
||
421 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
422 | point_timestamps.append(current_datetime) |
||
423 | point_values.append(row[1]) |
||
424 | |||
425 | elif point['object_type'] == 'ENERGY_VALUE': |
||
426 | query = (" SELECT utc_date_time, actual_value " |
||
427 | " FROM tbl_energy_value " |
||
428 | " WHERE point_id = %s " |
||
429 | " AND utc_date_time BETWEEN %s AND %s " |
||
430 | " ORDER BY utc_date_time ") |
||
431 | cursor_historical.execute(query, (point['id'], |
||
432 | reporting_start_datetime_utc, |
||
433 | reporting_end_datetime_utc)) |
||
434 | rows = cursor_historical.fetchall() |
||
435 | |||
436 | if rows is not None and len(rows) > 0: |
||
437 | for row in rows: |
||
438 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
439 | timedelta(minutes=timezone_offset) |
||
440 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
441 | point_timestamps.append(current_datetime) |
||
442 | point_values.append(row[1]) |
||
443 | elif point['object_type'] == 'DIGITAL_VALUE': |
||
444 | query = (" SELECT utc_date_time, actual_value " |
||
445 | " FROM tbl_digital_value " |
||
446 | " WHERE point_id = %s " |
||
447 | " AND utc_date_time BETWEEN %s AND %s ") |
||
448 | cursor_historical.execute(query, (point['id'], |
||
449 | reporting_start_datetime_utc, |
||
450 | reporting_end_datetime_utc)) |
||
451 | rows = cursor_historical.fetchall() |
||
452 | |||
453 | if rows is not None and len(rows) > 0: |
||
454 | for row in rows: |
||
455 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
456 | timedelta(minutes=timezone_offset) |
||
457 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
||
458 | point_timestamps.append(current_datetime) |
||
459 | point_values.append(row[1]) |
||
460 | |||
461 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
||
462 | parameters_data['timestamps'].append(point_timestamps) |
||
463 | parameters_data['values'].append(point_values) |
||
464 | |||
465 | ################################################################################################################ |
||
466 | # Step 11: query child spaces energy input |
||
467 | ################################################################################################################ |
||
468 | child_space_data = dict() |
||
469 | |||
470 | View Code Duplication | if energy_item_set is not None and len(energy_item_set) > 0: |
|
471 | for energy_item_id in energy_item_set: |
||
472 | child_space_data[energy_item_id] = dict() |
||
473 | child_space_data[energy_item_id]['child_space_names'] = list() |
||
474 | child_space_data[energy_item_id]['subtotals'] = list() |
||
475 | |||
476 | for child_space in child_space_list: |
||
477 | child_space_data[energy_item_id]['child_space_names'].append(child_space['name']) |
||
478 | |||
479 | cursor_energy.execute(" SELECT SUM(actual_value) " |
||
480 | " FROM tbl_space_input_item_hourly " |
||
481 | " WHERE space_id = %s " |
||
482 | " AND energy_item_id = %s " |
||
483 | " AND start_datetime_utc >= %s " |
||
484 | " AND start_datetime_utc < %s " |
||
485 | " ORDER BY start_datetime_utc ", |
||
486 | (child_space['id'], |
||
487 | energy_item_id, |
||
488 | reporting_start_datetime_utc, |
||
489 | reporting_end_datetime_utc)) |
||
490 | row_subtotal = cursor_energy.fetchone() |
||
491 | |||
492 | subtotal = Decimal(0.0) if (row_subtotal is None or row_subtotal[0] is None) else row_subtotal[0] |
||
493 | child_space_data[energy_item_id]['subtotals'].append(subtotal) |
||
494 | |||
495 | ################################################################################################################ |
||
496 | # Step 12: construct the report |
||
497 | ################################################################################################################ |
||
498 | if cursor_system: |
||
499 | cursor_system.close() |
||
500 | if cnx_system: |
||
501 | cnx_system.disconnect() |
||
502 | |||
503 | if cursor_energy: |
||
504 | cursor_energy.close() |
||
505 | if cnx_energy: |
||
506 | cnx_energy.disconnect() |
||
507 | |||
508 | result = dict() |
||
509 | |||
510 | result['space'] = dict() |
||
511 | result['space']['name'] = space['name'] |
||
512 | result['space']['area'] = space['area'] |
||
513 | |||
514 | result['base_period'] = dict() |
||
515 | result['base_period']['names'] = list() |
||
516 | result['base_period']['units'] = list() |
||
517 | result['base_period']['timestamps'] = list() |
||
518 | result['base_period']['values'] = list() |
||
519 | result['base_period']['subtotals'] = list() |
||
520 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
521 | for energy_item_id in energy_item_set: |
||
522 | result['base_period']['names'].append(energy_item_dict[energy_item_id]['name']) |
||
523 | result['base_period']['units'].append(energy_item_dict[energy_item_id]['unit_of_measure']) |
||
524 | result['base_period']['timestamps'].append(base[energy_item_id]['timestamps']) |
||
525 | result['base_period']['values'].append(base[energy_item_id]['values']) |
||
526 | result['base_period']['subtotals'].append(base[energy_item_id]['subtotal']) |
||
527 | |||
528 | result['reporting_period'] = dict() |
||
529 | result['reporting_period']['names'] = list() |
||
530 | result['reporting_period']['energy_item_ids'] = list() |
||
531 | result['reporting_period']['energy_category_names'] = list() |
||
532 | result['reporting_period']['energy_category_ids'] = list() |
||
533 | result['reporting_period']['units'] = list() |
||
534 | result['reporting_period']['timestamps'] = list() |
||
535 | result['reporting_period']['values'] = list() |
||
536 | result['reporting_period']['subtotals'] = list() |
||
537 | result['reporting_period']['subtotals_per_unit_area'] = list() |
||
538 | result['reporting_period']['toppeaks'] = list() |
||
539 | result['reporting_period']['onpeaks'] = list() |
||
540 | result['reporting_period']['midpeaks'] = list() |
||
541 | result['reporting_period']['offpeaks'] = list() |
||
542 | result['reporting_period']['increment_rates'] = list() |
||
543 | |||
544 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
545 | for energy_item_id in energy_item_set: |
||
546 | result['reporting_period']['names'].append(energy_item_dict[energy_item_id]['name']) |
||
547 | result['reporting_period']['energy_item_ids'].append(energy_item_id) |
||
548 | result['reporting_period']['energy_category_names'].append( |
||
549 | energy_item_dict[energy_item_id]['energy_category_name']) |
||
550 | result['reporting_period']['energy_category_ids'].append( |
||
551 | energy_item_dict[energy_item_id]['energy_category_id']) |
||
552 | result['reporting_period']['units'].append(energy_item_dict[energy_item_id]['unit_of_measure']) |
||
553 | result['reporting_period']['timestamps'].append(reporting[energy_item_id]['timestamps']) |
||
554 | result['reporting_period']['values'].append(reporting[energy_item_id]['values']) |
||
555 | result['reporting_period']['subtotals'].append(reporting[energy_item_id]['subtotal']) |
||
556 | result['reporting_period']['subtotals_per_unit_area'].append( |
||
557 | reporting[energy_item_id]['subtotal'] / space['area'] if space['area'] > 0.0 else None) |
||
558 | result['reporting_period']['toppeaks'].append(reporting[energy_item_id]['toppeak']) |
||
559 | result['reporting_period']['onpeaks'].append(reporting[energy_item_id]['onpeak']) |
||
560 | result['reporting_period']['midpeaks'].append(reporting[energy_item_id]['midpeak']) |
||
561 | result['reporting_period']['offpeaks'].append(reporting[energy_item_id]['offpeak']) |
||
562 | result['reporting_period']['increment_rates'].append( |
||
563 | (reporting[energy_item_id]['subtotal'] - base[energy_item_id]['subtotal']) / |
||
564 | base[energy_item_id]['subtotal'] |
||
565 | if base[energy_item_id]['subtotal'] > 0.0 else None) |
||
566 | |||
567 | result['parameters'] = { |
||
568 | "names": parameters_data['names'], |
||
569 | "timestamps": parameters_data['timestamps'], |
||
570 | "values": parameters_data['values'] |
||
571 | } |
||
572 | |||
573 | result['child_space'] = dict() |
||
574 | result['child_space']['energy_item_names'] = list() # 1D array [energy item] |
||
575 | result['child_space']['units'] = list() # 1D array [energy item] |
||
576 | result['child_space']['child_space_names_array'] = list() # 2D array [energy item][child space] |
||
577 | result['child_space']['subtotals_array'] = list() # 2D array [energy item][child space] |
||
578 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
579 | for energy_item_id in energy_item_set: |
||
580 | result['child_space']['energy_item_names'].append(energy_item_dict[energy_item_id]['name']) |
||
581 | result['child_space']['units'].append(energy_item_dict[energy_item_id]['unit_of_measure']) |
||
582 | result['child_space']['child_space_names_array'].append( |
||
583 | child_space_data[energy_item_id]['child_space_names']) |
||
584 | result['child_space']['subtotals_array'].append( |
||
585 | child_space_data[energy_item_id]['subtotals']) |
||
586 | |||
587 | resp.body = json.dumps(result) |
||
588 |