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.metercarbon |
||
9 | from core import utilities |
||
10 | from core.useractivity import access_control, api_key_control |
||
11 | |||
12 | |||
13 | View Code Duplication | class Reporting: |
|
0 ignored issues
–
show
Duplication
introduced
by
![]() |
|||
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 meter and energy category |
||
27 | # Step 3: query associated points |
||
28 | # Step 4: query base period energy consumption |
||
29 | # Step 5: query base period carbon dioxide emissions |
||
30 | # Step 6: query reporting period energy consumption |
||
31 | # Step 7: query reporting period carbon dioxide emissions |
||
32 | # Step 8: query tariff data |
||
33 | # Step 9: query associated points data |
||
34 | # Step 10: construct the report |
||
35 | #################################################################################################################### |
||
36 | @staticmethod |
||
37 | def on_get(req, resp): |
||
38 | if 'API-KEY' not in req.headers or \ |
||
39 | not isinstance(req.headers['API-KEY'], str) or \ |
||
40 | len(str.strip(req.headers['API-KEY'])) == 0: |
||
41 | access_control(req) |
||
42 | else: |
||
43 | api_key_control(req) |
||
44 | print(req.params) |
||
45 | meter_id = req.params.get('meterid') |
||
46 | meter_uuid = req.params.get('meteruuid') |
||
47 | period_type = req.params.get('periodtype') |
||
48 | base_period_start_datetime_local = req.params.get('baseperiodstartdatetime') |
||
49 | base_period_end_datetime_local = req.params.get('baseperiodenddatetime') |
||
50 | reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
||
51 | reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime') |
||
52 | language = req.params.get('language') |
||
53 | quick_mode = req.params.get('quickmode') |
||
54 | |||
55 | ################################################################################################################ |
||
56 | # Step 1: valid parameters |
||
57 | ################################################################################################################ |
||
58 | if meter_id is None and meter_uuid is None: |
||
59 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_METER_ID') |
||
60 | |||
61 | if meter_id is not None: |
||
62 | meter_id = str.strip(meter_id) |
||
63 | if not meter_id.isdigit() or int(meter_id) <= 0: |
||
64 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
65 | description='API.INVALID_METER_ID') |
||
66 | |||
67 | if meter_uuid is not None: |
||
68 | 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) |
||
69 | match = regex.match(str.strip(meter_uuid)) |
||
70 | if not bool(match): |
||
71 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
72 | description='API.INVALID_METER_UUID') |
||
73 | |||
74 | if period_type is None: |
||
75 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
76 | description='API.INVALID_PERIOD_TYPE') |
||
77 | else: |
||
78 | period_type = str.strip(period_type) |
||
79 | if period_type not in ['hourly', 'daily', 'weekly', 'monthly', 'yearly']: |
||
80 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
81 | description='API.INVALID_PERIOD_TYPE') |
||
82 | |||
83 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
84 | if config.utc_offset[0] == '-': |
||
85 | timezone_offset = -timezone_offset |
||
86 | |||
87 | base_start_datetime_utc = None |
||
88 | if base_period_start_datetime_local is not None and len(str.strip(base_period_start_datetime_local)) > 0: |
||
89 | base_period_start_datetime_local = str.strip(base_period_start_datetime_local) |
||
90 | try: |
||
91 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S') |
||
92 | except ValueError: |
||
93 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
94 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
||
95 | base_start_datetime_utc = \ |
||
96 | base_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
||
97 | # nomalize the start datetime |
||
98 | if config.minutes_to_count == 30 and base_start_datetime_utc.minute >= 30: |
||
99 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
||
100 | else: |
||
101 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
||
102 | |||
103 | base_end_datetime_utc = None |
||
104 | if base_period_end_datetime_local is not None and len(str.strip(base_period_end_datetime_local)) > 0: |
||
105 | base_period_end_datetime_local = str.strip(base_period_end_datetime_local) |
||
106 | try: |
||
107 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S') |
||
108 | except ValueError: |
||
109 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
110 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
||
111 | base_end_datetime_utc = \ |
||
112 | base_end_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
||
113 | |||
114 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
||
115 | base_start_datetime_utc >= base_end_datetime_utc: |
||
116 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
117 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
||
118 | |||
119 | if reporting_period_start_datetime_local is None: |
||
120 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
121 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
||
122 | else: |
||
123 | reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) |
||
124 | try: |
||
125 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, |
||
126 | '%Y-%m-%dT%H:%M:%S') |
||
127 | except ValueError: |
||
128 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
129 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
||
130 | reporting_start_datetime_utc = \ |
||
131 | reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
||
132 | # nomalize the start datetime |
||
133 | if config.minutes_to_count == 30 and reporting_start_datetime_utc.minute >= 30: |
||
134 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
||
135 | else: |
||
136 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
||
137 | |||
138 | if reporting_period_end_datetime_local is None: |
||
139 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
140 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
||
141 | else: |
||
142 | reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) |
||
143 | try: |
||
144 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, |
||
145 | '%Y-%m-%dT%H:%M:%S') |
||
146 | except ValueError: |
||
147 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
148 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
||
149 | reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
||
150 | timedelta(minutes=timezone_offset) |
||
151 | |||
152 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
||
153 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
154 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
||
155 | |||
156 | # if turn quick mode on, do not return parameters data and excel file |
||
157 | is_quick_mode = False |
||
158 | if quick_mode is not None and \ |
||
159 | len(str.strip(quick_mode)) > 0 and \ |
||
160 | str.lower(str.strip(quick_mode)) in ('true', 't', 'on', 'yes', 'y'): |
||
161 | is_quick_mode = True |
||
162 | |||
163 | trans = utilities.get_translation(language) |
||
164 | trans.install() |
||
165 | _ = trans.gettext |
||
166 | |||
167 | ################################################################################################################ |
||
168 | # Step 2: query the meter and energy category |
||
169 | ################################################################################################################ |
||
170 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
||
171 | cursor_system = cnx_system.cursor() |
||
172 | |||
173 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
||
174 | cursor_energy = cnx_energy.cursor() |
||
175 | |||
176 | cnx_carbon = mysql.connector.connect(**config.myems_carbon_db) |
||
177 | cursor_carbon = cnx_carbon.cursor() |
||
178 | |||
179 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
||
180 | cursor_historical = cnx_historical.cursor() |
||
181 | if meter_id is not None: |
||
182 | cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, " |
||
183 | " ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
||
184 | " FROM tbl_meters m, tbl_energy_categories ec " |
||
185 | " WHERE m.id = %s AND m.energy_category_id = ec.id ", (meter_id,)) |
||
186 | row_meter = cursor_system.fetchone() |
||
187 | elif meter_uuid is not None: |
||
188 | cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, " |
||
189 | " ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
||
190 | " FROM tbl_meters m, tbl_energy_categories ec " |
||
191 | " WHERE m.uuid = %s AND m.energy_category_id = ec.id ", (meter_uuid,)) |
||
192 | row_meter = cursor_system.fetchone() |
||
193 | |||
194 | if row_meter is None: |
||
0 ignored issues
–
show
|
|||
195 | if cursor_system: |
||
196 | cursor_system.close() |
||
197 | if cnx_system: |
||
198 | cnx_system.close() |
||
199 | |||
200 | if cursor_energy: |
||
201 | cursor_energy.close() |
||
202 | if cnx_energy: |
||
203 | cnx_energy.close() |
||
204 | |||
205 | if cursor_carbon: |
||
206 | cursor_carbon.close() |
||
207 | if cnx_carbon: |
||
208 | cnx_carbon.close() |
||
209 | |||
210 | if cursor_historical: |
||
211 | cursor_historical.close() |
||
212 | if cnx_historical: |
||
213 | cnx_historical.close() |
||
214 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', description='API.METER_NOT_FOUND') |
||
215 | |||
216 | meter = dict() |
||
217 | meter['id'] = row_meter[0] |
||
218 | meter['name'] = row_meter[1] |
||
219 | meter['cost_center_id'] = row_meter[2] |
||
220 | meter['energy_category_id'] = row_meter[3] |
||
221 | meter['energy_category_name'] = row_meter[4] |
||
222 | meter['unit_of_measure'] = config.currency_unit |
||
223 | meter['kgce'] = row_meter[6] |
||
224 | meter['kgco2e'] = row_meter[7] |
||
225 | |||
226 | ################################################################################################################ |
||
227 | # Step 3: query associated points |
||
228 | ################################################################################################################ |
||
229 | point_list = list() |
||
230 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
||
231 | " FROM tbl_meters m, tbl_meters_points mp, tbl_points p " |
||
232 | " WHERE m.id = %s AND m.id = mp.meter_id AND mp.point_id = p.id " |
||
233 | " ORDER BY p.id ", (meter['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 4: query base period energy consumption |
||
241 | ################################################################################################################ |
||
242 | query = (" SELECT start_datetime_utc, actual_value " |
||
243 | " FROM tbl_meter_hourly " |
||
244 | " WHERE meter_id = %s " |
||
245 | " AND start_datetime_utc >= %s " |
||
246 | " AND start_datetime_utc < %s " |
||
247 | " ORDER BY start_datetime_utc ") |
||
248 | cursor_energy.execute(query, (meter['id'], base_start_datetime_utc, base_end_datetime_utc)) |
||
249 | rows_meter_hourly = cursor_energy.fetchall() |
||
250 | |||
251 | rows_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_meter_hourly, |
||
252 | base_start_datetime_utc, |
||
253 | base_end_datetime_utc, |
||
254 | period_type) |
||
255 | base = dict() |
||
256 | base['timestamps'] = list() |
||
257 | base['values'] = list() |
||
258 | base['total_in_category'] = Decimal(0.0) |
||
259 | base['total_in_kgce'] = Decimal(0.0) |
||
260 | base['total_in_kgco2e'] = Decimal(0.0) |
||
261 | |||
262 | for row_meter_periodically in rows_meter_periodically: |
||
263 | current_datetime_local = row_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
264 | timedelta(minutes=timezone_offset) |
||
265 | if period_type == 'hourly': |
||
266 | current_datetime = current_datetime_local.isoformat()[0:19] |
||
267 | elif period_type == 'daily': |
||
268 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
269 | elif period_type == 'weekly': |
||
270 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
271 | elif period_type == 'monthly': |
||
272 | current_datetime = current_datetime_local.isoformat()[0:7] |
||
273 | elif period_type == 'yearly': |
||
274 | current_datetime = current_datetime_local.isoformat()[0:4] |
||
275 | |||
276 | actual_value = Decimal(0.0) if row_meter_periodically[1] is None \ |
||
277 | else row_meter_periodically[1] |
||
278 | base['timestamps'].append(current_datetime) |
||
0 ignored issues
–
show
|
|||
279 | base['total_in_kgce'] += actual_value * meter['kgce'] |
||
280 | base['total_in_kgco2e'] += actual_value * meter['kgco2e'] |
||
281 | |||
282 | ################################################################################################################ |
||
283 | # Step 5: query base period carbon dioxide emissions |
||
284 | ################################################################################################################ |
||
285 | query = (" SELECT start_datetime_utc, actual_value " |
||
286 | " FROM tbl_meter_hourly " |
||
287 | " WHERE meter_id = %s " |
||
288 | " AND start_datetime_utc >= %s " |
||
289 | " AND start_datetime_utc < %s " |
||
290 | " ORDER BY start_datetime_utc ") |
||
291 | cursor_carbon.execute(query, (meter['id'], base_start_datetime_utc, base_end_datetime_utc)) |
||
292 | rows_meter_hourly = cursor_carbon.fetchall() |
||
293 | |||
294 | rows_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_meter_hourly, |
||
295 | base_start_datetime_utc, |
||
296 | base_end_datetime_utc, |
||
297 | period_type) |
||
298 | |||
299 | base['values'] = list() |
||
300 | base['total_in_category'] = Decimal(0.0) |
||
301 | |||
302 | for row_meter_periodically in rows_meter_periodically: |
||
303 | actual_value = Decimal(0.0) if row_meter_periodically[1] is None \ |
||
304 | else row_meter_periodically[1] |
||
305 | base['values'].append(actual_value) |
||
306 | base['total_in_category'] += actual_value |
||
307 | |||
308 | ################################################################################################################ |
||
309 | # Step 6: query reporting period energy consumption |
||
310 | ################################################################################################################ |
||
311 | query = (" SELECT start_datetime_utc, actual_value " |
||
312 | " FROM tbl_meter_hourly " |
||
313 | " WHERE meter_id = %s " |
||
314 | " AND start_datetime_utc >= %s " |
||
315 | " AND start_datetime_utc < %s " |
||
316 | " ORDER BY start_datetime_utc ") |
||
317 | cursor_energy.execute(query, (meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
||
318 | rows_meter_hourly = cursor_energy.fetchall() |
||
319 | |||
320 | rows_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_meter_hourly, |
||
321 | reporting_start_datetime_utc, |
||
322 | reporting_end_datetime_utc, |
||
323 | period_type) |
||
324 | reporting = dict() |
||
325 | reporting['timestamps'] = list() |
||
326 | reporting['values'] = list() |
||
327 | reporting['rates'] = list() |
||
328 | reporting['total_in_category'] = Decimal(0.0) |
||
329 | reporting['total_in_kgce'] = Decimal(0.0) |
||
330 | reporting['total_in_kgco2e'] = Decimal(0.0) |
||
331 | |||
332 | for row_meter_periodically in rows_meter_periodically: |
||
333 | current_datetime_local = row_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
||
334 | timedelta(minutes=timezone_offset) |
||
335 | if period_type == 'hourly': |
||
336 | current_datetime = current_datetime_local.isoformat()[0:19] |
||
337 | elif period_type == 'daily': |
||
338 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
339 | elif period_type == 'weekly': |
||
340 | current_datetime = current_datetime_local.isoformat()[0:10] |
||
341 | elif period_type == 'monthly': |
||
342 | current_datetime = current_datetime_local.isoformat()[0:7] |
||
343 | elif period_type == 'yearly': |
||
344 | current_datetime = current_datetime_local.isoformat()[0:4] |
||
345 | |||
346 | actual_value = Decimal(0.0) if row_meter_periodically[1] is None \ |
||
347 | else row_meter_periodically[1] |
||
348 | |||
349 | reporting['timestamps'].append(current_datetime) |
||
350 | reporting['total_in_kgce'] += actual_value * meter['kgce'] |
||
351 | reporting['total_in_kgco2e'] += actual_value * meter['kgco2e'] |
||
352 | |||
353 | ################################################################################################################ |
||
354 | # Step 7: query reporting period carbon dioxide emissions |
||
355 | ################################################################################################################ |
||
356 | query = (" SELECT start_datetime_utc, actual_value " |
||
357 | " FROM tbl_meter_hourly " |
||
358 | " WHERE meter_id = %s " |
||
359 | " AND start_datetime_utc >= %s " |
||
360 | " AND start_datetime_utc < %s " |
||
361 | " ORDER BY start_datetime_utc ") |
||
362 | cursor_carbon.execute(query, (meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
||
363 | rows_meter_hourly = cursor_carbon.fetchall() |
||
364 | |||
365 | rows_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_meter_hourly, |
||
366 | reporting_start_datetime_utc, |
||
367 | reporting_end_datetime_utc, |
||
368 | period_type) |
||
369 | |||
370 | for row_meter_periodically in rows_meter_periodically: |
||
371 | actual_value = Decimal(0.0) if row_meter_periodically[1] is None \ |
||
372 | else row_meter_periodically[1] |
||
373 | |||
374 | reporting['values'].append(actual_value) |
||
375 | reporting['total_in_category'] += actual_value |
||
376 | |||
377 | for index, value in enumerate(reporting['values']): |
||
378 | if index < len(base['values']) and base['values'][index] != 0 and value != 0: |
||
379 | reporting['rates'].append((value - base['values'][index]) / base['values'][index]) |
||
380 | else: |
||
381 | reporting['rates'].append(None) |
||
382 | |||
383 | ################################################################################################################ |
||
384 | # Step 8: query tariff data |
||
385 | ################################################################################################################ |
||
386 | parameters_data = dict() |
||
387 | parameters_data['names'] = list() |
||
388 | parameters_data['timestamps'] = list() |
||
389 | parameters_data['values'] = list() |
||
390 | |||
391 | if config.is_tariff_appended and not is_quick_mode: |
||
392 | tariff_dict = utilities.get_energy_category_tariffs(meter['cost_center_id'], |
||
393 | meter['energy_category_id'], |
||
394 | reporting_start_datetime_utc, |
||
395 | reporting_end_datetime_utc) |
||
396 | tariff_timestamp_list = list() |
||
397 | tariff_value_list = list() |
||
398 | for k, v in tariff_dict.items(): |
||
399 | # convert k from utc to local |
||
400 | k = k + timedelta(minutes=timezone_offset) |
||
401 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
||
402 | tariff_value_list.append(v) |
||
403 | |||
404 | parameters_data['names'].append(_('Tariff') + '-' + meter['energy_category_name']) |
||
405 | parameters_data['timestamps'].append(tariff_timestamp_list) |
||
406 | parameters_data['values'].append(tariff_value_list) |
||
407 | |||
408 | ################################################################################################################ |
||
409 | # Step 9: query associated points data |
||
410 | ################################################################################################################ |
||
411 | if not is_quick_mode: |
||
412 | for point in point_list: |
||
413 | point_values = [] |
||
414 | point_timestamps = [] |
||
415 | if point['object_type'] == 'ENERGY_VALUE': |
||
416 | query = (" SELECT utc_date_time, actual_value " |
||
417 | " FROM tbl_energy_value " |
||
418 | " WHERE point_id = %s " |
||
419 | " AND utc_date_time BETWEEN %s AND %s " |
||
420 | " ORDER BY utc_date_time ") |
||
421 | cursor_historical.execute(query, (point['id'], |
||
422 | reporting_start_datetime_utc, |
||
423 | reporting_end_datetime_utc)) |
||
424 | rows = cursor_historical.fetchall() |
||
425 | |||
426 | if rows is not None and len(rows) > 0: |
||
427 | for row in rows: |
||
428 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
429 | timedelta(minutes=timezone_offset) |
||
430 | current_datetime = current_datetime_local.isoformat()[0:19] |
||
431 | point_timestamps.append(current_datetime) |
||
432 | point_values.append(row[1]) |
||
433 | elif point['object_type'] == 'ANALOG_VALUE': |
||
434 | query = (" SELECT utc_date_time, actual_value " |
||
435 | " FROM tbl_analog_value " |
||
436 | " WHERE point_id = %s " |
||
437 | " AND utc_date_time BETWEEN %s AND %s " |
||
438 | " ORDER BY utc_date_time ") |
||
439 | cursor_historical.execute(query, (point['id'], |
||
440 | reporting_start_datetime_utc, |
||
441 | reporting_end_datetime_utc)) |
||
442 | rows = cursor_historical.fetchall() |
||
443 | |||
444 | if rows is not None and len(rows) > 0: |
||
445 | for row in rows: |
||
446 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
447 | timedelta(minutes=timezone_offset) |
||
448 | current_datetime = current_datetime_local.isoformat()[0:19] |
||
449 | point_timestamps.append(current_datetime) |
||
450 | point_values.append(row[1]) |
||
451 | elif point['object_type'] == 'DIGITAL_VALUE': |
||
452 | query = (" SELECT utc_date_time, actual_value " |
||
453 | " FROM tbl_digital_value " |
||
454 | " WHERE point_id = %s " |
||
455 | " AND utc_date_time BETWEEN %s AND %s " |
||
456 | " ORDER BY utc_date_time ") |
||
457 | cursor_historical.execute(query, (point['id'], |
||
458 | reporting_start_datetime_utc, |
||
459 | reporting_end_datetime_utc)) |
||
460 | rows = cursor_historical.fetchall() |
||
461 | |||
462 | if rows is not None and len(rows) > 0: |
||
463 | for row in rows: |
||
464 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
||
465 | timedelta(minutes=timezone_offset) |
||
466 | current_datetime = current_datetime_local.isoformat()[0:19] |
||
467 | point_timestamps.append(current_datetime) |
||
468 | point_values.append(row[1]) |
||
469 | |||
470 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
||
471 | parameters_data['timestamps'].append(point_timestamps) |
||
472 | parameters_data['values'].append(point_values) |
||
473 | |||
474 | ################################################################################################################ |
||
475 | # Step 10: construct the report |
||
476 | ################################################################################################################ |
||
477 | if cursor_system: |
||
478 | cursor_system.close() |
||
479 | if cnx_system: |
||
480 | cnx_system.close() |
||
481 | |||
482 | if cursor_energy: |
||
483 | cursor_energy.close() |
||
484 | if cnx_energy: |
||
485 | cnx_energy.close() |
||
486 | |||
487 | if cursor_carbon: |
||
488 | cursor_carbon.close() |
||
489 | if cnx_carbon: |
||
490 | cnx_carbon.close() |
||
491 | |||
492 | if cursor_historical: |
||
493 | cursor_historical.close() |
||
494 | if cnx_historical: |
||
495 | cnx_historical.close() |
||
496 | result = {"meter": { |
||
497 | "cost_center_id": meter['cost_center_id'], |
||
498 | "energy_category_id": meter['energy_category_id'], |
||
499 | "energy_category_name": meter['energy_category_name'], |
||
500 | "unit_of_measure": 'KG', |
||
501 | "kgce": meter['kgce'], |
||
502 | "kgco2e": meter['kgco2e'], |
||
503 | }, "base_period": { |
||
504 | "total_in_category": base['total_in_category'], |
||
505 | "total_in_kgce": base['total_in_kgce'], |
||
506 | "total_in_kgco2e": base['total_in_kgco2e'], |
||
507 | "timestamps": base['timestamps'], |
||
508 | "values": base['values'], |
||
509 | }, "reporting_period": { |
||
510 | "increment_rate": |
||
511 | (reporting['total_in_category'] - base['total_in_category']) / base['total_in_category'] |
||
512 | if base['total_in_category'] != Decimal(0.0) else None, |
||
513 | "total_in_category": reporting['total_in_category'], |
||
514 | "total_in_kgce": reporting['total_in_kgce'], |
||
515 | "total_in_kgco2e": reporting['total_in_kgco2e'], |
||
516 | "timestamps": reporting['timestamps'], |
||
517 | "values": reporting['values'], |
||
518 | "rates": reporting['rates'], |
||
519 | }, "parameters": { |
||
520 | "names": parameters_data['names'], |
||
521 | "timestamps": parameters_data['timestamps'], |
||
522 | "values": parameters_data['values'] |
||
523 | }, 'excel_bytes_base64': None} |
||
524 | # export result to Excel file and then encode the file to base64 string |
||
525 | if not is_quick_mode: |
||
526 | result['excel_bytes_base64'] = \ |
||
527 | excelexporters.metercarbon.export(result, |
||
528 | meter['name'], |
||
529 | base_period_start_datetime_local, |
||
530 | base_period_end_datetime_local, |
||
531 | reporting_period_start_datetime_local, |
||
532 | reporting_period_end_datetime_local, |
||
533 | period_type, |
||
534 | language) |
||
535 | |||
536 | resp.text = json.dumps(result) |
||
537 |