1 | import re |
||
2 | from datetime import datetime, timedelta, timezone |
||
3 | from decimal import Decimal |
||
4 | import falcon |
||
5 | import mysql.connector |
||
6 | import simplejson as json |
||
7 | import config |
||
8 | import excelexporters.equipmentenergyitem |
||
9 | from core import utilities |
||
10 | from core.useractivity import access_control, api_key_control |
||
11 | |||
12 | |||
13 | class Reporting: |
||
14 | def __init__(self): |
||
15 | """"Initializes Reporting""" |
||
16 | pass |
||
17 | |||
18 | @staticmethod |
||
19 | def on_options(req, resp): |
||
20 | _ = req |
||
21 | resp.status = falcon.HTTP_200 |
||
22 | |||
23 | #################################################################################################################### |
||
24 | # PROCEDURES |
||
25 | # Step 1: valid parameters |
||
26 | # Step 2: query the equipment |
||
27 | # Step 3: query energy items |
||
28 | # Step 4: query associated points |
||
29 | # Step 5: query base period energy input |
||
30 | # Step 6: query reporting period energy input |
||
31 | # Step 7: query tariff data |
||
32 | # Step 8: query associated points data |
||
33 | # Step 9: construct the report |
||
34 | #################################################################################################################### |
||
35 | @staticmethod |
||
36 | def on_get(req, resp): |
||
37 | if 'API-KEY' not in req.headers or \ |
||
38 | not isinstance(req.headers['API-KEY'], str) or \ |
||
39 | len(str.strip(req.headers['API-KEY'])) == 0: |
||
40 | access_control(req) |
||
41 | else: |
||
42 | api_key_control(req) |
||
43 | print(req.params) |
||
44 | equipment_id = req.params.get('equipmentid') |
||
45 | equipment_uuid = req.params.get('equipmentuuid') |
||
46 | period_type = req.params.get('periodtype') |
||
47 | base_period_start_datetime_local = req.params.get('baseperiodstartdatetime') |
||
48 | base_period_end_datetime_local = req.params.get('baseperiodenddatetime') |
||
49 | reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
||
50 | reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime') |
||
51 | language = req.params.get('language') |
||
52 | quick_mode = req.params.get('quickmode') |
||
53 | |||
54 | ################################################################################################################ |
||
55 | # Step 1: valid parameters |
||
56 | ################################################################################################################ |
||
57 | if equipment_id is None and equipment_uuid is None: |
||
58 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
59 | title='API.BAD_REQUEST', |
||
60 | description='API.INVALID_EQUIPMENT_ID') |
||
61 | |||
62 | if equipment_id is not None: |
||
63 | equipment_id = str.strip(equipment_id) |
||
64 | if not equipment_id.isdigit() or int(equipment_id) <= 0: |
||
65 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
66 | title='API.BAD_REQUEST', |
||
67 | description='API.INVALID_EQUIPMENT_ID') |
||
68 | |||
69 | if equipment_uuid is not None: |
||
70 | regex = re.compile(r'^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I) |
||
71 | match = regex.match(str.strip(equipment_uuid)) |
||
72 | if not bool(match): |
||
73 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
74 | title='API.BAD_REQUEST', |
||
75 | description='API.INVALID_EQUIPMENT_UUID') |
||
76 | |||
77 | if period_type is None: |
||
78 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
79 | description='API.INVALID_PERIOD_TYPE') |
||
80 | else: |
||
81 | period_type = str.strip(period_type) |
||
82 | if period_type not in ['hourly', 'daily', 'weekly', 'monthly', 'yearly']: |
||
83 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
84 | description='API.INVALID_PERIOD_TYPE') |
||
85 | |||
86 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
87 | if config.utc_offset[0] == '-': |
||
88 | timezone_offset = -timezone_offset |
||
89 | |||
90 | base_start_datetime_utc = None |
||
91 | if base_period_start_datetime_local is not None and len(str.strip(base_period_start_datetime_local)) > 0: |
||
92 | base_period_start_datetime_local = str.strip(base_period_start_datetime_local) |
||
93 | try: |
||
94 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S') |
||
95 | except ValueError: |
||
96 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
97 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
||
98 | base_start_datetime_utc = \ |
||
99 | base_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
||
100 | # nomalize the start datetime |
||
101 | if config.minutes_to_count == 30 and base_start_datetime_utc.minute >= 30: |
||
102 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
||
103 | else: |
||
104 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
||
105 | |||
106 | base_end_datetime_utc = None |
||
107 | if base_period_end_datetime_local is not None and len(str.strip(base_period_end_datetime_local)) > 0: |
||
108 | base_period_end_datetime_local = str.strip(base_period_end_datetime_local) |
||
109 | try: |
||
110 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S') |
||
111 | except ValueError: |
||
112 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
113 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
||
114 | base_end_datetime_utc = \ |
||
115 | base_end_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
||
116 | |||
117 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
||
118 | base_start_datetime_utc >= base_end_datetime_utc: |
||
119 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
120 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
||
121 | |||
122 | if reporting_period_start_datetime_local is None: |
||
123 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
124 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
||
125 | else: |
||
126 | reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) |
||
127 | try: |
||
128 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, |
||
129 | '%Y-%m-%dT%H:%M:%S') |
||
130 | except ValueError: |
||
131 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
132 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
||
133 | reporting_start_datetime_utc = \ |
||
134 | reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
||
135 | # nomalize the start datetime |
||
136 | if config.minutes_to_count == 30 and reporting_start_datetime_utc.minute >= 30: |
||
137 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
||
138 | else: |
||
139 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
||
140 | |||
141 | if reporting_period_end_datetime_local is None: |
||
142 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
143 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
||
144 | else: |
||
145 | reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) |
||
146 | try: |
||
147 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, |
||
148 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
149 | timedelta(minutes=timezone_offset) |
||
150 | except ValueError: |
||
151 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
152 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
||
153 | |||
154 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
||
155 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
156 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
||
157 | |||
158 | # if turn quick mode on, do not return parameters data and excel file |
||
159 | is_quick_mode = False |
||
160 | if quick_mode is not None and \ |
||
161 | len(str.strip(quick_mode)) > 0 and \ |
||
162 | str.lower(str.strip(quick_mode)) in ('true', 't', 'on', 'yes', 'y'): |
||
163 | is_quick_mode = True |
||
164 | |||
165 | trans = utilities.get_translation(language) |
||
166 | trans.install() |
||
167 | _ = trans.gettext |
||
168 | |||
169 | ################################################################################################################ |
||
170 | # Step 2: query the equipment |
||
171 | ################################################################################################################ |
||
172 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
||
173 | cursor_system = cnx_system.cursor() |
||
174 | |||
175 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
||
176 | cursor_energy = cnx_energy.cursor() |
||
177 | |||
178 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
||
179 | cursor_historical = cnx_historical.cursor() |
||
180 | |||
181 | if equipment_id is not None: |
||
182 | cursor_system.execute(" SELECT id, name, cost_center_id " |
||
183 | " FROM tbl_equipments " |
||
184 | " WHERE id = %s ", (equipment_id,)) |
||
185 | row_equipment = cursor_system.fetchone() |
||
186 | elif equipment_uuid is not None: |
||
187 | cursor_system.execute(" SELECT id, name, cost_center_id " |
||
188 | " FROM tbl_equipments " |
||
189 | " WHERE uuid = %s ", (equipment_uuid,)) |
||
190 | row_equipment = cursor_system.fetchone() |
||
191 | |||
192 | View Code Duplication | if row_equipment is None: |
|
0 ignored issues
–
show
introduced
by
![]() |
|||
193 | if cursor_system: |
||
194 | cursor_system.close() |
||
195 | if cnx_system: |
||
196 | cnx_system.close() |
||
197 | |||
198 | if cursor_energy: |
||
199 | cursor_energy.close() |
||
200 | if cnx_energy: |
||
201 | cnx_energy.close() |
||
202 | |||
203 | if cursor_historical: |
||
204 | cursor_historical.close() |
||
205 | if cnx_historical: |
||
206 | cnx_historical.close() |
||
207 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', description='API.EQUIPMENT_NOT_FOUND') |
||
208 | |||
209 | equipment = dict() |
||
210 | equipment['id'] = row_equipment[0] |
||
211 | equipment['name'] = row_equipment[1] |
||
212 | equipment['cost_center_id'] = row_equipment[2] |
||
213 | |||
214 | ################################################################################################################ |
||
215 | # Step 3: query energy items |
||
216 | ################################################################################################################ |
||
217 | energy_item_set = set() |
||
218 | # query energy items in base period |
||
219 | cursor_energy.execute(" SELECT DISTINCT(energy_item_id) " |
||
220 | " FROM tbl_equipment_input_item_hourly " |
||
221 | " WHERE equipment_id = %s " |
||
222 | " AND start_datetime_utc >= %s " |
||
223 | " AND start_datetime_utc < %s ", |
||
224 | (equipment['id'], base_start_datetime_utc, base_end_datetime_utc)) |
||
225 | rows_energy_items = cursor_energy.fetchall() |
||
226 | if rows_energy_items is not None and len(rows_energy_items) > 0: |
||
227 | for row_item in rows_energy_items: |
||
228 | energy_item_set.add(row_item[0]) |
||
229 | |||
230 | # query energy items in reporting period |
||
231 | cursor_energy.execute(" SELECT DISTINCT(energy_item_id) " |
||
232 | " FROM tbl_equipment_input_item_hourly " |
||
233 | " WHERE equipment_id = %s " |
||
234 | " AND start_datetime_utc >= %s " |
||
235 | " AND start_datetime_utc < %s ", |
||
236 | (equipment['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
||
237 | rows_energy_items = cursor_energy.fetchall() |
||
238 | if rows_energy_items is not None and len(rows_energy_items) > 0: |
||
239 | for row_item in rows_energy_items: |
||
240 | energy_item_set.add(row_item[0]) |
||
241 | |||
242 | # query all energy items in base period and reporting period |
||
243 | cursor_system.execute(" SELECT ei.id, ei.name, ei.energy_category_id, " |
||
244 | " ec.name AS energy_category_name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
||
245 | " FROM tbl_energy_items ei, tbl_energy_categories ec " |
||
246 | " WHERE ei.energy_category_id = ec.id " |
||
247 | " ORDER BY ei.id ", ) |
||
248 | rows_energy_items = cursor_system.fetchall() |
||
249 | if rows_energy_items is None or len(rows_energy_items) == 0: |
||
250 | if cursor_system: |
||
251 | cursor_system.close() |
||
252 | if cnx_system: |
||
253 | cnx_system.close() |
||
254 | |||
255 | if cursor_energy: |
||
256 | cursor_energy.close() |
||
257 | if cnx_energy: |
||
258 | cnx_energy.close() |
||
259 | |||
260 | if cursor_historical: |
||
261 | cursor_historical.close() |
||
262 | if cnx_historical: |
||
263 | cnx_historical.close() |
||
264 | raise falcon.HTTPError(status=falcon.HTTP_404, |
||
265 | title='API.NOT_FOUND', |
||
266 | description='API.ENERGY_ITEM_NOT_FOUND') |
||
267 | energy_item_dict = dict() |
||
268 | for row_energy_item in rows_energy_items: |
||
269 | if row_energy_item[0] in energy_item_set: |
||
270 | energy_item_dict[row_energy_item[0]] = {"name": row_energy_item[1], |
||
271 | "energy_category_id": row_energy_item[2], |
||
272 | "energy_category_name": row_energy_item[3], |
||
273 | "unit_of_measure": row_energy_item[4], |
||
274 | "kgce": row_energy_item[5], |
||
275 | "kgco2e": row_energy_item[6]} |
||
276 | |||
277 | ################################################################################################################ |
||
278 | # Step 4: query associated points |
||
279 | ################################################################################################################ |
||
280 | point_list = list() |
||
281 | cursor_system.execute(" SELECT p.id, ep.name, p.units, p.object_type " |
||
282 | " FROM tbl_equipments e, tbl_equipments_parameters ep, tbl_points p " |
||
283 | " WHERE e.id = %s AND e.id = ep.equipment_id AND ep.parameter_type = 'point' " |
||
284 | " AND ep.point_id = p.id " |
||
285 | " ORDER BY p.id ", (equipment['id'],)) |
||
286 | rows_points = cursor_system.fetchall() |
||
287 | if rows_points is not None and len(rows_points) > 0: |
||
288 | for row in rows_points: |
||
289 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
||
290 | |||
291 | ################################################################################################################ |
||
292 | # Step 5: query base period energy input |
||
293 | ################################################################################################################ |
||
294 | base = dict() |
||
295 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
296 | for energy_item_id in energy_item_set: |
||
297 | base[energy_item_id] = dict() |
||
298 | base[energy_item_id]['timestamps'] = list() |
||
299 | base[energy_item_id]['values'] = list() |
||
300 | base[energy_item_id]['subtotal'] = Decimal(0.0) |
||
301 | |||
302 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
||
303 | " FROM tbl_equipment_input_item_hourly " |
||
304 | " WHERE equipment_id = %s " |
||
305 | " AND energy_item_id = %s " |
||
306 | " AND start_datetime_utc >= %s " |
||
307 | " AND start_datetime_utc < %s " |
||
308 | " ORDER BY start_datetime_utc ", |
||
309 | (equipment['id'], |
||
310 | energy_item_id, |
||
311 | base_start_datetime_utc, |
||
312 | base_end_datetime_utc)) |
||
313 | rows_equipment_hourly = cursor_energy.fetchall() |
||
314 | |||
315 | rows_equipment_periodically = utilities.aggregate_hourly_data_by_period(rows_equipment_hourly, |
||
316 | base_start_datetime_utc, |
||
317 | base_end_datetime_utc, |
||
318 | period_type) |
||
319 | for row_equipment_periodically in rows_equipment_periodically: |
||
320 | current_datetime_local = row_equipment_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
321 | timedelta(minutes=timezone_offset) |
||
322 | if period_type == 'hourly': |
||
323 | current_datetime = current_datetime_local.isoformat()[0:19] |
||
324 | elif period_type == 'daily': |
||
325 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
326 | elif period_type == 'weekly': |
||
327 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
328 | elif period_type == 'monthly': |
||
329 | current_datetime = current_datetime_local.isoformat()[0:7] |
||
330 | elif period_type == 'yearly': |
||
331 | current_datetime = current_datetime_local.isoformat()[0:4] |
||
332 | |||
333 | actual_value = Decimal(0.0) if row_equipment_periodically[1] is None \ |
||
334 | else row_equipment_periodically[1] |
||
335 | base[energy_item_id]['timestamps'].append(current_datetime) |
||
0 ignored issues
–
show
|
|||
336 | base[energy_item_id]['values'].append(actual_value) |
||
337 | base[energy_item_id]['subtotal'] += actual_value |
||
338 | |||
339 | ################################################################################################################ |
||
340 | # Step 6: query reporting period energy input |
||
341 | ################################################################################################################ |
||
342 | reporting = dict() |
||
343 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
344 | for energy_item_id in energy_item_set: |
||
345 | reporting[energy_item_id] = dict() |
||
346 | reporting[energy_item_id]['timestamps'] = list() |
||
347 | reporting[energy_item_id]['values'] = list() |
||
348 | reporting[energy_item_id]['subtotal'] = Decimal(0.0) |
||
349 | reporting[energy_item_id]['toppeak'] = Decimal(0.0) |
||
350 | reporting[energy_item_id]['onpeak'] = Decimal(0.0) |
||
351 | reporting[energy_item_id]['midpeak'] = Decimal(0.0) |
||
352 | reporting[energy_item_id]['offpeak'] = Decimal(0.0) |
||
353 | reporting[energy_item_id]['deep'] = Decimal(0.0) |
||
354 | |||
355 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
||
356 | " FROM tbl_equipment_input_item_hourly " |
||
357 | " WHERE equipment_id = %s " |
||
358 | " AND energy_item_id = %s " |
||
359 | " AND start_datetime_utc >= %s " |
||
360 | " AND start_datetime_utc < %s " |
||
361 | " ORDER BY start_datetime_utc ", |
||
362 | (equipment['id'], |
||
363 | energy_item_id, |
||
364 | reporting_start_datetime_utc, |
||
365 | reporting_end_datetime_utc)) |
||
366 | rows_equipment_hourly = cursor_energy.fetchall() |
||
367 | |||
368 | rows_equipment_periodically = utilities.aggregate_hourly_data_by_period(rows_equipment_hourly, |
||
369 | reporting_start_datetime_utc, |
||
370 | reporting_end_datetime_utc, |
||
371 | period_type) |
||
372 | for row_equipment_periodically in rows_equipment_periodically: |
||
373 | current_datetime_local = row_equipment_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
374 | timedelta(minutes=timezone_offset) |
||
375 | if period_type == 'hourly': |
||
376 | current_datetime = current_datetime_local.isoformat()[0:19] |
||
377 | elif period_type == 'daily': |
||
378 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
379 | elif period_type == 'weekly': |
||
380 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
381 | elif period_type == 'monthly': |
||
382 | current_datetime = current_datetime_local.isoformat()[0:7] |
||
383 | elif period_type == 'yearly': |
||
384 | current_datetime = current_datetime_local.isoformat()[0:4] |
||
385 | |||
386 | actual_value = Decimal(0.0) if row_equipment_periodically[1] is None \ |
||
387 | else row_equipment_periodically[1] |
||
388 | reporting[energy_item_id]['timestamps'].append(current_datetime) |
||
389 | reporting[energy_item_id]['values'].append(actual_value) |
||
390 | reporting[energy_item_id]['subtotal'] += actual_value |
||
391 | |||
392 | energy_category_tariff_dict = \ |
||
393 | utilities.get_energy_category_peak_types(equipment['cost_center_id'], |
||
394 | energy_item_dict[energy_item_id]['energy_category_id'], |
||
395 | reporting_start_datetime_utc, |
||
396 | reporting_end_datetime_utc) |
||
397 | for row in rows_equipment_hourly: |
||
398 | peak_type = energy_category_tariff_dict.get(row[0], None) |
||
399 | if peak_type == 'toppeak': |
||
400 | reporting[energy_item_id]['toppeak'] += row[1] |
||
401 | elif peak_type == 'onpeak': |
||
402 | reporting[energy_item_id]['onpeak'] += row[1] |
||
403 | elif peak_type == 'midpeak': |
||
404 | reporting[energy_item_id]['midpeak'] += row[1] |
||
405 | elif peak_type == 'offpeak': |
||
406 | reporting[energy_item_id]['offpeak'] += row[1] |
||
407 | elif peak_type == 'deep': |
||
408 | reporting[energy_item_id]['deep'] += row[1] |
||
409 | |||
410 | ################################################################################################################ |
||
411 | # Step 7: query tariff data |
||
412 | ################################################################################################################ |
||
413 | parameters_data = dict() |
||
414 | parameters_data['names'] = list() |
||
415 | parameters_data['timestamps'] = list() |
||
416 | parameters_data['values'] = list() |
||
417 | if not is_quick_mode: |
||
418 | if config.is_tariff_appended and energy_item_set is not None and len(energy_item_set) > 0: |
||
419 | for energy_item_id in energy_item_set: |
||
420 | energy_category_tariff_dict = \ |
||
421 | utilities.get_energy_category_tariffs(equipment['cost_center_id'], |
||
422 | energy_item_dict[energy_item_id]['energy_category_id'], |
||
423 | reporting_start_datetime_utc, |
||
424 | reporting_end_datetime_utc) |
||
425 | tariff_timestamp_list = list() |
||
426 | tariff_value_list = list() |
||
427 | for k, v in energy_category_tariff_dict.items(): |
||
428 | # convert k from utc to local |
||
429 | k = k + timedelta(minutes=timezone_offset) |
||
430 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
||
431 | tariff_value_list.append(v) |
||
432 | |||
433 | parameters_data['names'].append(_('Tariff') + '-' + energy_item_dict[energy_item_id]['name']) |
||
434 | parameters_data['timestamps'].append(tariff_timestamp_list) |
||
435 | parameters_data['values'].append(tariff_value_list) |
||
436 | |||
437 | ################################################################################################################ |
||
438 | # Step 8: query associated points data |
||
439 | ################################################################################################################ |
||
440 | if not is_quick_mode: |
||
441 | for point in point_list: |
||
442 | point_values = [] |
||
443 | point_timestamps = [] |
||
444 | if point['object_type'] == 'ENERGY_VALUE': |
||
445 | query = (" SELECT utc_date_time, actual_value " |
||
446 | " FROM tbl_energy_value " |
||
447 | " WHERE point_id = %s " |
||
448 | " AND utc_date_time BETWEEN %s AND %s " |
||
449 | " ORDER BY utc_date_time ") |
||
450 | cursor_historical.execute(query, (point['id'], |
||
451 | reporting_start_datetime_utc, |
||
452 | reporting_end_datetime_utc)) |
||
453 | rows = cursor_historical.fetchall() |
||
454 | |||
455 | if rows is not None and len(rows) > 0: |
||
456 | for row in rows: |
||
457 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
458 | timedelta(minutes=timezone_offset) |
||
459 | current_datetime = current_datetime_local.isoformat()[0:19] |
||
460 | point_timestamps.append(current_datetime) |
||
461 | point_values.append(row[1]) |
||
462 | elif point['object_type'] == 'ANALOG_VALUE': |
||
463 | query = (" SELECT utc_date_time, actual_value " |
||
464 | " FROM tbl_analog_value " |
||
465 | " WHERE point_id = %s " |
||
466 | " AND utc_date_time BETWEEN %s AND %s " |
||
467 | " ORDER BY utc_date_time ") |
||
468 | cursor_historical.execute(query, (point['id'], |
||
469 | reporting_start_datetime_utc, |
||
470 | reporting_end_datetime_utc)) |
||
471 | rows = cursor_historical.fetchall() |
||
472 | |||
473 | if rows is not None and len(rows) > 0: |
||
474 | for row in rows: |
||
475 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
476 | timedelta(minutes=timezone_offset) |
||
477 | current_datetime = current_datetime_local.isoformat()[0:19] |
||
478 | point_timestamps.append(current_datetime) |
||
479 | point_values.append(row[1]) |
||
480 | elif point['object_type'] == 'DIGITAL_VALUE': |
||
481 | query = (" SELECT utc_date_time, actual_value " |
||
482 | " FROM tbl_digital_value " |
||
483 | " WHERE point_id = %s " |
||
484 | " AND utc_date_time BETWEEN %s AND %s " |
||
485 | " ORDER BY utc_date_time ") |
||
486 | cursor_historical.execute(query, (point['id'], |
||
487 | reporting_start_datetime_utc, |
||
488 | reporting_end_datetime_utc)) |
||
489 | rows = cursor_historical.fetchall() |
||
490 | |||
491 | if rows is not None and len(rows) > 0: |
||
492 | for row in rows: |
||
493 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
494 | timedelta(minutes=timezone_offset) |
||
495 | current_datetime = current_datetime_local.isoformat()[0:19] |
||
496 | point_timestamps.append(current_datetime) |
||
497 | point_values.append(row[1]) |
||
498 | |||
499 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
||
500 | parameters_data['timestamps'].append(point_timestamps) |
||
501 | parameters_data['values'].append(point_values) |
||
502 | |||
503 | ################################################################################################################ |
||
504 | # Step 9: construct the report |
||
505 | ################################################################################################################ |
||
506 | if cursor_system: |
||
507 | cursor_system.close() |
||
508 | if cnx_system: |
||
509 | cnx_system.close() |
||
510 | |||
511 | if cursor_energy: |
||
512 | cursor_energy.close() |
||
513 | if cnx_energy: |
||
514 | cnx_energy.close() |
||
515 | |||
516 | if cursor_historical: |
||
517 | cursor_historical.close() |
||
518 | if cnx_historical: |
||
519 | cnx_historical.close() |
||
520 | |||
521 | result = dict() |
||
522 | |||
523 | result['equipment'] = dict() |
||
524 | result['equipment']['name'] = equipment['name'] |
||
525 | |||
526 | result['base_period'] = dict() |
||
527 | result['base_period']['names'] = list() |
||
528 | result['base_period']['units'] = list() |
||
529 | result['base_period']['timestamps'] = list() |
||
530 | result['base_period']['values'] = list() |
||
531 | result['base_period']['subtotals'] = list() |
||
532 | if energy_item_set is not None and len(energy_item_set) > 0: |
||
533 | for energy_item_id in energy_item_set: |
||
534 | result['base_period']['names'].append(energy_item_dict[energy_item_id]['name']) |
||
535 | result['base_period']['units'].append(energy_item_dict[energy_item_id]['unit_of_measure']) |
||
536 | result['base_period']['timestamps'].append(base[energy_item_id]['timestamps']) |
||
537 | result['base_period']['values'].append(base[energy_item_id]['values']) |
||
538 | result['base_period']['subtotals'].append(base[energy_item_id]['subtotal']) |
||
539 | |||
540 | result['reporting_period'] = dict() |
||
541 | result['reporting_period']['names'] = list() |
||
542 | result['reporting_period']['energy_item_ids'] = list() |
||
543 | result['reporting_period']['energy_category_names'] = list() |
||
544 | result['reporting_period']['energy_category_ids'] = list() |
||
545 | result['reporting_period']['units'] = list() |
||
546 | result['reporting_period']['timestamps'] = list() |
||
547 | result['reporting_period']['values'] = list() |
||
548 | result['reporting_period']['rates'] = list() |
||
549 | result['reporting_period']['subtotals'] = list() |
||
550 | result['reporting_period']['toppeaks'] = list() |
||
551 | result['reporting_period']['onpeaks'] = list() |
||
552 | result['reporting_period']['midpeaks'] = list() |
||
553 | result['reporting_period']['offpeaks'] = list() |
||
554 | result['reporting_period']['deeps'] = list() |
||
555 | result['reporting_period']['increment_rates'] = list() |
||
556 | |||
557 | View Code Duplication | if energy_item_set is not None and len(energy_item_set) > 0: |
|
0 ignored issues
–
show
|
|||
558 | for energy_item_id in energy_item_set: |
||
559 | result['reporting_period']['names'].append(energy_item_dict[energy_item_id]['name']) |
||
560 | result['reporting_period']['energy_item_ids'].append(energy_item_id) |
||
561 | result['reporting_period']['energy_category_names'].append( |
||
562 | energy_item_dict[energy_item_id]['energy_category_name']) |
||
563 | result['reporting_period']['energy_category_ids'].append( |
||
564 | energy_item_dict[energy_item_id]['energy_category_id']) |
||
565 | result['reporting_period']['units'].append(energy_item_dict[energy_item_id]['unit_of_measure']) |
||
566 | result['reporting_period']['timestamps'].append(reporting[energy_item_id]['timestamps']) |
||
567 | result['reporting_period']['values'].append(reporting[energy_item_id]['values']) |
||
568 | result['reporting_period']['subtotals'].append(reporting[energy_item_id]['subtotal']) |
||
569 | result['reporting_period']['toppeaks'].append(reporting[energy_item_id]['toppeak']) |
||
570 | result['reporting_period']['onpeaks'].append(reporting[energy_item_id]['onpeak']) |
||
571 | result['reporting_period']['midpeaks'].append(reporting[energy_item_id]['midpeak']) |
||
572 | result['reporting_period']['offpeaks'].append(reporting[energy_item_id]['offpeak']) |
||
573 | result['reporting_period']['deeps'].append(reporting[energy_item_id]['deep']) |
||
574 | result['reporting_period']['increment_rates'].append( |
||
575 | (reporting[energy_item_id]['subtotal'] - base[energy_item_id]['subtotal']) / |
||
576 | base[energy_item_id]['subtotal'] |
||
577 | if base[energy_item_id]['subtotal'] > 0.0 else None) |
||
578 | |||
579 | rate = list() |
||
580 | for index, value in enumerate(reporting[energy_item_id]['values']): |
||
581 | if index < len(base[energy_item_id]['values']) \ |
||
582 | and base[energy_item_id]['values'][index] != 0 and value != 0: |
||
583 | rate.append((value - base[energy_item_id]['values'][index]) |
||
584 | / base[energy_item_id]['values'][index]) |
||
585 | else: |
||
586 | rate.append(None) |
||
587 | result['reporting_period']['rates'].append(rate) |
||
588 | |||
589 | result['parameters'] = { |
||
590 | "names": parameters_data['names'], |
||
591 | "timestamps": parameters_data['timestamps'], |
||
592 | "values": parameters_data['values'] |
||
593 | } |
||
594 | |||
595 | # export result to Excel file and then encode the file to base64 string |
||
596 | result['excel_bytes_base64'] = None |
||
597 | if not is_quick_mode: |
||
598 | result['excel_bytes_base64'] = \ |
||
599 | excelexporters.equipmentenergyitem.export(result, |
||
600 | equipment['name'], |
||
601 | base_period_start_datetime_local, |
||
602 | base_period_end_datetime_local, |
||
603 | reporting_period_start_datetime_local, |
||
604 | reporting_period_end_datetime_local, |
||
605 | period_type, |
||
606 | language) |
||
607 | |||
608 | resp.text = json.dumps(result) |
||
609 |