@@ 13-780 (lines=768) @@ | ||
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 shopfloor |
|
27 | # Step 3: query energy categories |
|
28 | # Step 4: query associated sensors |
|
29 | # Step 5: query associated points |
|
30 | # Step 6: query base period energy saving |
|
31 | # Step 7: query reporting period energy saving |
|
32 | # Step 8: query tariff data |
|
33 | # Step 9: query associated sensors and 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 | shopfloor_id = req.params.get('shopfloorid') |
|
46 | shopfloor_uuid = req.params.get('shopflooruuid') |
|
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 shopfloor_id is None and shopfloor_uuid is None: |
|
59 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
60 | title='API.BAD_REQUEST', |
|
61 | description='API.INVALID_SHOPFLOOR_ID') |
|
62 | ||
63 | if shopfloor_id is not None: |
|
64 | shopfloor_id = str.strip(shopfloor_id) |
|
65 | if not shopfloor_id.isdigit() or int(shopfloor_id) <= 0: |
|
66 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
67 | title='API.BAD_REQUEST', |
|
68 | description='API.INVALID_SHOPFLOOR_ID') |
|
69 | ||
70 | if shopfloor_uuid is not None: |
|
71 | 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) |
|
72 | match = regex.match(str.strip(shopfloor_uuid)) |
|
73 | if not bool(match): |
|
74 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
75 | title='API.BAD_REQUEST', |
|
76 | description='API.INVALID_SHOPFLOOR_UUID') |
|
77 | ||
78 | if period_type is None: |
|
79 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
80 | description='API.INVALID_PERIOD_TYPE') |
|
81 | else: |
|
82 | period_type = str.strip(period_type) |
|
83 | if period_type not in ['hourly', 'daily', 'weekly', 'monthly', 'yearly']: |
|
84 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
85 | description='API.INVALID_PERIOD_TYPE') |
|
86 | ||
87 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
|
88 | if config.utc_offset[0] == '-': |
|
89 | timezone_offset = -timezone_offset |
|
90 | ||
91 | base_start_datetime_utc = None |
|
92 | if base_period_start_datetime_local is not None and len(str.strip(base_period_start_datetime_local)) > 0: |
|
93 | base_period_start_datetime_local = str.strip(base_period_start_datetime_local) |
|
94 | try: |
|
95 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
96 | except ValueError: |
|
97 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
98 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
|
99 | base_start_datetime_utc = \ |
|
100 | base_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
101 | # nomalize the start datetime |
|
102 | if config.minutes_to_count == 30 and base_start_datetime_utc.minute >= 30: |
|
103 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
|
104 | else: |
|
105 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
|
106 | ||
107 | base_end_datetime_utc = None |
|
108 | if base_period_end_datetime_local is not None and len(str.strip(base_period_end_datetime_local)) > 0: |
|
109 | base_period_end_datetime_local = str.strip(base_period_end_datetime_local) |
|
110 | try: |
|
111 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
112 | except ValueError: |
|
113 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
114 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
|
115 | base_end_datetime_utc = \ |
|
116 | base_end_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
117 | ||
118 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
|
119 | base_start_datetime_utc >= base_end_datetime_utc: |
|
120 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
121 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
|
122 | ||
123 | if reporting_period_start_datetime_local is None: |
|
124 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
125 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
126 | else: |
|
127 | reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) |
|
128 | try: |
|
129 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, |
|
130 | '%Y-%m-%dT%H:%M:%S') |
|
131 | except ValueError: |
|
132 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
133 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
134 | reporting_start_datetime_utc = \ |
|
135 | reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
136 | # nomalize the start datetime |
|
137 | if config.minutes_to_count == 30 and reporting_start_datetime_utc.minute >= 30: |
|
138 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
|
139 | else: |
|
140 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
|
141 | ||
142 | if reporting_period_end_datetime_local is None: |
|
143 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
144 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
145 | else: |
|
146 | reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) |
|
147 | try: |
|
148 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, |
|
149 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
150 | timedelta(minutes=timezone_offset) |
|
151 | except ValueError: |
|
152 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
153 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
154 | ||
155 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
|
156 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
157 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
|
158 | ||
159 | # if turn quick mode on, do not return parameters data and excel file |
|
160 | is_quick_mode = False |
|
161 | if quick_mode is not None and \ |
|
162 | len(str.strip(quick_mode)) > 0 and \ |
|
163 | str.lower(str.strip(quick_mode)) in ('true', 't', 'on', 'yes', 'y'): |
|
164 | is_quick_mode = True |
|
165 | ||
166 | trans = utilities.get_translation(language) |
|
167 | trans.install() |
|
168 | _ = trans.gettext |
|
169 | ||
170 | ################################################################################################################ |
|
171 | # Step 2: query the shopfloor |
|
172 | ################################################################################################################ |
|
173 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
|
174 | cursor_system = cnx_system.cursor() |
|
175 | ||
176 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
|
177 | cursor_energy = cnx_energy.cursor() |
|
178 | ||
179 | cnx_energy_baseline = mysql.connector.connect(**config.myems_energy_baseline_db) |
|
180 | cursor_energy_baseline = cnx_energy_baseline.cursor() |
|
181 | ||
182 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
|
183 | cursor_historical = cnx_historical.cursor() |
|
184 | ||
185 | if shopfloor_id is not None: |
|
186 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
187 | " FROM tbl_shopfloors " |
|
188 | " WHERE id = %s ", (shopfloor_id,)) |
|
189 | row_shopfloor = cursor_system.fetchone() |
|
190 | elif shopfloor_uuid is not None: |
|
191 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
192 | " FROM tbl_shopfloors " |
|
193 | " WHERE uuid = %s ", (shopfloor_uuid,)) |
|
194 | row_shopfloor = cursor_system.fetchone() |
|
195 | ||
196 | if row_shopfloor is None: |
|
197 | if cursor_system: |
|
198 | cursor_system.close() |
|
199 | if cnx_system: |
|
200 | cnx_system.close() |
|
201 | ||
202 | if cursor_energy: |
|
203 | cursor_energy.close() |
|
204 | if cnx_energy: |
|
205 | cnx_energy.close() |
|
206 | ||
207 | if cursor_energy_baseline: |
|
208 | cursor_energy_baseline.close() |
|
209 | if cnx_energy_baseline: |
|
210 | cnx_energy_baseline.close() |
|
211 | ||
212 | if cursor_historical: |
|
213 | cursor_historical.close() |
|
214 | if cnx_historical: |
|
215 | cnx_historical.close() |
|
216 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', description='API.SHOPFLOOR_NOT_FOUND') |
|
217 | ||
218 | shopfloor = dict() |
|
219 | shopfloor['id'] = row_shopfloor[0] |
|
220 | shopfloor['name'] = row_shopfloor[1] |
|
221 | shopfloor['area'] = row_shopfloor[2] |
|
222 | shopfloor['cost_center_id'] = row_shopfloor[3] |
|
223 | ||
224 | ################################################################################################################ |
|
225 | # Step 3: query energy categories |
|
226 | ################################################################################################################ |
|
227 | energy_category_set = set() |
|
228 | # query energy categories in base period |
|
229 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
230 | " FROM tbl_shopfloor_input_category_hourly " |
|
231 | " WHERE shopfloor_id = %s " |
|
232 | " AND start_datetime_utc >= %s " |
|
233 | " AND start_datetime_utc < %s ", |
|
234 | (shopfloor['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
235 | rows_energy_categories = cursor_energy.fetchall() |
|
236 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
|
237 | for row_energy_category in rows_energy_categories: |
|
238 | energy_category_set.add(row_energy_category[0]) |
|
239 | ||
240 | # query energy categories in reporting period |
|
241 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
242 | " FROM tbl_shopfloor_input_category_hourly " |
|
243 | " WHERE shopfloor_id = %s " |
|
244 | " AND start_datetime_utc >= %s " |
|
245 | " AND start_datetime_utc < %s ", |
|
246 | (shopfloor['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
247 | rows_energy_categories = cursor_energy.fetchall() |
|
248 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
|
249 | for row_energy_category in rows_energy_categories: |
|
250 | energy_category_set.add(row_energy_category[0]) |
|
251 | ||
252 | # query all energy categories in base period and reporting period |
|
253 | cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e " |
|
254 | " FROM tbl_energy_categories " |
|
255 | " ORDER BY id ", ) |
|
256 | rows_energy_categories = cursor_system.fetchall() |
|
257 | if rows_energy_categories is None or len(rows_energy_categories) == 0: |
|
258 | if cursor_system: |
|
259 | cursor_system.close() |
|
260 | if cnx_system: |
|
261 | cnx_system.close() |
|
262 | ||
263 | if cursor_energy: |
|
264 | cursor_energy.close() |
|
265 | if cnx_energy: |
|
266 | cnx_energy.close() |
|
267 | ||
268 | if cursor_energy_baseline: |
|
269 | cursor_energy_baseline.close() |
|
270 | if cnx_energy_baseline: |
|
271 | cnx_energy_baseline.close() |
|
272 | ||
273 | if cursor_historical: |
|
274 | cursor_historical.close() |
|
275 | if cnx_historical: |
|
276 | cnx_historical.close() |
|
277 | raise falcon.HTTPError(status=falcon.HTTP_404, |
|
278 | title='API.NOT_FOUND', |
|
279 | description='API.ENERGY_CATEGORY_NOT_FOUND') |
|
280 | energy_category_dict = dict() |
|
281 | for row_energy_category in rows_energy_categories: |
|
282 | if row_energy_category[0] in energy_category_set: |
|
283 | energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1], |
|
284 | "unit_of_measure": row_energy_category[2], |
|
285 | "kgce": row_energy_category[3], |
|
286 | "kgco2e": row_energy_category[4]} |
|
287 | ||
288 | ################################################################################################################ |
|
289 | # Step 4: query associated sensors |
|
290 | ################################################################################################################ |
|
291 | point_list = list() |
|
292 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
293 | " FROM tbl_shopfloors st, tbl_sensors se, tbl_shopfloors_sensors ss, " |
|
294 | " tbl_points p, tbl_sensors_points sp " |
|
295 | " WHERE st.id = %s AND st.id = ss.shopfloor_id AND ss.sensor_id = se.id " |
|
296 | " AND se.id = sp.sensor_id AND sp.point_id = p.id " |
|
297 | " ORDER BY p.id ", (shopfloor['id'],)) |
|
298 | rows_points = cursor_system.fetchall() |
|
299 | if rows_points is not None and len(rows_points) > 0: |
|
300 | for row in rows_points: |
|
301 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
302 | ||
303 | ################################################################################################################ |
|
304 | # Step 5: query associated points |
|
305 | ################################################################################################################ |
|
306 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
307 | " FROM tbl_shopfloors s, tbl_shopfloors_points sp, tbl_points p " |
|
308 | " WHERE s.id = %s AND s.id = sp.shopfloor_id AND sp.point_id = p.id " |
|
309 | " ORDER BY p.id ", (shopfloor['id'],)) |
|
310 | rows_points = cursor_system.fetchall() |
|
311 | if rows_points is not None and len(rows_points) > 0: |
|
312 | for row in rows_points: |
|
313 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
314 | ||
315 | ################################################################################################################ |
|
316 | # Step 6: query base period energy saving |
|
317 | ################################################################################################################ |
|
318 | base = dict() |
|
319 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
320 | for energy_category_id in energy_category_set: |
|
321 | kgce = energy_category_dict[energy_category_id]['kgce'] |
|
322 | kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
|
323 | ||
324 | base[energy_category_id] = dict() |
|
325 | base[energy_category_id]['timestamps'] = list() |
|
326 | base[energy_category_id]['values_baseline'] = list() |
|
327 | base[energy_category_id]['values_actual'] = list() |
|
328 | base[energy_category_id]['values_saving'] = list() |
|
329 | base[energy_category_id]['subtotal_baseline'] = Decimal(0.0) |
|
330 | base[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
|
331 | base[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
|
332 | base[energy_category_id]['subtotal_in_kgce_baseline'] = Decimal(0.0) |
|
333 | base[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
|
334 | base[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
|
335 | base[energy_category_id]['subtotal_in_kgco2e_baseline'] = Decimal(0.0) |
|
336 | base[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
|
337 | base[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
|
338 | # query base period's energy baseline |
|
339 | cursor_energy_baseline.execute(" SELECT start_datetime_utc, actual_value " |
|
340 | " FROM tbl_shopfloor_input_category_hourly " |
|
341 | " WHERE shopfloor_id = %s " |
|
342 | " AND energy_category_id = %s " |
|
343 | " AND start_datetime_utc >= %s " |
|
344 | " AND start_datetime_utc < %s " |
|
345 | " ORDER BY start_datetime_utc ", |
|
346 | (shopfloor['id'], |
|
347 | energy_category_id, |
|
348 | base_start_datetime_utc, |
|
349 | base_end_datetime_utc)) |
|
350 | rows_shopfloor_hourly = cursor_energy_baseline.fetchall() |
|
351 | ||
352 | rows_shopfloor_periodically = utilities.aggregate_hourly_data_by_period(rows_shopfloor_hourly, |
|
353 | base_start_datetime_utc, |
|
354 | base_end_datetime_utc, |
|
355 | period_type) |
|
356 | for row_shopfloor_periodically in rows_shopfloor_periodically: |
|
357 | current_datetime_local = row_shopfloor_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
358 | timedelta(minutes=timezone_offset) |
|
359 | if period_type == 'hourly': |
|
360 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
361 | elif period_type == 'daily': |
|
362 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
363 | elif period_type == 'weekly': |
|
364 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
365 | elif period_type == 'monthly': |
|
366 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
367 | elif period_type == 'yearly': |
|
368 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
369 | ||
370 | baseline_value = Decimal(0.0) if row_shopfloor_periodically[1] is None \ |
|
371 | else row_shopfloor_periodically[1] |
|
372 | base[energy_category_id]['timestamps'].append(current_datetime) |
|
373 | base[energy_category_id]['values_baseline'].append(baseline_value) |
|
374 | base[energy_category_id]['subtotal_baseline'] += baseline_value |
|
375 | base[energy_category_id]['subtotal_in_kgce_baseline'] += baseline_value * kgce |
|
376 | base[energy_category_id]['subtotal_in_kgco2e_baseline'] += baseline_value * kgco2e |
|
377 | ||
378 | # query base period's energy actual |
|
379 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
380 | " FROM tbl_shopfloor_input_category_hourly " |
|
381 | " WHERE shopfloor_id = %s " |
|
382 | " AND energy_category_id = %s " |
|
383 | " AND start_datetime_utc >= %s " |
|
384 | " AND start_datetime_utc < %s " |
|
385 | " ORDER BY start_datetime_utc ", |
|
386 | (shopfloor['id'], |
|
387 | energy_category_id, |
|
388 | base_start_datetime_utc, |
|
389 | base_end_datetime_utc)) |
|
390 | rows_shopfloor_hourly = cursor_energy.fetchall() |
|
391 | ||
392 | rows_shopfloor_periodically = utilities.aggregate_hourly_data_by_period(rows_shopfloor_hourly, |
|
393 | base_start_datetime_utc, |
|
394 | base_end_datetime_utc, |
|
395 | period_type) |
|
396 | for row_shopfloor_periodically in rows_shopfloor_periodically: |
|
397 | current_datetime_local = row_shopfloor_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
398 | timedelta(minutes=timezone_offset) |
|
399 | if period_type == 'hourly': |
|
400 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
401 | elif period_type == 'daily': |
|
402 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
403 | elif period_type == 'weekly': |
|
404 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
405 | elif period_type == 'monthly': |
|
406 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
407 | elif period_type == 'yearly': |
|
408 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
409 | ||
410 | actual_value = Decimal(0.0) if row_shopfloor_periodically[1] is None \ |
|
411 | else row_shopfloor_periodically[1] |
|
412 | base[energy_category_id]['values_actual'].append(actual_value) |
|
413 | base[energy_category_id]['subtotal_actual'] += actual_value |
|
414 | base[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
|
415 | base[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
|
416 | ||
417 | # calculate base period's energy savings |
|
418 | for i in range(len(base[energy_category_id]['values_baseline'])): |
|
419 | base[energy_category_id]['values_saving'].append( |
|
420 | base[energy_category_id]['values_baseline'][i] - |
|
421 | base[energy_category_id]['values_actual'][i]) |
|
422 | ||
423 | base[energy_category_id]['subtotal_saving'] = \ |
|
424 | base[energy_category_id]['subtotal_baseline'] - \ |
|
425 | base[energy_category_id]['subtotal_actual'] |
|
426 | base[energy_category_id]['subtotal_in_kgce_saving'] = \ |
|
427 | base[energy_category_id]['subtotal_in_kgce_baseline'] - \ |
|
428 | base[energy_category_id]['subtotal_in_kgce_actual'] |
|
429 | base[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
|
430 | base[energy_category_id]['subtotal_in_kgco2e_baseline'] - \ |
|
431 | base[energy_category_id]['subtotal_in_kgco2e_actual'] |
|
432 | ################################################################################################################ |
|
433 | # Step 7: query reporting period energy saving |
|
434 | ################################################################################################################ |
|
435 | reporting = dict() |
|
436 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
437 | for energy_category_id in energy_category_set: |
|
438 | kgce = energy_category_dict[energy_category_id]['kgce'] |
|
439 | kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
|
440 | ||
441 | reporting[energy_category_id] = dict() |
|
442 | reporting[energy_category_id]['timestamps'] = list() |
|
443 | reporting[energy_category_id]['values_baseline'] = list() |
|
444 | reporting[energy_category_id]['values_actual'] = list() |
|
445 | reporting[energy_category_id]['values_saving'] = list() |
|
446 | reporting[energy_category_id]['subtotal_baseline'] = Decimal(0.0) |
|
447 | reporting[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
|
448 | reporting[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
|
449 | reporting[energy_category_id]['subtotal_in_kgce_baseline'] = Decimal(0.0) |
|
450 | reporting[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
|
451 | reporting[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
|
452 | reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] = Decimal(0.0) |
|
453 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
|
454 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
|
455 | # query reporting period's energy baseline |
|
456 | cursor_energy_baseline.execute(" SELECT start_datetime_utc, actual_value " |
|
457 | " FROM tbl_shopfloor_input_category_hourly " |
|
458 | " WHERE shopfloor_id = %s " |
|
459 | " AND energy_category_id = %s " |
|
460 | " AND start_datetime_utc >= %s " |
|
461 | " AND start_datetime_utc < %s " |
|
462 | " ORDER BY start_datetime_utc ", |
|
463 | (shopfloor['id'], |
|
464 | energy_category_id, |
|
465 | reporting_start_datetime_utc, |
|
466 | reporting_end_datetime_utc)) |
|
467 | rows_shopfloor_hourly = cursor_energy_baseline.fetchall() |
|
468 | ||
469 | rows_shopfloor_periodically = utilities.aggregate_hourly_data_by_period(rows_shopfloor_hourly, |
|
470 | reporting_start_datetime_utc, |
|
471 | reporting_end_datetime_utc, |
|
472 | period_type) |
|
473 | for row_shopfloor_periodically in rows_shopfloor_periodically: |
|
474 | current_datetime_local = row_shopfloor_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
475 | timedelta(minutes=timezone_offset) |
|
476 | if period_type == 'hourly': |
|
477 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
478 | elif period_type == 'daily': |
|
479 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
480 | elif period_type == 'weekly': |
|
481 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
482 | elif period_type == 'monthly': |
|
483 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
484 | elif period_type == 'yearly': |
|
485 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
486 | ||
487 | baseline_value = Decimal(0.0) if row_shopfloor_periodically[1] is None \ |
|
488 | else row_shopfloor_periodically[1] |
|
489 | reporting[energy_category_id]['timestamps'].append(current_datetime) |
|
490 | reporting[energy_category_id]['values_baseline'].append(baseline_value) |
|
491 | reporting[energy_category_id]['subtotal_baseline'] += baseline_value |
|
492 | reporting[energy_category_id]['subtotal_in_kgce_baseline'] += baseline_value * kgce |
|
493 | reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] += baseline_value * kgco2e |
|
494 | ||
495 | # query reporting period's energy actual |
|
496 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
497 | " FROM tbl_shopfloor_input_category_hourly " |
|
498 | " WHERE shopfloor_id = %s " |
|
499 | " AND energy_category_id = %s " |
|
500 | " AND start_datetime_utc >= %s " |
|
501 | " AND start_datetime_utc < %s " |
|
502 | " ORDER BY start_datetime_utc ", |
|
503 | (shopfloor['id'], |
|
504 | energy_category_id, |
|
505 | reporting_start_datetime_utc, |
|
506 | reporting_end_datetime_utc)) |
|
507 | rows_shopfloor_hourly = cursor_energy.fetchall() |
|
508 | ||
509 | rows_shopfloor_periodically = utilities.aggregate_hourly_data_by_period(rows_shopfloor_hourly, |
|
510 | reporting_start_datetime_utc, |
|
511 | reporting_end_datetime_utc, |
|
512 | period_type) |
|
513 | for row_shopfloor_periodically in rows_shopfloor_periodically: |
|
514 | current_datetime_local = row_shopfloor_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
515 | timedelta(minutes=timezone_offset) |
|
516 | if period_type == 'hourly': |
|
517 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
518 | elif period_type == 'daily': |
|
519 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
520 | elif period_type == 'weekly': |
|
521 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
522 | elif period_type == 'monthly': |
|
523 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
524 | elif period_type == 'yearly': |
|
525 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
526 | ||
527 | actual_value = Decimal(0.0) if row_shopfloor_periodically[1] is None \ |
|
528 | else row_shopfloor_periodically[1] |
|
529 | reporting[energy_category_id]['values_actual'].append(actual_value) |
|
530 | reporting[energy_category_id]['subtotal_actual'] += actual_value |
|
531 | reporting[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
|
532 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
|
533 | ||
534 | # calculate reporting period's energy savings |
|
535 | for i in range(len(reporting[energy_category_id]['values_baseline'])): |
|
536 | reporting[energy_category_id]['values_saving'].append( |
|
537 | reporting[energy_category_id]['values_baseline'][i] - |
|
538 | reporting[energy_category_id]['values_actual'][i]) |
|
539 | ||
540 | reporting[energy_category_id]['subtotal_saving'] = \ |
|
541 | reporting[energy_category_id]['subtotal_baseline'] - \ |
|
542 | reporting[energy_category_id]['subtotal_actual'] |
|
543 | reporting[energy_category_id]['subtotal_in_kgce_saving'] = \ |
|
544 | reporting[energy_category_id]['subtotal_in_kgce_baseline'] - \ |
|
545 | reporting[energy_category_id]['subtotal_in_kgce_actual'] |
|
546 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
|
547 | reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] - \ |
|
548 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] |
|
549 | ################################################################################################################ |
|
550 | # Step 8: query tariff data |
|
551 | ################################################################################################################ |
|
552 | parameters_data = dict() |
|
553 | parameters_data['names'] = list() |
|
554 | parameters_data['timestamps'] = list() |
|
555 | parameters_data['values'] = list() |
|
556 | if config.is_tariff_appended and energy_category_set is not None and len(energy_category_set) > 0 \ |
|
557 | and not is_quick_mode: |
|
558 | for energy_category_id in energy_category_set: |
|
559 | energy_category_tariff_dict = utilities.get_energy_category_tariffs(shopfloor['cost_center_id'], |
|
560 | energy_category_id, |
|
561 | reporting_start_datetime_utc, |
|
562 | reporting_end_datetime_utc) |
|
563 | tariff_timestamp_list = list() |
|
564 | tariff_value_list = list() |
|
565 | for k, v in energy_category_tariff_dict.items(): |
|
566 | # convert k from utc to local |
|
567 | k = k + timedelta(minutes=timezone_offset) |
|
568 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
|
569 | tariff_value_list.append(v) |
|
570 | ||
571 | parameters_data['names'].append(_('Tariff') + '-' + energy_category_dict[energy_category_id]['name']) |
|
572 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
573 | parameters_data['values'].append(tariff_value_list) |
|
574 | ||
575 | ################################################################################################################ |
|
576 | # Step 9: query associated sensors and points data |
|
577 | ################################################################################################################ |
|
578 | if not is_quick_mode: |
|
579 | for point in point_list: |
|
580 | point_values = [] |
|
581 | point_timestamps = [] |
|
582 | if point['object_type'] == 'ENERGY_VALUE': |
|
583 | query = (" SELECT utc_date_time, actual_value " |
|
584 | " FROM tbl_energy_value " |
|
585 | " WHERE point_id = %s " |
|
586 | " AND utc_date_time BETWEEN %s AND %s " |
|
587 | " ORDER BY utc_date_time ") |
|
588 | cursor_historical.execute(query, (point['id'], |
|
589 | reporting_start_datetime_utc, |
|
590 | reporting_end_datetime_utc)) |
|
591 | rows = cursor_historical.fetchall() |
|
592 | ||
593 | if rows is not None and len(rows) > 0: |
|
594 | for row in rows: |
|
595 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
596 | timedelta(minutes=timezone_offset) |
|
597 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
598 | point_timestamps.append(current_datetime) |
|
599 | point_values.append(row[1]) |
|
600 | elif point['object_type'] == 'ANALOG_VALUE': |
|
601 | query = (" SELECT utc_date_time, actual_value " |
|
602 | " FROM tbl_analog_value " |
|
603 | " WHERE point_id = %s " |
|
604 | " AND utc_date_time BETWEEN %s AND %s " |
|
605 | " ORDER BY utc_date_time ") |
|
606 | cursor_historical.execute(query, (point['id'], |
|
607 | reporting_start_datetime_utc, |
|
608 | reporting_end_datetime_utc)) |
|
609 | rows = cursor_historical.fetchall() |
|
610 | ||
611 | if rows is not None and len(rows) > 0: |
|
612 | for row in rows: |
|
613 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
614 | timedelta(minutes=timezone_offset) |
|
615 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
616 | point_timestamps.append(current_datetime) |
|
617 | point_values.append(row[1]) |
|
618 | elif point['object_type'] == 'DIGITAL_VALUE': |
|
619 | query = (" SELECT utc_date_time, actual_value " |
|
620 | " FROM tbl_digital_value " |
|
621 | " WHERE point_id = %s " |
|
622 | " AND utc_date_time BETWEEN %s AND %s " |
|
623 | " ORDER BY utc_date_time ") |
|
624 | cursor_historical.execute(query, (point['id'], |
|
625 | reporting_start_datetime_utc, |
|
626 | reporting_end_datetime_utc)) |
|
627 | rows = cursor_historical.fetchall() |
|
628 | ||
629 | if rows is not None and len(rows) > 0: |
|
630 | for row in rows: |
|
631 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
632 | timedelta(minutes=timezone_offset) |
|
633 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
634 | point_timestamps.append(current_datetime) |
|
635 | point_values.append(row[1]) |
|
636 | ||
637 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
|
638 | parameters_data['timestamps'].append(point_timestamps) |
|
639 | parameters_data['values'].append(point_values) |
|
640 | ||
641 | ################################################################################################################ |
|
642 | # Step 10: construct the report |
|
643 | ################################################################################################################ |
|
644 | if cursor_system: |
|
645 | cursor_system.close() |
|
646 | if cnx_system: |
|
647 | cnx_system.close() |
|
648 | ||
649 | if cursor_energy: |
|
650 | cursor_energy.close() |
|
651 | if cnx_energy: |
|
652 | cnx_energy.close() |
|
653 | ||
654 | if cursor_energy_baseline: |
|
655 | cursor_energy_baseline.close() |
|
656 | if cnx_energy_baseline: |
|
657 | cnx_energy_baseline.close() |
|
658 | ||
659 | if cursor_historical: |
|
660 | cursor_historical.close() |
|
661 | if cnx_historical: |
|
662 | cnx_historical.close() |
|
663 | ||
664 | result = dict() |
|
665 | ||
666 | result['shopfloor'] = dict() |
|
667 | result['shopfloor']['name'] = shopfloor['name'] |
|
668 | result['shopfloor']['area'] = shopfloor['area'] |
|
669 | ||
670 | result['base_period'] = dict() |
|
671 | result['base_period']['names'] = list() |
|
672 | result['base_period']['units'] = list() |
|
673 | result['base_period']['timestamps'] = list() |
|
674 | result['base_period']['values_saving'] = list() |
|
675 | result['base_period']['subtotals_saving'] = list() |
|
676 | result['base_period']['subtotals_in_kgce_saving'] = list() |
|
677 | result['base_period']['subtotals_in_kgco2e_saving'] = list() |
|
678 | result['base_period']['total_in_kgce_saving'] = Decimal(0.0) |
|
679 | result['base_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
|
680 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
681 | for energy_category_id in energy_category_set: |
|
682 | result['base_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
683 | result['base_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
684 | result['base_period']['timestamps'].append(base[energy_category_id]['timestamps']) |
|
685 | result['base_period']['values_saving'].append(base[energy_category_id]['values_saving']) |
|
686 | result['base_period']['subtotals_saving'].append(base[energy_category_id]['subtotal_saving']) |
|
687 | result['base_period']['subtotals_in_kgce_saving'].append( |
|
688 | base[energy_category_id]['subtotal_in_kgce_saving']) |
|
689 | result['base_period']['subtotals_in_kgco2e_saving'].append( |
|
690 | base[energy_category_id]['subtotal_in_kgco2e_saving']) |
|
691 | result['base_period']['total_in_kgce_saving'] += base[energy_category_id]['subtotal_in_kgce_saving'] |
|
692 | result['base_period']['total_in_kgco2e_saving'] += base[energy_category_id]['subtotal_in_kgco2e_saving'] |
|
693 | ||
694 | result['reporting_period'] = dict() |
|
695 | result['reporting_period']['names'] = list() |
|
696 | result['reporting_period']['energy_category_ids'] = list() |
|
697 | result['reporting_period']['units'] = list() |
|
698 | result['reporting_period']['timestamps'] = list() |
|
699 | result['reporting_period']['values_saving'] = list() |
|
700 | result['reporting_period']['rates_saving'] = list() |
|
701 | result['reporting_period']['subtotals_saving'] = list() |
|
702 | result['reporting_period']['subtotals_in_kgce_saving'] = list() |
|
703 | result['reporting_period']['subtotals_in_kgco2e_saving'] = list() |
|
704 | result['reporting_period']['subtotals_per_unit_area_saving'] = list() |
|
705 | result['reporting_period']['increment_rates_saving'] = list() |
|
706 | result['reporting_period']['total_in_kgce_saving'] = Decimal(0.0) |
|
707 | result['reporting_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
|
708 | result['reporting_period']['increment_rate_in_kgce_saving'] = Decimal(0.0) |
|
709 | result['reporting_period']['increment_rate_in_kgco2e_saving'] = Decimal(0.0) |
|
710 | ||
711 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
712 | for energy_category_id in energy_category_set: |
|
713 | result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
714 | result['reporting_period']['energy_category_ids'].append(energy_category_id) |
|
715 | result['reporting_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
716 | result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps']) |
|
717 | result['reporting_period']['values_saving'].append(reporting[energy_category_id]['values_saving']) |
|
718 | result['reporting_period']['subtotals_saving'].append(reporting[energy_category_id]['subtotal_saving']) |
|
719 | result['reporting_period']['subtotals_in_kgce_saving'].append( |
|
720 | reporting[energy_category_id]['subtotal_in_kgce_saving']) |
|
721 | result['reporting_period']['subtotals_in_kgco2e_saving'].append( |
|
722 | reporting[energy_category_id]['subtotal_in_kgco2e_saving']) |
|
723 | result['reporting_period']['subtotals_per_unit_area_saving'].append( |
|
724 | reporting[energy_category_id]['subtotal_saving'] / shopfloor['area'] |
|
725 | if shopfloor['area'] > Decimal(0.0) else None) |
|
726 | result['reporting_period']['increment_rates_saving'].append( |
|
727 | (reporting[energy_category_id]['subtotal_saving'] - base[energy_category_id]['subtotal_saving']) / |
|
728 | base[energy_category_id]['subtotal_saving'] |
|
729 | if base[energy_category_id]['subtotal_saving'] != Decimal(0.0) else None) |
|
730 | result['reporting_period']['total_in_kgce_saving'] += \ |
|
731 | reporting[energy_category_id]['subtotal_in_kgce_saving'] |
|
732 | result['reporting_period']['total_in_kgco2e_saving'] += \ |
|
733 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] |
|
734 | ||
735 | rate = list() |
|
736 | for index, value in enumerate(reporting[energy_category_id]['values_saving']): |
|
737 | if index < len(base[energy_category_id]['values_saving']) \ |
|
738 | and base[energy_category_id]['values_saving'][index] != 0 and value != 0: |
|
739 | rate.append((value - base[energy_category_id]['values_saving'][index]) |
|
740 | / base[energy_category_id]['values_saving'][index]) |
|
741 | else: |
|
742 | rate.append(None) |
|
743 | result['reporting_period']['rates_saving'].append(rate) |
|
744 | ||
745 | result['reporting_period']['total_in_kgco2e_per_unit_area_saving'] = \ |
|
746 | result['reporting_period']['total_in_kgce_saving'] / shopfloor['area'] \ |
|
747 | if shopfloor['area'] > 0.0 else None |
|
748 | ||
749 | result['reporting_period']['increment_rate_in_kgce_saving'] = \ |
|
750 | (result['reporting_period']['total_in_kgce_saving'] - result['base_period']['total_in_kgce_saving']) / \ |
|
751 | result['base_period']['total_in_kgce_saving'] \ |
|
752 | if result['base_period']['total_in_kgce_saving'] != Decimal(0.0) else None |
|
753 | ||
754 | result['reporting_period']['total_in_kgce_per_unit_area_saving'] = \ |
|
755 | result['reporting_period']['total_in_kgco2e_saving'] / shopfloor['area'] \ |
|
756 | if shopfloor['area'] > Decimal(0.0) else None |
|
757 | ||
758 | result['reporting_period']['increment_rate_in_kgco2e_saving'] = \ |
|
759 | (result['reporting_period']['total_in_kgco2e_saving'] - result['base_period']['total_in_kgco2e_saving']) / \ |
|
760 | result['base_period']['total_in_kgco2e_saving'] \ |
|
761 | if result['base_period']['total_in_kgco2e_saving'] != Decimal(0.0) else None |
|
762 | ||
763 | result['parameters'] = { |
|
764 | "names": parameters_data['names'], |
|
765 | "timestamps": parameters_data['timestamps'], |
|
766 | "values": parameters_data['values'] |
|
767 | } |
|
768 | ||
769 | result['excel_bytes_base64'] = None |
|
770 | if not is_quick_mode: |
|
771 | result['excel_bytes_base64'] = excelexporters.shopfloorsaving.export(result, |
|
772 | shopfloor['name'], |
|
773 | base_period_start_datetime_local, |
|
774 | base_period_end_datetime_local, |
|
775 | reporting_period_start_datetime_local, |
|
776 | reporting_period_end_datetime_local, |
|
777 | period_type, |
|
778 | language) |
|
779 | ||
780 | resp.text = json.dumps(result) |
|
781 |
@@ 13-780 (lines=768) @@ | ||
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 shopfloor |
|
27 | # Step 3: query energy categories |
|
28 | # Step 4: query associated sensors |
|
29 | # Step 5: query associated points |
|
30 | # Step 6: query base period energy saving |
|
31 | # Step 7: query reporting period energy saving |
|
32 | # Step 8: query tariff data |
|
33 | # Step 9: query associated sensors and 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 | shopfloor_id = req.params.get('shopfloorid') |
|
46 | shopfloor_uuid = req.params.get('shopflooruuid') |
|
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 shopfloor_id is None and shopfloor_uuid is None: |
|
59 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
60 | title='API.BAD_REQUEST', |
|
61 | description='API.INVALID_SHOPFLOOR_ID') |
|
62 | ||
63 | if shopfloor_id is not None: |
|
64 | shopfloor_id = str.strip(shopfloor_id) |
|
65 | if not shopfloor_id.isdigit() or int(shopfloor_id) <= 0: |
|
66 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
67 | title='API.BAD_REQUEST', |
|
68 | description='API.INVALID_SHOPFLOOR_ID') |
|
69 | ||
70 | if shopfloor_uuid is not None: |
|
71 | 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) |
|
72 | match = regex.match(str.strip(shopfloor_uuid)) |
|
73 | if not bool(match): |
|
74 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
75 | title='API.BAD_REQUEST', |
|
76 | description='API.INVALID_SHOPFLOOR_UUID') |
|
77 | ||
78 | if period_type is None: |
|
79 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
80 | description='API.INVALID_PERIOD_TYPE') |
|
81 | else: |
|
82 | period_type = str.strip(period_type) |
|
83 | if period_type not in ['hourly', 'daily', 'weekly', 'monthly', 'yearly']: |
|
84 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
85 | description='API.INVALID_PERIOD_TYPE') |
|
86 | ||
87 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
|
88 | if config.utc_offset[0] == '-': |
|
89 | timezone_offset = -timezone_offset |
|
90 | ||
91 | base_start_datetime_utc = None |
|
92 | if base_period_start_datetime_local is not None and len(str.strip(base_period_start_datetime_local)) > 0: |
|
93 | base_period_start_datetime_local = str.strip(base_period_start_datetime_local) |
|
94 | try: |
|
95 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
96 | except ValueError: |
|
97 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
98 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
|
99 | base_start_datetime_utc = \ |
|
100 | base_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
101 | # nomalize the start datetime |
|
102 | if config.minutes_to_count == 30 and base_start_datetime_utc.minute >= 30: |
|
103 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
|
104 | else: |
|
105 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
|
106 | ||
107 | base_end_datetime_utc = None |
|
108 | if base_period_end_datetime_local is not None and len(str.strip(base_period_end_datetime_local)) > 0: |
|
109 | base_period_end_datetime_local = str.strip(base_period_end_datetime_local) |
|
110 | try: |
|
111 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
112 | except ValueError: |
|
113 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
114 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
|
115 | base_end_datetime_utc = \ |
|
116 | base_end_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
117 | ||
118 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
|
119 | base_start_datetime_utc >= base_end_datetime_utc: |
|
120 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
121 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
|
122 | ||
123 | if reporting_period_start_datetime_local is None: |
|
124 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
125 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
126 | else: |
|
127 | reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) |
|
128 | try: |
|
129 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, |
|
130 | '%Y-%m-%dT%H:%M:%S') |
|
131 | except ValueError: |
|
132 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
133 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
134 | reporting_start_datetime_utc = \ |
|
135 | reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
136 | # nomalize the start datetime |
|
137 | if config.minutes_to_count == 30 and reporting_start_datetime_utc.minute >= 30: |
|
138 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
|
139 | else: |
|
140 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
|
141 | ||
142 | if reporting_period_end_datetime_local is None: |
|
143 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
144 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
145 | else: |
|
146 | reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) |
|
147 | try: |
|
148 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, |
|
149 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
150 | timedelta(minutes=timezone_offset) |
|
151 | except ValueError: |
|
152 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
153 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
154 | ||
155 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
|
156 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
157 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
|
158 | ||
159 | # if turn quick mode on, do not return parameters data and excel file |
|
160 | is_quick_mode = False |
|
161 | if quick_mode is not None and \ |
|
162 | len(str.strip(quick_mode)) > 0 and \ |
|
163 | str.lower(str.strip(quick_mode)) in ('true', 't', 'on', 'yes', 'y'): |
|
164 | is_quick_mode = True |
|
165 | ||
166 | trans = utilities.get_translation(language) |
|
167 | trans.install() |
|
168 | _ = trans.gettext |
|
169 | ||
170 | ################################################################################################################ |
|
171 | # Step 2: query the shopfloor |
|
172 | ################################################################################################################ |
|
173 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
|
174 | cursor_system = cnx_system.cursor() |
|
175 | ||
176 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
|
177 | cursor_energy = cnx_energy.cursor() |
|
178 | ||
179 | cnx_energy_plan = mysql.connector.connect(**config.myems_energy_plan_db) |
|
180 | cursor_energy_plan = cnx_energy_plan.cursor() |
|
181 | ||
182 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
|
183 | cursor_historical = cnx_historical.cursor() |
|
184 | ||
185 | if shopfloor_id is not None: |
|
186 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
187 | " FROM tbl_shopfloors " |
|
188 | " WHERE id = %s ", (shopfloor_id,)) |
|
189 | row_shopfloor = cursor_system.fetchone() |
|
190 | elif shopfloor_uuid is not None: |
|
191 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
192 | " FROM tbl_shopfloors " |
|
193 | " WHERE uuid = %s ", (shopfloor_uuid,)) |
|
194 | row_shopfloor = cursor_system.fetchone() |
|
195 | ||
196 | if row_shopfloor is None: |
|
197 | if cursor_system: |
|
198 | cursor_system.close() |
|
199 | if cnx_system: |
|
200 | cnx_system.close() |
|
201 | ||
202 | if cursor_energy: |
|
203 | cursor_energy.close() |
|
204 | if cnx_energy: |
|
205 | cnx_energy.close() |
|
206 | ||
207 | if cursor_energy_plan: |
|
208 | cursor_energy_plan.close() |
|
209 | if cnx_energy_plan: |
|
210 | cnx_energy_plan.close() |
|
211 | ||
212 | if cursor_historical: |
|
213 | cursor_historical.close() |
|
214 | if cnx_historical: |
|
215 | cnx_historical.close() |
|
216 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', description='API.SHOPFLOOR_NOT_FOUND') |
|
217 | ||
218 | shopfloor = dict() |
|
219 | shopfloor['id'] = row_shopfloor[0] |
|
220 | shopfloor['name'] = row_shopfloor[1] |
|
221 | shopfloor['area'] = row_shopfloor[2] |
|
222 | shopfloor['cost_center_id'] = row_shopfloor[3] |
|
223 | ||
224 | ################################################################################################################ |
|
225 | # Step 3: query energy categories |
|
226 | ################################################################################################################ |
|
227 | energy_category_set = set() |
|
228 | # query energy categories in base period |
|
229 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
230 | " FROM tbl_shopfloor_input_category_hourly " |
|
231 | " WHERE shopfloor_id = %s " |
|
232 | " AND start_datetime_utc >= %s " |
|
233 | " AND start_datetime_utc < %s ", |
|
234 | (shopfloor['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
235 | rows_energy_categories = cursor_energy.fetchall() |
|
236 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
|
237 | for row_energy_category in rows_energy_categories: |
|
238 | energy_category_set.add(row_energy_category[0]) |
|
239 | ||
240 | # query energy categories in reporting period |
|
241 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
242 | " FROM tbl_shopfloor_input_category_hourly " |
|
243 | " WHERE shopfloor_id = %s " |
|
244 | " AND start_datetime_utc >= %s " |
|
245 | " AND start_datetime_utc < %s ", |
|
246 | (shopfloor['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
247 | rows_energy_categories = cursor_energy.fetchall() |
|
248 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
|
249 | for row_energy_category in rows_energy_categories: |
|
250 | energy_category_set.add(row_energy_category[0]) |
|
251 | ||
252 | # query all energy categories in base period and reporting period |
|
253 | cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e " |
|
254 | " FROM tbl_energy_categories " |
|
255 | " ORDER BY id ", ) |
|
256 | rows_energy_categories = cursor_system.fetchall() |
|
257 | if rows_energy_categories is None or len(rows_energy_categories) == 0: |
|
258 | if cursor_system: |
|
259 | cursor_system.close() |
|
260 | if cnx_system: |
|
261 | cnx_system.close() |
|
262 | ||
263 | if cursor_energy: |
|
264 | cursor_energy.close() |
|
265 | if cnx_energy: |
|
266 | cnx_energy.close() |
|
267 | ||
268 | if cursor_energy_plan: |
|
269 | cursor_energy_plan.close() |
|
270 | if cnx_energy_plan: |
|
271 | cnx_energy_plan.close() |
|
272 | ||
273 | if cursor_historical: |
|
274 | cursor_historical.close() |
|
275 | if cnx_historical: |
|
276 | cnx_historical.close() |
|
277 | raise falcon.HTTPError(status=falcon.HTTP_404, |
|
278 | title='API.NOT_FOUND', |
|
279 | description='API.ENERGY_CATEGORY_NOT_FOUND') |
|
280 | energy_category_dict = dict() |
|
281 | for row_energy_category in rows_energy_categories: |
|
282 | if row_energy_category[0] in energy_category_set: |
|
283 | energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1], |
|
284 | "unit_of_measure": row_energy_category[2], |
|
285 | "kgce": row_energy_category[3], |
|
286 | "kgco2e": row_energy_category[4]} |
|
287 | ||
288 | ################################################################################################################ |
|
289 | # Step 4: query associated sensors |
|
290 | ################################################################################################################ |
|
291 | point_list = list() |
|
292 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
293 | " FROM tbl_shopfloors st, tbl_sensors se, tbl_shopfloors_sensors ss, " |
|
294 | " tbl_points p, tbl_sensors_points sp " |
|
295 | " WHERE st.id = %s AND st.id = ss.shopfloor_id AND ss.sensor_id = se.id " |
|
296 | " AND se.id = sp.sensor_id AND sp.point_id = p.id " |
|
297 | " ORDER BY p.id ", (shopfloor['id'],)) |
|
298 | rows_points = cursor_system.fetchall() |
|
299 | if rows_points is not None and len(rows_points) > 0: |
|
300 | for row in rows_points: |
|
301 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
302 | ||
303 | ################################################################################################################ |
|
304 | # Step 5: query associated points |
|
305 | ################################################################################################################ |
|
306 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
307 | " FROM tbl_shopfloors s, tbl_shopfloors_points sp, tbl_points p " |
|
308 | " WHERE s.id = %s AND s.id = sp.shopfloor_id AND sp.point_id = p.id " |
|
309 | " ORDER BY p.id ", (shopfloor['id'],)) |
|
310 | rows_points = cursor_system.fetchall() |
|
311 | if rows_points is not None and len(rows_points) > 0: |
|
312 | for row in rows_points: |
|
313 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
314 | ||
315 | ################################################################################################################ |
|
316 | # Step 6: query base period energy saving |
|
317 | ################################################################################################################ |
|
318 | base = dict() |
|
319 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
320 | for energy_category_id in energy_category_set: |
|
321 | kgce = energy_category_dict[energy_category_id]['kgce'] |
|
322 | kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
|
323 | ||
324 | base[energy_category_id] = dict() |
|
325 | base[energy_category_id]['timestamps'] = list() |
|
326 | base[energy_category_id]['values_plan'] = list() |
|
327 | base[energy_category_id]['values_actual'] = list() |
|
328 | base[energy_category_id]['values_saving'] = list() |
|
329 | base[energy_category_id]['subtotal_plan'] = Decimal(0.0) |
|
330 | base[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
|
331 | base[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
|
332 | base[energy_category_id]['subtotal_in_kgce_plan'] = Decimal(0.0) |
|
333 | base[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
|
334 | base[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
|
335 | base[energy_category_id]['subtotal_in_kgco2e_plan'] = Decimal(0.0) |
|
336 | base[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
|
337 | base[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
|
338 | # query base period's energy plan |
|
339 | cursor_energy_plan.execute(" SELECT start_datetime_utc, actual_value " |
|
340 | " FROM tbl_shopfloor_input_category_hourly " |
|
341 | " WHERE shopfloor_id = %s " |
|
342 | " AND energy_category_id = %s " |
|
343 | " AND start_datetime_utc >= %s " |
|
344 | " AND start_datetime_utc < %s " |
|
345 | " ORDER BY start_datetime_utc ", |
|
346 | (shopfloor['id'], |
|
347 | energy_category_id, |
|
348 | base_start_datetime_utc, |
|
349 | base_end_datetime_utc)) |
|
350 | rows_shopfloor_hourly = cursor_energy_plan.fetchall() |
|
351 | ||
352 | rows_shopfloor_periodically = utilities.aggregate_hourly_data_by_period(rows_shopfloor_hourly, |
|
353 | base_start_datetime_utc, |
|
354 | base_end_datetime_utc, |
|
355 | period_type) |
|
356 | for row_shopfloor_periodically in rows_shopfloor_periodically: |
|
357 | current_datetime_local = row_shopfloor_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
358 | timedelta(minutes=timezone_offset) |
|
359 | if period_type == 'hourly': |
|
360 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
361 | elif period_type == 'daily': |
|
362 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
363 | elif period_type == 'weekly': |
|
364 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
365 | elif period_type == 'monthly': |
|
366 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
367 | elif period_type == 'yearly': |
|
368 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
369 | ||
370 | plan_value = Decimal(0.0) if row_shopfloor_periodically[1] is None \ |
|
371 | else row_shopfloor_periodically[1] |
|
372 | base[energy_category_id]['timestamps'].append(current_datetime) |
|
373 | base[energy_category_id]['values_plan'].append(plan_value) |
|
374 | base[energy_category_id]['subtotal_plan'] += plan_value |
|
375 | base[energy_category_id]['subtotal_in_kgce_plan'] += plan_value * kgce |
|
376 | base[energy_category_id]['subtotal_in_kgco2e_plan'] += plan_value * kgco2e |
|
377 | ||
378 | # query base period's energy actual |
|
379 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
380 | " FROM tbl_shopfloor_input_category_hourly " |
|
381 | " WHERE shopfloor_id = %s " |
|
382 | " AND energy_category_id = %s " |
|
383 | " AND start_datetime_utc >= %s " |
|
384 | " AND start_datetime_utc < %s " |
|
385 | " ORDER BY start_datetime_utc ", |
|
386 | (shopfloor['id'], |
|
387 | energy_category_id, |
|
388 | base_start_datetime_utc, |
|
389 | base_end_datetime_utc)) |
|
390 | rows_shopfloor_hourly = cursor_energy.fetchall() |
|
391 | ||
392 | rows_shopfloor_periodically = utilities.aggregate_hourly_data_by_period(rows_shopfloor_hourly, |
|
393 | base_start_datetime_utc, |
|
394 | base_end_datetime_utc, |
|
395 | period_type) |
|
396 | for row_shopfloor_periodically in rows_shopfloor_periodically: |
|
397 | current_datetime_local = row_shopfloor_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
398 | timedelta(minutes=timezone_offset) |
|
399 | if period_type == 'hourly': |
|
400 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
401 | elif period_type == 'daily': |
|
402 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
403 | elif period_type == 'weekly': |
|
404 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
405 | elif period_type == 'monthly': |
|
406 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
407 | elif period_type == 'yearly': |
|
408 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
409 | ||
410 | actual_value = Decimal(0.0) if row_shopfloor_periodically[1] is None \ |
|
411 | else row_shopfloor_periodically[1] |
|
412 | base[energy_category_id]['values_actual'].append(actual_value) |
|
413 | base[energy_category_id]['subtotal_actual'] += actual_value |
|
414 | base[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
|
415 | base[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
|
416 | ||
417 | # calculate base period's energy savings |
|
418 | for i in range(len(base[energy_category_id]['values_plan'])): |
|
419 | base[energy_category_id]['values_saving'].append( |
|
420 | base[energy_category_id]['values_plan'][i] - |
|
421 | base[energy_category_id]['values_actual'][i]) |
|
422 | ||
423 | base[energy_category_id]['subtotal_saving'] = \ |
|
424 | base[energy_category_id]['subtotal_plan'] - \ |
|
425 | base[energy_category_id]['subtotal_actual'] |
|
426 | base[energy_category_id]['subtotal_in_kgce_saving'] = \ |
|
427 | base[energy_category_id]['subtotal_in_kgce_plan'] - \ |
|
428 | base[energy_category_id]['subtotal_in_kgce_actual'] |
|
429 | base[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
|
430 | base[energy_category_id]['subtotal_in_kgco2e_plan'] - \ |
|
431 | base[energy_category_id]['subtotal_in_kgco2e_actual'] |
|
432 | ################################################################################################################ |
|
433 | # Step 7: query reporting period energy saving |
|
434 | ################################################################################################################ |
|
435 | reporting = dict() |
|
436 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
437 | for energy_category_id in energy_category_set: |
|
438 | kgce = energy_category_dict[energy_category_id]['kgce'] |
|
439 | kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
|
440 | ||
441 | reporting[energy_category_id] = dict() |
|
442 | reporting[energy_category_id]['timestamps'] = list() |
|
443 | reporting[energy_category_id]['values_plan'] = list() |
|
444 | reporting[energy_category_id]['values_actual'] = list() |
|
445 | reporting[energy_category_id]['values_saving'] = list() |
|
446 | reporting[energy_category_id]['subtotal_plan'] = Decimal(0.0) |
|
447 | reporting[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
|
448 | reporting[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
|
449 | reporting[energy_category_id]['subtotal_in_kgce_plan'] = Decimal(0.0) |
|
450 | reporting[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
|
451 | reporting[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
|
452 | reporting[energy_category_id]['subtotal_in_kgco2e_plan'] = Decimal(0.0) |
|
453 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
|
454 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
|
455 | # query reporting period's energy plan |
|
456 | cursor_energy_plan.execute(" SELECT start_datetime_utc, actual_value " |
|
457 | " FROM tbl_shopfloor_input_category_hourly " |
|
458 | " WHERE shopfloor_id = %s " |
|
459 | " AND energy_category_id = %s " |
|
460 | " AND start_datetime_utc >= %s " |
|
461 | " AND start_datetime_utc < %s " |
|
462 | " ORDER BY start_datetime_utc ", |
|
463 | (shopfloor['id'], |
|
464 | energy_category_id, |
|
465 | reporting_start_datetime_utc, |
|
466 | reporting_end_datetime_utc)) |
|
467 | rows_shopfloor_hourly = cursor_energy_plan.fetchall() |
|
468 | ||
469 | rows_shopfloor_periodically = utilities.aggregate_hourly_data_by_period(rows_shopfloor_hourly, |
|
470 | reporting_start_datetime_utc, |
|
471 | reporting_end_datetime_utc, |
|
472 | period_type) |
|
473 | for row_shopfloor_periodically in rows_shopfloor_periodically: |
|
474 | current_datetime_local = row_shopfloor_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
475 | timedelta(minutes=timezone_offset) |
|
476 | if period_type == 'hourly': |
|
477 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
478 | elif period_type == 'daily': |
|
479 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
480 | elif period_type == 'weekly': |
|
481 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
482 | elif period_type == 'monthly': |
|
483 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
484 | elif period_type == 'yearly': |
|
485 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
486 | ||
487 | plan_value = Decimal(0.0) if row_shopfloor_periodically[1] is None \ |
|
488 | else row_shopfloor_periodically[1] |
|
489 | reporting[energy_category_id]['timestamps'].append(current_datetime) |
|
490 | reporting[energy_category_id]['values_plan'].append(plan_value) |
|
491 | reporting[energy_category_id]['subtotal_plan'] += plan_value |
|
492 | reporting[energy_category_id]['subtotal_in_kgce_plan'] += plan_value * kgce |
|
493 | reporting[energy_category_id]['subtotal_in_kgco2e_plan'] += plan_value * kgco2e |
|
494 | ||
495 | # query reporting period's energy actual |
|
496 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
497 | " FROM tbl_shopfloor_input_category_hourly " |
|
498 | " WHERE shopfloor_id = %s " |
|
499 | " AND energy_category_id = %s " |
|
500 | " AND start_datetime_utc >= %s " |
|
501 | " AND start_datetime_utc < %s " |
|
502 | " ORDER BY start_datetime_utc ", |
|
503 | (shopfloor['id'], |
|
504 | energy_category_id, |
|
505 | reporting_start_datetime_utc, |
|
506 | reporting_end_datetime_utc)) |
|
507 | rows_shopfloor_hourly = cursor_energy.fetchall() |
|
508 | ||
509 | rows_shopfloor_periodically = utilities.aggregate_hourly_data_by_period(rows_shopfloor_hourly, |
|
510 | reporting_start_datetime_utc, |
|
511 | reporting_end_datetime_utc, |
|
512 | period_type) |
|
513 | for row_shopfloor_periodically in rows_shopfloor_periodically: |
|
514 | current_datetime_local = row_shopfloor_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
515 | timedelta(minutes=timezone_offset) |
|
516 | if period_type == 'hourly': |
|
517 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
518 | elif period_type == 'daily': |
|
519 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
520 | elif period_type == 'weekly': |
|
521 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
522 | elif period_type == 'monthly': |
|
523 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
524 | elif period_type == 'yearly': |
|
525 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
526 | ||
527 | actual_value = Decimal(0.0) if row_shopfloor_periodically[1] is None \ |
|
528 | else row_shopfloor_periodically[1] |
|
529 | reporting[energy_category_id]['values_actual'].append(actual_value) |
|
530 | reporting[energy_category_id]['subtotal_actual'] += actual_value |
|
531 | reporting[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
|
532 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
|
533 | ||
534 | # calculate reporting period's energy savings |
|
535 | for i in range(len(reporting[energy_category_id]['values_plan'])): |
|
536 | reporting[energy_category_id]['values_saving'].append( |
|
537 | reporting[energy_category_id]['values_plan'][i] - |
|
538 | reporting[energy_category_id]['values_actual'][i]) |
|
539 | ||
540 | reporting[energy_category_id]['subtotal_saving'] = \ |
|
541 | reporting[energy_category_id]['subtotal_plan'] - \ |
|
542 | reporting[energy_category_id]['subtotal_actual'] |
|
543 | reporting[energy_category_id]['subtotal_in_kgce_saving'] = \ |
|
544 | reporting[energy_category_id]['subtotal_in_kgce_plan'] - \ |
|
545 | reporting[energy_category_id]['subtotal_in_kgce_actual'] |
|
546 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
|
547 | reporting[energy_category_id]['subtotal_in_kgco2e_plan'] - \ |
|
548 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] |
|
549 | ################################################################################################################ |
|
550 | # Step 8: query tariff data |
|
551 | ################################################################################################################ |
|
552 | parameters_data = dict() |
|
553 | parameters_data['names'] = list() |
|
554 | parameters_data['timestamps'] = list() |
|
555 | parameters_data['values'] = list() |
|
556 | if config.is_tariff_appended and energy_category_set is not None and len(energy_category_set) > 0 \ |
|
557 | and not is_quick_mode: |
|
558 | for energy_category_id in energy_category_set: |
|
559 | energy_category_tariff_dict = utilities.get_energy_category_tariffs(shopfloor['cost_center_id'], |
|
560 | energy_category_id, |
|
561 | reporting_start_datetime_utc, |
|
562 | reporting_end_datetime_utc) |
|
563 | tariff_timestamp_list = list() |
|
564 | tariff_value_list = list() |
|
565 | for k, v in energy_category_tariff_dict.items(): |
|
566 | # convert k from utc to local |
|
567 | k = k + timedelta(minutes=timezone_offset) |
|
568 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
|
569 | tariff_value_list.append(v) |
|
570 | ||
571 | parameters_data['names'].append(_('Tariff') + '-' + energy_category_dict[energy_category_id]['name']) |
|
572 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
573 | parameters_data['values'].append(tariff_value_list) |
|
574 | ||
575 | ################################################################################################################ |
|
576 | # Step 9: query associated sensors and points data |
|
577 | ################################################################################################################ |
|
578 | if not is_quick_mode: |
|
579 | for point in point_list: |
|
580 | point_values = [] |
|
581 | point_timestamps = [] |
|
582 | if point['object_type'] == 'ENERGY_VALUE': |
|
583 | query = (" SELECT utc_date_time, actual_value " |
|
584 | " FROM tbl_energy_value " |
|
585 | " WHERE point_id = %s " |
|
586 | " AND utc_date_time BETWEEN %s AND %s " |
|
587 | " ORDER BY utc_date_time ") |
|
588 | cursor_historical.execute(query, (point['id'], |
|
589 | reporting_start_datetime_utc, |
|
590 | reporting_end_datetime_utc)) |
|
591 | rows = cursor_historical.fetchall() |
|
592 | ||
593 | if rows is not None and len(rows) > 0: |
|
594 | for row in rows: |
|
595 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
596 | timedelta(minutes=timezone_offset) |
|
597 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
598 | point_timestamps.append(current_datetime) |
|
599 | point_values.append(row[1]) |
|
600 | elif point['object_type'] == 'ANALOG_VALUE': |
|
601 | query = (" SELECT utc_date_time, actual_value " |
|
602 | " FROM tbl_analog_value " |
|
603 | " WHERE point_id = %s " |
|
604 | " AND utc_date_time BETWEEN %s AND %s " |
|
605 | " ORDER BY utc_date_time ") |
|
606 | cursor_historical.execute(query, (point['id'], |
|
607 | reporting_start_datetime_utc, |
|
608 | reporting_end_datetime_utc)) |
|
609 | rows = cursor_historical.fetchall() |
|
610 | ||
611 | if rows is not None and len(rows) > 0: |
|
612 | for row in rows: |
|
613 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
614 | timedelta(minutes=timezone_offset) |
|
615 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
616 | point_timestamps.append(current_datetime) |
|
617 | point_values.append(row[1]) |
|
618 | elif point['object_type'] == 'DIGITAL_VALUE': |
|
619 | query = (" SELECT utc_date_time, actual_value " |
|
620 | " FROM tbl_digital_value " |
|
621 | " WHERE point_id = %s " |
|
622 | " AND utc_date_time BETWEEN %s AND %s " |
|
623 | " ORDER BY utc_date_time ") |
|
624 | cursor_historical.execute(query, (point['id'], |
|
625 | reporting_start_datetime_utc, |
|
626 | reporting_end_datetime_utc)) |
|
627 | rows = cursor_historical.fetchall() |
|
628 | ||
629 | if rows is not None and len(rows) > 0: |
|
630 | for row in rows: |
|
631 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
632 | timedelta(minutes=timezone_offset) |
|
633 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
634 | point_timestamps.append(current_datetime) |
|
635 | point_values.append(row[1]) |
|
636 | ||
637 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
|
638 | parameters_data['timestamps'].append(point_timestamps) |
|
639 | parameters_data['values'].append(point_values) |
|
640 | ||
641 | ################################################################################################################ |
|
642 | # Step 10: construct the report |
|
643 | ################################################################################################################ |
|
644 | if cursor_system: |
|
645 | cursor_system.close() |
|
646 | if cnx_system: |
|
647 | cnx_system.close() |
|
648 | ||
649 | if cursor_energy: |
|
650 | cursor_energy.close() |
|
651 | if cnx_energy: |
|
652 | cnx_energy.close() |
|
653 | ||
654 | if cursor_energy_plan: |
|
655 | cursor_energy_plan.close() |
|
656 | if cnx_energy_plan: |
|
657 | cnx_energy_plan.close() |
|
658 | ||
659 | if cursor_historical: |
|
660 | cursor_historical.close() |
|
661 | if cnx_historical: |
|
662 | cnx_historical.close() |
|
663 | ||
664 | result = dict() |
|
665 | ||
666 | result['shopfloor'] = dict() |
|
667 | result['shopfloor']['name'] = shopfloor['name'] |
|
668 | result['shopfloor']['area'] = shopfloor['area'] |
|
669 | ||
670 | result['base_period'] = dict() |
|
671 | result['base_period']['names'] = list() |
|
672 | result['base_period']['units'] = list() |
|
673 | result['base_period']['timestamps'] = list() |
|
674 | result['base_period']['values_saving'] = list() |
|
675 | result['base_period']['subtotals_saving'] = list() |
|
676 | result['base_period']['subtotals_in_kgce_saving'] = list() |
|
677 | result['base_period']['subtotals_in_kgco2e_saving'] = list() |
|
678 | result['base_period']['total_in_kgce_saving'] = Decimal(0.0) |
|
679 | result['base_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
|
680 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
681 | for energy_category_id in energy_category_set: |
|
682 | result['base_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
683 | result['base_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
684 | result['base_period']['timestamps'].append(base[energy_category_id]['timestamps']) |
|
685 | result['base_period']['values_saving'].append(base[energy_category_id]['values_saving']) |
|
686 | result['base_period']['subtotals_saving'].append(base[energy_category_id]['subtotal_saving']) |
|
687 | result['base_period']['subtotals_in_kgce_saving'].append( |
|
688 | base[energy_category_id]['subtotal_in_kgce_saving']) |
|
689 | result['base_period']['subtotals_in_kgco2e_saving'].append( |
|
690 | base[energy_category_id]['subtotal_in_kgco2e_saving']) |
|
691 | result['base_period']['total_in_kgce_saving'] += base[energy_category_id]['subtotal_in_kgce_saving'] |
|
692 | result['base_period']['total_in_kgco2e_saving'] += base[energy_category_id]['subtotal_in_kgco2e_saving'] |
|
693 | ||
694 | result['reporting_period'] = dict() |
|
695 | result['reporting_period']['names'] = list() |
|
696 | result['reporting_period']['energy_category_ids'] = list() |
|
697 | result['reporting_period']['units'] = list() |
|
698 | result['reporting_period']['timestamps'] = list() |
|
699 | result['reporting_period']['values_saving'] = list() |
|
700 | result['reporting_period']['rates_saving'] = list() |
|
701 | result['reporting_period']['subtotals_saving'] = list() |
|
702 | result['reporting_period']['subtotals_in_kgce_saving'] = list() |
|
703 | result['reporting_period']['subtotals_in_kgco2e_saving'] = list() |
|
704 | result['reporting_period']['subtotals_per_unit_area_saving'] = list() |
|
705 | result['reporting_period']['increment_rates_saving'] = list() |
|
706 | result['reporting_period']['total_in_kgce_saving'] = Decimal(0.0) |
|
707 | result['reporting_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
|
708 | result['reporting_period']['increment_rate_in_kgce_saving'] = Decimal(0.0) |
|
709 | result['reporting_period']['increment_rate_in_kgco2e_saving'] = Decimal(0.0) |
|
710 | ||
711 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
712 | for energy_category_id in energy_category_set: |
|
713 | result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
714 | result['reporting_period']['energy_category_ids'].append(energy_category_id) |
|
715 | result['reporting_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
716 | result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps']) |
|
717 | result['reporting_period']['values_saving'].append(reporting[energy_category_id]['values_saving']) |
|
718 | result['reporting_period']['subtotals_saving'].append(reporting[energy_category_id]['subtotal_saving']) |
|
719 | result['reporting_period']['subtotals_in_kgce_saving'].append( |
|
720 | reporting[energy_category_id]['subtotal_in_kgce_saving']) |
|
721 | result['reporting_period']['subtotals_in_kgco2e_saving'].append( |
|
722 | reporting[energy_category_id]['subtotal_in_kgco2e_saving']) |
|
723 | result['reporting_period']['subtotals_per_unit_area_saving'].append( |
|
724 | reporting[energy_category_id]['subtotal_saving'] / shopfloor['area'] |
|
725 | if shopfloor['area'] > Decimal(0.0) else None) |
|
726 | result['reporting_period']['increment_rates_saving'].append( |
|
727 | (reporting[energy_category_id]['subtotal_saving'] - base[energy_category_id]['subtotal_saving']) / |
|
728 | base[energy_category_id]['subtotal_saving'] |
|
729 | if base[energy_category_id]['subtotal_saving'] != Decimal(0.0) else None) |
|
730 | result['reporting_period']['total_in_kgce_saving'] += \ |
|
731 | reporting[energy_category_id]['subtotal_in_kgce_saving'] |
|
732 | result['reporting_period']['total_in_kgco2e_saving'] += \ |
|
733 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] |
|
734 | ||
735 | rate = list() |
|
736 | for index, value in enumerate(reporting[energy_category_id]['values_saving']): |
|
737 | if index < len(base[energy_category_id]['values_saving']) \ |
|
738 | and base[energy_category_id]['values_saving'][index] != 0 and value != 0: |
|
739 | rate.append((value - base[energy_category_id]['values_saving'][index]) |
|
740 | / base[energy_category_id]['values_saving'][index]) |
|
741 | else: |
|
742 | rate.append(None) |
|
743 | result['reporting_period']['rates_saving'].append(rate) |
|
744 | ||
745 | result['reporting_period']['total_in_kgco2e_per_unit_area_saving'] = \ |
|
746 | result['reporting_period']['total_in_kgce_saving'] / shopfloor['area'] \ |
|
747 | if shopfloor['area'] > 0.0 else None |
|
748 | ||
749 | result['reporting_period']['increment_rate_in_kgce_saving'] = \ |
|
750 | (result['reporting_period']['total_in_kgce_saving'] - result['base_period']['total_in_kgce_saving']) / \ |
|
751 | result['base_period']['total_in_kgce_saving'] \ |
|
752 | if result['base_period']['total_in_kgce_saving'] != Decimal(0.0) else None |
|
753 | ||
754 | result['reporting_period']['total_in_kgce_per_unit_area_saving'] = \ |
|
755 | result['reporting_period']['total_in_kgco2e_saving'] / shopfloor['area'] \ |
|
756 | if shopfloor['area'] > Decimal(0.0) else None |
|
757 | ||
758 | result['reporting_period']['increment_rate_in_kgco2e_saving'] = \ |
|
759 | (result['reporting_period']['total_in_kgco2e_saving'] - result['base_period']['total_in_kgco2e_saving']) / \ |
|
760 | result['base_period']['total_in_kgco2e_saving'] \ |
|
761 | if result['base_period']['total_in_kgco2e_saving'] != Decimal(0.0) else None |
|
762 | ||
763 | result['parameters'] = { |
|
764 | "names": parameters_data['names'], |
|
765 | "timestamps": parameters_data['timestamps'], |
|
766 | "values": parameters_data['values'] |
|
767 | } |
|
768 | ||
769 | result['excel_bytes_base64'] = None |
|
770 | if not is_quick_mode: |
|
771 | result['excel_bytes_base64'] = excelexporters.shopfloorplan.export(result, |
|
772 | shopfloor['name'], |
|
773 | base_period_start_datetime_local, |
|
774 | base_period_end_datetime_local, |
|
775 | reporting_period_start_datetime_local, |
|
776 | reporting_period_end_datetime_local, |
|
777 | period_type, |
|
778 | language) |
|
779 | ||
780 | resp.text = json.dumps(result) |
|
781 |
@@ 14-777 (lines=764) @@ | ||
11 | from core.useractivity import access_control, api_key_control |
|
12 | ||
13 | ||
14 | class Reporting: |
|
15 | def __init__(self): |
|
16 | """"Initializes Reporting""" |
|
17 | pass |
|
18 | ||
19 | @staticmethod |
|
20 | def on_options(req, resp): |
|
21 | _ = req |
|
22 | resp.status = falcon.HTTP_200 |
|
23 | ||
24 | #################################################################################################################### |
|
25 | # PROCEDURES |
|
26 | # Step 1: valid parameters |
|
27 | # Step 2: query the tenant |
|
28 | # Step 3: query energy categories |
|
29 | # Step 4: query associated sensors |
|
30 | # Step 5: query associated points |
|
31 | # Step 6: query base period energy saving |
|
32 | # Step 7: query reporting period energy saving |
|
33 | # Step 8: query tariff data |
|
34 | # Step 9: query associated sensors and points data |
|
35 | # Step 10: construct the report |
|
36 | #################################################################################################################### |
|
37 | @staticmethod |
|
38 | def on_get(req, resp): |
|
39 | if 'API-KEY' not in req.headers or \ |
|
40 | not isinstance(req.headers['API-KEY'], str) or \ |
|
41 | len(str.strip(req.headers['API-KEY'])) == 0: |
|
42 | access_control(req) |
|
43 | else: |
|
44 | api_key_control(req) |
|
45 | print(req.params) |
|
46 | tenant_id = req.params.get('tenantid') |
|
47 | tenant_uuid = req.params.get('tenantuuid') |
|
48 | period_type = req.params.get('periodtype') |
|
49 | base_period_start_datetime_local = req.params.get('baseperiodstartdatetime') |
|
50 | base_period_end_datetime_local = req.params.get('baseperiodenddatetime') |
|
51 | reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
|
52 | reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime') |
|
53 | language = req.params.get('language') |
|
54 | quick_mode = req.params.get('quickmode') |
|
55 | ||
56 | ################################################################################################################ |
|
57 | # Step 1: valid parameters |
|
58 | ################################################################################################################ |
|
59 | if tenant_id is None and tenant_uuid is None: |
|
60 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
61 | title='API.BAD_REQUEST', |
|
62 | description='API.INVALID_TENANT_ID') |
|
63 | ||
64 | if tenant_id is not None: |
|
65 | tenant_id = str.strip(tenant_id) |
|
66 | if not tenant_id.isdigit() or int(tenant_id) <= 0: |
|
67 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
68 | title='API.BAD_REQUEST', |
|
69 | description='API.INVALID_TENANT_ID') |
|
70 | ||
71 | if tenant_uuid is not None: |
|
72 | 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) |
|
73 | match = regex.match(str.strip(tenant_uuid)) |
|
74 | if not bool(match): |
|
75 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
76 | title='API.BAD_REQUEST', |
|
77 | description='API.INVALID_TENANT_UUID') |
|
78 | ||
79 | if period_type is None: |
|
80 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
81 | description='API.INVALID_PERIOD_TYPE') |
|
82 | else: |
|
83 | period_type = str.strip(period_type) |
|
84 | if period_type not in ['hourly', 'daily', 'weekly', 'monthly', 'yearly']: |
|
85 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
86 | description='API.INVALID_PERIOD_TYPE') |
|
87 | ||
88 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
|
89 | if config.utc_offset[0] == '-': |
|
90 | timezone_offset = -timezone_offset |
|
91 | ||
92 | base_start_datetime_utc = None |
|
93 | if base_period_start_datetime_local is not None and len(str.strip(base_period_start_datetime_local)) > 0: |
|
94 | base_period_start_datetime_local = str.strip(base_period_start_datetime_local) |
|
95 | try: |
|
96 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
97 | except ValueError: |
|
98 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
99 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
|
100 | base_start_datetime_utc = \ |
|
101 | base_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
102 | # nomalize the start datetime |
|
103 | if config.minutes_to_count == 30 and base_start_datetime_utc.minute >= 30: |
|
104 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
|
105 | else: |
|
106 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
|
107 | ||
108 | base_end_datetime_utc = None |
|
109 | if base_period_end_datetime_local is not None and len(str.strip(base_period_end_datetime_local)) > 0: |
|
110 | base_period_end_datetime_local = str.strip(base_period_end_datetime_local) |
|
111 | try: |
|
112 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
113 | except ValueError: |
|
114 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
115 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
|
116 | base_end_datetime_utc = \ |
|
117 | base_end_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
118 | ||
119 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
|
120 | base_start_datetime_utc >= base_end_datetime_utc: |
|
121 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
122 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
|
123 | ||
124 | if reporting_period_start_datetime_local is None: |
|
125 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
126 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
127 | else: |
|
128 | reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) |
|
129 | try: |
|
130 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, |
|
131 | '%Y-%m-%dT%H:%M:%S') |
|
132 | except ValueError: |
|
133 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
134 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
135 | reporting_start_datetime_utc = \ |
|
136 | reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
137 | # nomalize the start datetime |
|
138 | if config.minutes_to_count == 30 and reporting_start_datetime_utc.minute >= 30: |
|
139 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
|
140 | else: |
|
141 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
|
142 | ||
143 | if reporting_period_end_datetime_local is None: |
|
144 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
145 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
146 | else: |
|
147 | reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) |
|
148 | try: |
|
149 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, |
|
150 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
151 | timedelta(minutes=timezone_offset) |
|
152 | except ValueError: |
|
153 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
154 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
155 | ||
156 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
|
157 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
158 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
|
159 | ||
160 | # if turn quick mode on, do not return parameters data and excel file |
|
161 | is_quick_mode = False |
|
162 | if quick_mode is not None and \ |
|
163 | len(str.strip(quick_mode)) > 0 and \ |
|
164 | str.lower(str.strip(quick_mode)) in ('true', 't', 'on', 'yes', 'y'): |
|
165 | is_quick_mode = True |
|
166 | ||
167 | trans = utilities.get_translation(language) |
|
168 | trans.install() |
|
169 | _ = trans.gettext |
|
170 | ||
171 | ################################################################################################################ |
|
172 | # Step 2: query the tenant |
|
173 | ################################################################################################################ |
|
174 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
|
175 | cursor_system = cnx_system.cursor() |
|
176 | ||
177 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
|
178 | cursor_energy = cnx_energy.cursor() |
|
179 | ||
180 | cnx_energy_baseline = mysql.connector.connect(**config.myems_energy_baseline_db) |
|
181 | cursor_energy_baseline = cnx_energy_baseline.cursor() |
|
182 | ||
183 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
|
184 | cursor_historical = cnx_historical.cursor() |
|
185 | ||
186 | if tenant_id is not None: |
|
187 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
188 | " FROM tbl_tenants " |
|
189 | " WHERE id = %s ", (tenant_id,)) |
|
190 | row_tenant = cursor_system.fetchone() |
|
191 | elif tenant_uuid is not None: |
|
192 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
193 | " FROM tbl_tenants " |
|
194 | " WHERE uuid = %s ", (tenant_uuid,)) |
|
195 | row_tenant = cursor_system.fetchone() |
|
196 | ||
197 | if row_tenant is None: |
|
198 | if cursor_system: |
|
199 | cursor_system.close() |
|
200 | if cnx_system: |
|
201 | cnx_system.close() |
|
202 | ||
203 | if cursor_energy: |
|
204 | cursor_energy.close() |
|
205 | if cnx_energy: |
|
206 | cnx_energy.close() |
|
207 | ||
208 | if cursor_energy_baseline: |
|
209 | cursor_energy_baseline.close() |
|
210 | if cnx_energy_baseline: |
|
211 | cnx_energy_baseline.close() |
|
212 | ||
213 | if cursor_historical: |
|
214 | cursor_historical.close() |
|
215 | if cnx_historical: |
|
216 | cnx_historical.close() |
|
217 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', description='API.TENANT_NOT_FOUND') |
|
218 | ||
219 | tenant = dict() |
|
220 | tenant['id'] = row_tenant[0] |
|
221 | tenant['name'] = row_tenant[1] |
|
222 | tenant['area'] = row_tenant[2] |
|
223 | tenant['cost_center_id'] = row_tenant[3] |
|
224 | ||
225 | ################################################################################################################ |
|
226 | # Step 3: query energy categories |
|
227 | ################################################################################################################ |
|
228 | energy_category_set = set() |
|
229 | # query energy categories in base period |
|
230 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
231 | " FROM tbl_tenant_input_category_hourly " |
|
232 | " WHERE tenant_id = %s " |
|
233 | " AND start_datetime_utc >= %s " |
|
234 | " AND start_datetime_utc < %s ", |
|
235 | (tenant['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
236 | rows_energy_categories = cursor_energy.fetchall() |
|
237 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
|
238 | for row_energy_category in rows_energy_categories: |
|
239 | energy_category_set.add(row_energy_category[0]) |
|
240 | ||
241 | # query energy categories in reporting period |
|
242 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
243 | " FROM tbl_tenant_input_category_hourly " |
|
244 | " WHERE tenant_id = %s " |
|
245 | " AND start_datetime_utc >= %s " |
|
246 | " AND start_datetime_utc < %s ", |
|
247 | (tenant['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
248 | rows_energy_categories = cursor_energy.fetchall() |
|
249 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
|
250 | for row_energy_category in rows_energy_categories: |
|
251 | energy_category_set.add(row_energy_category[0]) |
|
252 | ||
253 | # query all energy categories in base period and reporting period |
|
254 | cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e " |
|
255 | " FROM tbl_energy_categories " |
|
256 | " ORDER BY id ", ) |
|
257 | rows_energy_categories = cursor_system.fetchall() |
|
258 | if rows_energy_categories is None or len(rows_energy_categories) == 0: |
|
259 | if cursor_system: |
|
260 | cursor_system.close() |
|
261 | if cnx_system: |
|
262 | cnx_system.close() |
|
263 | ||
264 | if cursor_energy: |
|
265 | cursor_energy.close() |
|
266 | if cnx_energy: |
|
267 | cnx_energy.close() |
|
268 | ||
269 | if cursor_energy_baseline: |
|
270 | cursor_energy_baseline.close() |
|
271 | if cnx_energy_baseline: |
|
272 | cnx_energy_baseline.close() |
|
273 | ||
274 | if cursor_historical: |
|
275 | cursor_historical.close() |
|
276 | if cnx_historical: |
|
277 | cnx_historical.close() |
|
278 | raise falcon.HTTPError(status=falcon.HTTP_404, |
|
279 | title='API.NOT_FOUND', |
|
280 | description='API.ENERGY_CATEGORY_NOT_FOUND') |
|
281 | energy_category_dict = dict() |
|
282 | for row_energy_category in rows_energy_categories: |
|
283 | if row_energy_category[0] in energy_category_set: |
|
284 | energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1], |
|
285 | "unit_of_measure": row_energy_category[2], |
|
286 | "kgce": row_energy_category[3], |
|
287 | "kgco2e": row_energy_category[4]} |
|
288 | ||
289 | ################################################################################################################ |
|
290 | # Step 4: query associated sensors |
|
291 | ################################################################################################################ |
|
292 | point_list = list() |
|
293 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
294 | " FROM tbl_tenants t, tbl_sensors s, tbl_tenants_sensors ts, " |
|
295 | " tbl_points p, tbl_sensors_points sp " |
|
296 | " WHERE t.id = %s AND t.id = ts.tenant_id AND ts.sensor_id = s.id " |
|
297 | " AND s.id = sp.sensor_id AND sp.point_id = p.id " |
|
298 | " ORDER BY p.id ", (tenant['id'],)) |
|
299 | rows_points = cursor_system.fetchall() |
|
300 | if rows_points is not None and len(rows_points) > 0: |
|
301 | for row in rows_points: |
|
302 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
303 | ||
304 | ################################################################################################################ |
|
305 | # Step 5: query associated points |
|
306 | ################################################################################################################ |
|
307 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
308 | " FROM tbl_tenants t, tbl_tenants_points tp, tbl_points p " |
|
309 | " WHERE t.id = %s AND t.id = tp.tenant_id AND tp.point_id = p.id " |
|
310 | " ORDER BY p.id ", (tenant['id'],)) |
|
311 | rows_points = cursor_system.fetchall() |
|
312 | if rows_points is not None and len(rows_points) > 0: |
|
313 | for row in rows_points: |
|
314 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
315 | ||
316 | ################################################################################################################ |
|
317 | # Step 6: query base period energy saving |
|
318 | ################################################################################################################ |
|
319 | base = dict() |
|
320 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
321 | for energy_category_id in energy_category_set: |
|
322 | kgce = energy_category_dict[energy_category_id]['kgce'] |
|
323 | kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
|
324 | ||
325 | base[energy_category_id] = dict() |
|
326 | base[energy_category_id]['timestamps'] = list() |
|
327 | base[energy_category_id]['values_baseline'] = list() |
|
328 | base[energy_category_id]['values_actual'] = list() |
|
329 | base[energy_category_id]['values_saving'] = list() |
|
330 | base[energy_category_id]['subtotal_baseline'] = Decimal(0.0) |
|
331 | base[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
|
332 | base[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
|
333 | base[energy_category_id]['subtotal_in_kgce_baseline'] = Decimal(0.0) |
|
334 | base[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
|
335 | base[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
|
336 | base[energy_category_id]['subtotal_in_kgco2e_baseline'] = Decimal(0.0) |
|
337 | base[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
|
338 | base[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
|
339 | # query base period's energy baseline |
|
340 | cursor_energy_baseline.execute(" SELECT start_datetime_utc, actual_value " |
|
341 | " FROM tbl_tenant_input_category_hourly " |
|
342 | " WHERE tenant_id = %s " |
|
343 | " AND energy_category_id = %s " |
|
344 | " AND start_datetime_utc >= %s " |
|
345 | " AND start_datetime_utc < %s " |
|
346 | " ORDER BY start_datetime_utc ", |
|
347 | (tenant['id'], |
|
348 | energy_category_id, |
|
349 | base_start_datetime_utc, |
|
350 | base_end_datetime_utc)) |
|
351 | rows_tenant_hourly = cursor_energy_baseline.fetchall() |
|
352 | ||
353 | rows_tenant_periodically = utilities.aggregate_hourly_data_by_period(rows_tenant_hourly, |
|
354 | base_start_datetime_utc, |
|
355 | base_end_datetime_utc, |
|
356 | period_type) |
|
357 | for row_tenant_periodically in rows_tenant_periodically: |
|
358 | current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
359 | timedelta(minutes=timezone_offset) |
|
360 | if period_type == 'hourly': |
|
361 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
362 | elif period_type == 'daily': |
|
363 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
364 | elif period_type == 'weekly': |
|
365 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
366 | elif period_type == 'monthly': |
|
367 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
368 | elif period_type == 'yearly': |
|
369 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
370 | ||
371 | baseline_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1] |
|
372 | base[energy_category_id]['timestamps'].append(current_datetime) |
|
373 | base[energy_category_id]['values_baseline'].append(baseline_value) |
|
374 | base[energy_category_id]['subtotal_baseline'] += baseline_value |
|
375 | base[energy_category_id]['subtotal_in_kgce_baseline'] += baseline_value * kgce |
|
376 | base[energy_category_id]['subtotal_in_kgco2e_baseline'] += baseline_value * kgco2e |
|
377 | ||
378 | # query base period's energy actual |
|
379 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
380 | " FROM tbl_tenant_input_category_hourly " |
|
381 | " WHERE tenant_id = %s " |
|
382 | " AND energy_category_id = %s " |
|
383 | " AND start_datetime_utc >= %s " |
|
384 | " AND start_datetime_utc < %s " |
|
385 | " ORDER BY start_datetime_utc ", |
|
386 | (tenant['id'], |
|
387 | energy_category_id, |
|
388 | base_start_datetime_utc, |
|
389 | base_end_datetime_utc)) |
|
390 | rows_tenant_hourly = cursor_energy.fetchall() |
|
391 | ||
392 | rows_tenant_periodically = utilities.aggregate_hourly_data_by_period(rows_tenant_hourly, |
|
393 | base_start_datetime_utc, |
|
394 | base_end_datetime_utc, |
|
395 | period_type) |
|
396 | for row_tenant_periodically in rows_tenant_periodically: |
|
397 | current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
398 | timedelta(minutes=timezone_offset) |
|
399 | if period_type == 'hourly': |
|
400 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
401 | elif period_type == 'daily': |
|
402 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
403 | elif period_type == 'weekly': |
|
404 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
405 | elif period_type == 'monthly': |
|
406 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
407 | elif period_type == 'yearly': |
|
408 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
409 | ||
410 | actual_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1] |
|
411 | base[energy_category_id]['values_actual'].append(actual_value) |
|
412 | base[energy_category_id]['subtotal_actual'] += actual_value |
|
413 | base[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
|
414 | base[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
|
415 | ||
416 | # calculate base period's energy saving |
|
417 | for i in range(len(base[energy_category_id]['values_baseline'])): |
|
418 | base[energy_category_id]['values_saving'].append( |
|
419 | base[energy_category_id]['values_baseline'][i] - |
|
420 | base[energy_category_id]['values_actual'][i]) |
|
421 | ||
422 | base[energy_category_id]['subtotal_saving'] = \ |
|
423 | base[energy_category_id]['subtotal_baseline'] - \ |
|
424 | base[energy_category_id]['subtotal_actual'] |
|
425 | base[energy_category_id]['subtotal_in_kgce_saving'] = \ |
|
426 | base[energy_category_id]['subtotal_in_kgce_baseline'] - \ |
|
427 | base[energy_category_id]['subtotal_in_kgce_actual'] |
|
428 | base[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
|
429 | base[energy_category_id]['subtotal_in_kgco2e_baseline'] - \ |
|
430 | base[energy_category_id]['subtotal_in_kgco2e_actual'] |
|
431 | ################################################################################################################ |
|
432 | # Step 7: query reporting period energy saving |
|
433 | ################################################################################################################ |
|
434 | reporting = dict() |
|
435 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
436 | for energy_category_id in energy_category_set: |
|
437 | kgce = energy_category_dict[energy_category_id]['kgce'] |
|
438 | kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
|
439 | ||
440 | reporting[energy_category_id] = dict() |
|
441 | reporting[energy_category_id]['timestamps'] = list() |
|
442 | reporting[energy_category_id]['values_baseline'] = list() |
|
443 | reporting[energy_category_id]['values_actual'] = list() |
|
444 | reporting[energy_category_id]['values_saving'] = list() |
|
445 | reporting[energy_category_id]['subtotal_baseline'] = Decimal(0.0) |
|
446 | reporting[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
|
447 | reporting[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
|
448 | reporting[energy_category_id]['subtotal_in_kgce_baseline'] = Decimal(0.0) |
|
449 | reporting[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
|
450 | reporting[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
|
451 | reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] = Decimal(0.0) |
|
452 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
|
453 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
|
454 | # query reporting period's energy baseline |
|
455 | cursor_energy_baseline.execute(" SELECT start_datetime_utc, actual_value " |
|
456 | " FROM tbl_tenant_input_category_hourly " |
|
457 | " WHERE tenant_id = %s " |
|
458 | " AND energy_category_id = %s " |
|
459 | " AND start_datetime_utc >= %s " |
|
460 | " AND start_datetime_utc < %s " |
|
461 | " ORDER BY start_datetime_utc ", |
|
462 | (tenant['id'], |
|
463 | energy_category_id, |
|
464 | reporting_start_datetime_utc, |
|
465 | reporting_end_datetime_utc)) |
|
466 | rows_tenant_hourly = cursor_energy_baseline.fetchall() |
|
467 | ||
468 | rows_tenant_periodically = utilities.aggregate_hourly_data_by_period(rows_tenant_hourly, |
|
469 | reporting_start_datetime_utc, |
|
470 | reporting_end_datetime_utc, |
|
471 | period_type) |
|
472 | for row_tenant_periodically in rows_tenant_periodically: |
|
473 | current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
474 | timedelta(minutes=timezone_offset) |
|
475 | if period_type == 'hourly': |
|
476 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
477 | elif period_type == 'daily': |
|
478 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
479 | elif period_type == 'weekly': |
|
480 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
481 | elif period_type == 'monthly': |
|
482 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
483 | elif period_type == 'yearly': |
|
484 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
485 | ||
486 | baseline_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1] |
|
487 | reporting[energy_category_id]['timestamps'].append(current_datetime) |
|
488 | reporting[energy_category_id]['values_baseline'].append(baseline_value) |
|
489 | reporting[energy_category_id]['subtotal_baseline'] += baseline_value |
|
490 | reporting[energy_category_id]['subtotal_in_kgce_baseline'] += baseline_value * kgce |
|
491 | reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] += baseline_value * kgco2e |
|
492 | ||
493 | # query reporting period's energy actual |
|
494 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
495 | " FROM tbl_tenant_input_category_hourly " |
|
496 | " WHERE tenant_id = %s " |
|
497 | " AND energy_category_id = %s " |
|
498 | " AND start_datetime_utc >= %s " |
|
499 | " AND start_datetime_utc < %s " |
|
500 | " ORDER BY start_datetime_utc ", |
|
501 | (tenant['id'], |
|
502 | energy_category_id, |
|
503 | reporting_start_datetime_utc, |
|
504 | reporting_end_datetime_utc)) |
|
505 | rows_tenant_hourly = cursor_energy.fetchall() |
|
506 | ||
507 | rows_tenant_periodically = utilities.aggregate_hourly_data_by_period(rows_tenant_hourly, |
|
508 | reporting_start_datetime_utc, |
|
509 | reporting_end_datetime_utc, |
|
510 | period_type) |
|
511 | for row_tenant_periodically in rows_tenant_periodically: |
|
512 | current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
513 | timedelta(minutes=timezone_offset) |
|
514 | if period_type == 'hourly': |
|
515 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
516 | elif period_type == 'daily': |
|
517 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
518 | elif period_type == 'weekly': |
|
519 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
520 | elif period_type == 'monthly': |
|
521 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
522 | elif period_type == 'yearly': |
|
523 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
524 | ||
525 | actual_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1] |
|
526 | reporting[energy_category_id]['values_actual'].append(actual_value) |
|
527 | reporting[energy_category_id]['subtotal_actual'] += actual_value |
|
528 | reporting[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
|
529 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
|
530 | ||
531 | # calculate reporting period's energy savings |
|
532 | for i in range(len(reporting[energy_category_id]['values_baseline'])): |
|
533 | reporting[energy_category_id]['values_saving'].append( |
|
534 | reporting[energy_category_id]['values_baseline'][i] - |
|
535 | reporting[energy_category_id]['values_actual'][i]) |
|
536 | ||
537 | reporting[energy_category_id]['subtotal_saving'] = \ |
|
538 | reporting[energy_category_id]['subtotal_baseline'] - \ |
|
539 | reporting[energy_category_id]['subtotal_actual'] |
|
540 | reporting[energy_category_id]['subtotal_in_kgce_saving'] = \ |
|
541 | reporting[energy_category_id]['subtotal_in_kgce_baseline'] - \ |
|
542 | reporting[energy_category_id]['subtotal_in_kgce_actual'] |
|
543 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
|
544 | reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] - \ |
|
545 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] |
|
546 | ################################################################################################################ |
|
547 | # Step 8: query tariff data |
|
548 | ################################################################################################################ |
|
549 | parameters_data = dict() |
|
550 | parameters_data['names'] = list() |
|
551 | parameters_data['timestamps'] = list() |
|
552 | parameters_data['values'] = list() |
|
553 | if config.is_tariff_appended and energy_category_set is not None and len(energy_category_set) > 0 \ |
|
554 | and not is_quick_mode: |
|
555 | for energy_category_id in energy_category_set: |
|
556 | energy_category_tariff_dict = utilities.get_energy_category_tariffs(tenant['cost_center_id'], |
|
557 | energy_category_id, |
|
558 | reporting_start_datetime_utc, |
|
559 | reporting_end_datetime_utc) |
|
560 | tariff_timestamp_list = list() |
|
561 | tariff_value_list = list() |
|
562 | for k, v in energy_category_tariff_dict.items(): |
|
563 | # convert k from utc to local |
|
564 | k = k + timedelta(minutes=timezone_offset) |
|
565 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
|
566 | tariff_value_list.append(v) |
|
567 | ||
568 | parameters_data['names'].append(_('Tariff') + '-' + energy_category_dict[energy_category_id]['name']) |
|
569 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
570 | parameters_data['values'].append(tariff_value_list) |
|
571 | ||
572 | ################################################################################################################ |
|
573 | # Step 9: query associated sensors and points data |
|
574 | ################################################################################################################ |
|
575 | if not is_quick_mode: |
|
576 | for point in point_list: |
|
577 | point_values = [] |
|
578 | point_timestamps = [] |
|
579 | if point['object_type'] == 'ENERGY_VALUE': |
|
580 | query = (" SELECT utc_date_time, actual_value " |
|
581 | " FROM tbl_energy_value " |
|
582 | " WHERE point_id = %s " |
|
583 | " AND utc_date_time BETWEEN %s AND %s " |
|
584 | " ORDER BY utc_date_time ") |
|
585 | cursor_historical.execute(query, (point['id'], |
|
586 | reporting_start_datetime_utc, |
|
587 | reporting_end_datetime_utc)) |
|
588 | rows = cursor_historical.fetchall() |
|
589 | ||
590 | if rows is not None and len(rows) > 0: |
|
591 | for row in rows: |
|
592 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
593 | timedelta(minutes=timezone_offset) |
|
594 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
595 | point_timestamps.append(current_datetime) |
|
596 | point_values.append(row[1]) |
|
597 | elif point['object_type'] == 'ANALOG_VALUE': |
|
598 | query = (" SELECT utc_date_time, actual_value " |
|
599 | " FROM tbl_analog_value " |
|
600 | " WHERE point_id = %s " |
|
601 | " AND utc_date_time BETWEEN %s AND %s " |
|
602 | " ORDER BY utc_date_time ") |
|
603 | cursor_historical.execute(query, (point['id'], |
|
604 | reporting_start_datetime_utc, |
|
605 | reporting_end_datetime_utc)) |
|
606 | rows = cursor_historical.fetchall() |
|
607 | ||
608 | if rows is not None and len(rows) > 0: |
|
609 | for row in rows: |
|
610 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
611 | timedelta(minutes=timezone_offset) |
|
612 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
613 | point_timestamps.append(current_datetime) |
|
614 | point_values.append(row[1]) |
|
615 | elif point['object_type'] == 'DIGITAL_VALUE': |
|
616 | query = (" SELECT utc_date_time, actual_value " |
|
617 | " FROM tbl_digital_value " |
|
618 | " WHERE point_id = %s " |
|
619 | " AND utc_date_time BETWEEN %s AND %s " |
|
620 | " ORDER BY utc_date_time ") |
|
621 | cursor_historical.execute(query, (point['id'], |
|
622 | reporting_start_datetime_utc, |
|
623 | reporting_end_datetime_utc)) |
|
624 | rows = cursor_historical.fetchall() |
|
625 | ||
626 | if rows is not None and len(rows) > 0: |
|
627 | for row in rows: |
|
628 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
629 | timedelta(minutes=timezone_offset) |
|
630 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
631 | point_timestamps.append(current_datetime) |
|
632 | point_values.append(row[1]) |
|
633 | ||
634 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
|
635 | parameters_data['timestamps'].append(point_timestamps) |
|
636 | parameters_data['values'].append(point_values) |
|
637 | ||
638 | ################################################################################################################ |
|
639 | # Step 10: construct the report |
|
640 | ################################################################################################################ |
|
641 | if cursor_system: |
|
642 | cursor_system.close() |
|
643 | if cnx_system: |
|
644 | cnx_system.close() |
|
645 | ||
646 | if cursor_energy: |
|
647 | cursor_energy.close() |
|
648 | if cnx_energy: |
|
649 | cnx_energy.close() |
|
650 | ||
651 | if cursor_energy_baseline: |
|
652 | cursor_energy_baseline.close() |
|
653 | if cnx_energy_baseline: |
|
654 | cnx_energy_baseline.close() |
|
655 | ||
656 | if cursor_historical: |
|
657 | cursor_historical.close() |
|
658 | if cnx_historical: |
|
659 | cnx_historical.close() |
|
660 | ||
661 | result = dict() |
|
662 | ||
663 | result['tenant'] = dict() |
|
664 | result['tenant']['name'] = tenant['name'] |
|
665 | result['tenant']['area'] = tenant['area'] |
|
666 | ||
667 | result['base_period'] = dict() |
|
668 | result['base_period']['names'] = list() |
|
669 | result['base_period']['units'] = list() |
|
670 | result['base_period']['timestamps'] = list() |
|
671 | result['base_period']['values_saving'] = list() |
|
672 | result['base_period']['subtotals_saving'] = list() |
|
673 | result['base_period']['subtotals_in_kgce_saving'] = list() |
|
674 | result['base_period']['subtotals_in_kgco2e_saving'] = list() |
|
675 | result['base_period']['total_in_kgce_saving'] = Decimal(0.0) |
|
676 | result['base_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
|
677 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
678 | for energy_category_id in energy_category_set: |
|
679 | result['base_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
680 | result['base_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
681 | result['base_period']['timestamps'].append(base[energy_category_id]['timestamps']) |
|
682 | result['base_period']['values_saving'].append(base[energy_category_id]['values_saving']) |
|
683 | result['base_period']['subtotals_saving'].append(base[energy_category_id]['subtotal_saving']) |
|
684 | result['base_period']['subtotals_in_kgce_saving'].append( |
|
685 | base[energy_category_id]['subtotal_in_kgce_saving']) |
|
686 | result['base_period']['subtotals_in_kgco2e_saving'].append( |
|
687 | base[energy_category_id]['subtotal_in_kgco2e_saving']) |
|
688 | result['base_period']['total_in_kgce_saving'] += base[energy_category_id]['subtotal_in_kgce_saving'] |
|
689 | result['base_period']['total_in_kgco2e_saving'] += base[energy_category_id]['subtotal_in_kgco2e_saving'] |
|
690 | ||
691 | result['reporting_period'] = dict() |
|
692 | result['reporting_period']['names'] = list() |
|
693 | result['reporting_period']['energy_category_ids'] = list() |
|
694 | result['reporting_period']['units'] = list() |
|
695 | result['reporting_period']['timestamps'] = list() |
|
696 | result['reporting_period']['values_saving'] = list() |
|
697 | result['reporting_period']['rates_saving'] = list() |
|
698 | result['reporting_period']['subtotals_saving'] = list() |
|
699 | result['reporting_period']['subtotals_in_kgce_saving'] = list() |
|
700 | result['reporting_period']['subtotals_in_kgco2e_saving'] = list() |
|
701 | result['reporting_period']['subtotals_per_unit_area_saving'] = list() |
|
702 | result['reporting_period']['increment_rates_saving'] = list() |
|
703 | result['reporting_period']['total_in_kgce_saving'] = Decimal(0.0) |
|
704 | result['reporting_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
|
705 | result['reporting_period']['increment_rate_in_kgce_saving'] = Decimal(0.0) |
|
706 | result['reporting_period']['increment_rate_in_kgco2e_saving'] = Decimal(0.0) |
|
707 | ||
708 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
709 | for energy_category_id in energy_category_set: |
|
710 | result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
711 | result['reporting_period']['energy_category_ids'].append(energy_category_id) |
|
712 | result['reporting_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
713 | result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps']) |
|
714 | result['reporting_period']['values_saving'].append(reporting[energy_category_id]['values_saving']) |
|
715 | result['reporting_period']['subtotals_saving'].append(reporting[energy_category_id]['subtotal_saving']) |
|
716 | result['reporting_period']['subtotals_in_kgce_saving'].append( |
|
717 | reporting[energy_category_id]['subtotal_in_kgce_saving']) |
|
718 | result['reporting_period']['subtotals_in_kgco2e_saving'].append( |
|
719 | reporting[energy_category_id]['subtotal_in_kgco2e_saving']) |
|
720 | result['reporting_period']['subtotals_per_unit_area_saving'].append( |
|
721 | reporting[energy_category_id]['subtotal_saving'] / tenant['area'] |
|
722 | if tenant['area'] != Decimal(0.0) else None) |
|
723 | result['reporting_period']['increment_rates_saving'].append( |
|
724 | (reporting[energy_category_id]['subtotal_saving'] - base[energy_category_id]['subtotal_saving']) / |
|
725 | base[energy_category_id]['subtotal_saving'] |
|
726 | if base[energy_category_id]['subtotal_saving'] != Decimal(0.0) else None) |
|
727 | result['reporting_period']['total_in_kgce_saving'] += \ |
|
728 | reporting[energy_category_id]['subtotal_in_kgce_saving'] |
|
729 | result['reporting_period']['total_in_kgco2e_saving'] += \ |
|
730 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] |
|
731 | ||
732 | rate = list() |
|
733 | for index, value in enumerate(reporting[energy_category_id]['values_saving']): |
|
734 | if index < len(base[energy_category_id]['values_saving']) \ |
|
735 | and base[energy_category_id]['values_saving'][index] != Decimal(0.0) \ |
|
736 | and value != Decimal(0.0): |
|
737 | rate.append((value - base[energy_category_id]['values_saving'][index]) |
|
738 | / base[energy_category_id]['values_saving'][index]) |
|
739 | else: |
|
740 | rate.append(None) |
|
741 | result['reporting_period']['rates_saving'].append(rate) |
|
742 | ||
743 | result['reporting_period']['total_in_kgco2e_per_unit_area_saving'] = \ |
|
744 | result['reporting_period']['total_in_kgce_saving'] / tenant['area'] \ |
|
745 | if tenant['area'] != Decimal(0.0) else None |
|
746 | ||
747 | result['reporting_period']['increment_rate_in_kgce_saving'] = \ |
|
748 | (result['reporting_period']['total_in_kgce_saving'] - result['base_period']['total_in_kgce_saving']) / \ |
|
749 | result['base_period']['total_in_kgce_saving'] \ |
|
750 | if result['base_period']['total_in_kgce_saving'] != Decimal(0.0) else None |
|
751 | ||
752 | result['reporting_period']['total_in_kgce_per_unit_area_saving'] = \ |
|
753 | result['reporting_period']['total_in_kgco2e_saving'] / tenant['area'] if tenant['area'] > 0.0 else None |
|
754 | ||
755 | result['reporting_period']['increment_rate_in_kgco2e_saving'] = \ |
|
756 | (result['reporting_period']['total_in_kgco2e_saving'] - result['base_period']['total_in_kgco2e_saving']) / \ |
|
757 | result['base_period']['total_in_kgco2e_saving'] \ |
|
758 | if result['base_period']['total_in_kgco2e_saving'] != Decimal(0.0) else None |
|
759 | ||
760 | result['parameters'] = { |
|
761 | "names": parameters_data['names'], |
|
762 | "timestamps": parameters_data['timestamps'], |
|
763 | "values": parameters_data['values'] |
|
764 | } |
|
765 | ||
766 | # export result to Excel file and then encode the file to base64 string |
|
767 | if not is_quick_mode: |
|
768 | result['excel_bytes_base64'] = excelexporters.tenantsaving.export(result, |
|
769 | tenant['name'], |
|
770 | base_period_start_datetime_local, |
|
771 | base_period_end_datetime_local, |
|
772 | reporting_period_start_datetime_local, |
|
773 | reporting_period_end_datetime_local, |
|
774 | period_type, |
|
775 | language) |
|
776 | ||
777 | resp.text = json.dumps(result) |
|
778 |
@@ 13-776 (lines=764) @@ | ||
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 tenant |
|
27 | # Step 3: query energy categories |
|
28 | # Step 4: query associated sensors |
|
29 | # Step 5: query associated points |
|
30 | # Step 6: query base period energy saving |
|
31 | # Step 7: query reporting period energy saving |
|
32 | # Step 8: query tariff data |
|
33 | # Step 9: query associated sensors and 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 | tenant_id = req.params.get('tenantid') |
|
46 | tenant_uuid = req.params.get('tenantuuid') |
|
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 tenant_id is None and tenant_uuid is None: |
|
59 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
60 | title='API.BAD_REQUEST', |
|
61 | description='API.INVALID_TENANT_ID') |
|
62 | ||
63 | if tenant_id is not None: |
|
64 | tenant_id = str.strip(tenant_id) |
|
65 | if not tenant_id.isdigit() or int(tenant_id) <= 0: |
|
66 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
67 | title='API.BAD_REQUEST', |
|
68 | description='API.INVALID_TENANT_ID') |
|
69 | ||
70 | if tenant_uuid is not None: |
|
71 | 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) |
|
72 | match = regex.match(str.strip(tenant_uuid)) |
|
73 | if not bool(match): |
|
74 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
75 | title='API.BAD_REQUEST', |
|
76 | description='API.INVALID_TENANT_UUID') |
|
77 | ||
78 | if period_type is None: |
|
79 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
80 | description='API.INVALID_PERIOD_TYPE') |
|
81 | else: |
|
82 | period_type = str.strip(period_type) |
|
83 | if period_type not in ['hourly', 'daily', 'weekly', 'monthly', 'yearly']: |
|
84 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
85 | description='API.INVALID_PERIOD_TYPE') |
|
86 | ||
87 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
|
88 | if config.utc_offset[0] == '-': |
|
89 | timezone_offset = -timezone_offset |
|
90 | ||
91 | base_start_datetime_utc = None |
|
92 | if base_period_start_datetime_local is not None and len(str.strip(base_period_start_datetime_local)) > 0: |
|
93 | base_period_start_datetime_local = str.strip(base_period_start_datetime_local) |
|
94 | try: |
|
95 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
96 | except ValueError: |
|
97 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
98 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
|
99 | base_start_datetime_utc = \ |
|
100 | base_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
101 | # nomalize the start datetime |
|
102 | if config.minutes_to_count == 30 and base_start_datetime_utc.minute >= 30: |
|
103 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
|
104 | else: |
|
105 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
|
106 | ||
107 | base_end_datetime_utc = None |
|
108 | if base_period_end_datetime_local is not None and len(str.strip(base_period_end_datetime_local)) > 0: |
|
109 | base_period_end_datetime_local = str.strip(base_period_end_datetime_local) |
|
110 | try: |
|
111 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
112 | except ValueError: |
|
113 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
114 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
|
115 | base_end_datetime_utc = \ |
|
116 | base_end_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
117 | ||
118 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
|
119 | base_start_datetime_utc >= base_end_datetime_utc: |
|
120 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
121 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
|
122 | ||
123 | if reporting_period_start_datetime_local is None: |
|
124 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
125 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
126 | else: |
|
127 | reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) |
|
128 | try: |
|
129 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, |
|
130 | '%Y-%m-%dT%H:%M:%S') |
|
131 | except ValueError: |
|
132 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
133 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
134 | reporting_start_datetime_utc = \ |
|
135 | reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
136 | # nomalize the start datetime |
|
137 | if config.minutes_to_count == 30 and reporting_start_datetime_utc.minute >= 30: |
|
138 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
|
139 | else: |
|
140 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
|
141 | ||
142 | if reporting_period_end_datetime_local is None: |
|
143 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
144 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
145 | else: |
|
146 | reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) |
|
147 | try: |
|
148 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, |
|
149 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
150 | timedelta(minutes=timezone_offset) |
|
151 | except ValueError: |
|
152 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
153 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
154 | ||
155 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
|
156 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
157 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
|
158 | ||
159 | # if turn quick mode on, do not return parameters data and excel file |
|
160 | is_quick_mode = False |
|
161 | if quick_mode is not None and \ |
|
162 | len(str.strip(quick_mode)) > 0 and \ |
|
163 | str.lower(str.strip(quick_mode)) in ('true', 't', 'on', 'yes', 'y'): |
|
164 | is_quick_mode = True |
|
165 | ||
166 | trans = utilities.get_translation(language) |
|
167 | trans.install() |
|
168 | _ = trans.gettext |
|
169 | ||
170 | ################################################################################################################ |
|
171 | # Step 2: query the tenant |
|
172 | ################################################################################################################ |
|
173 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
|
174 | cursor_system = cnx_system.cursor() |
|
175 | ||
176 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
|
177 | cursor_energy = cnx_energy.cursor() |
|
178 | ||
179 | cnx_energy_plan = mysql.connector.connect(**config.myems_energy_plan_db) |
|
180 | cursor_energy_plan = cnx_energy_plan.cursor() |
|
181 | ||
182 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
|
183 | cursor_historical = cnx_historical.cursor() |
|
184 | ||
185 | if tenant_id is not None: |
|
186 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
187 | " FROM tbl_tenants " |
|
188 | " WHERE id = %s ", (tenant_id,)) |
|
189 | row_tenant = cursor_system.fetchone() |
|
190 | elif tenant_uuid is not None: |
|
191 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
192 | " FROM tbl_tenants " |
|
193 | " WHERE uuid = %s ", (tenant_uuid,)) |
|
194 | row_tenant = cursor_system.fetchone() |
|
195 | ||
196 | if row_tenant is None: |
|
197 | if cursor_system: |
|
198 | cursor_system.close() |
|
199 | if cnx_system: |
|
200 | cnx_system.close() |
|
201 | ||
202 | if cursor_energy: |
|
203 | cursor_energy.close() |
|
204 | if cnx_energy: |
|
205 | cnx_energy.close() |
|
206 | ||
207 | if cursor_energy_plan: |
|
208 | cursor_energy_plan.close() |
|
209 | if cnx_energy_plan: |
|
210 | cnx_energy_plan.close() |
|
211 | ||
212 | if cursor_historical: |
|
213 | cursor_historical.close() |
|
214 | if cnx_historical: |
|
215 | cnx_historical.close() |
|
216 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', description='API.TENANT_NOT_FOUND') |
|
217 | ||
218 | tenant = dict() |
|
219 | tenant['id'] = row_tenant[0] |
|
220 | tenant['name'] = row_tenant[1] |
|
221 | tenant['area'] = row_tenant[2] |
|
222 | tenant['cost_center_id'] = row_tenant[3] |
|
223 | ||
224 | ################################################################################################################ |
|
225 | # Step 3: query energy categories |
|
226 | ################################################################################################################ |
|
227 | energy_category_set = set() |
|
228 | # query energy categories in base period |
|
229 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
230 | " FROM tbl_tenant_input_category_hourly " |
|
231 | " WHERE tenant_id = %s " |
|
232 | " AND start_datetime_utc >= %s " |
|
233 | " AND start_datetime_utc < %s ", |
|
234 | (tenant['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
235 | rows_energy_categories = cursor_energy.fetchall() |
|
236 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
|
237 | for row_energy_category in rows_energy_categories: |
|
238 | energy_category_set.add(row_energy_category[0]) |
|
239 | ||
240 | # query energy categories in reporting period |
|
241 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
242 | " FROM tbl_tenant_input_category_hourly " |
|
243 | " WHERE tenant_id = %s " |
|
244 | " AND start_datetime_utc >= %s " |
|
245 | " AND start_datetime_utc < %s ", |
|
246 | (tenant['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
247 | rows_energy_categories = cursor_energy.fetchall() |
|
248 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
|
249 | for row_energy_category in rows_energy_categories: |
|
250 | energy_category_set.add(row_energy_category[0]) |
|
251 | ||
252 | # query all energy categories in base period and reporting period |
|
253 | cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e " |
|
254 | " FROM tbl_energy_categories " |
|
255 | " ORDER BY id ", ) |
|
256 | rows_energy_categories = cursor_system.fetchall() |
|
257 | if rows_energy_categories is None or len(rows_energy_categories) == 0: |
|
258 | if cursor_system: |
|
259 | cursor_system.close() |
|
260 | if cnx_system: |
|
261 | cnx_system.close() |
|
262 | ||
263 | if cursor_energy: |
|
264 | cursor_energy.close() |
|
265 | if cnx_energy: |
|
266 | cnx_energy.close() |
|
267 | ||
268 | if cursor_energy_plan: |
|
269 | cursor_energy_plan.close() |
|
270 | if cnx_energy_plan: |
|
271 | cnx_energy_plan.close() |
|
272 | ||
273 | if cursor_historical: |
|
274 | cursor_historical.close() |
|
275 | if cnx_historical: |
|
276 | cnx_historical.close() |
|
277 | raise falcon.HTTPError(status=falcon.HTTP_404, |
|
278 | title='API.NOT_FOUND', |
|
279 | description='API.ENERGY_CATEGORY_NOT_FOUND') |
|
280 | energy_category_dict = dict() |
|
281 | for row_energy_category in rows_energy_categories: |
|
282 | if row_energy_category[0] in energy_category_set: |
|
283 | energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1], |
|
284 | "unit_of_measure": row_energy_category[2], |
|
285 | "kgce": row_energy_category[3], |
|
286 | "kgco2e": row_energy_category[4]} |
|
287 | ||
288 | ################################################################################################################ |
|
289 | # Step 4: query associated sensors |
|
290 | ################################################################################################################ |
|
291 | point_list = list() |
|
292 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
293 | " FROM tbl_tenants t, tbl_sensors s, tbl_tenants_sensors ts, " |
|
294 | " tbl_points p, tbl_sensors_points sp " |
|
295 | " WHERE t.id = %s AND t.id = ts.tenant_id AND ts.sensor_id = s.id " |
|
296 | " AND s.id = sp.sensor_id AND sp.point_id = p.id " |
|
297 | " ORDER BY p.id ", (tenant['id'],)) |
|
298 | rows_points = cursor_system.fetchall() |
|
299 | if rows_points is not None and len(rows_points) > 0: |
|
300 | for row in rows_points: |
|
301 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
302 | ||
303 | ################################################################################################################ |
|
304 | # Step 5: query associated points |
|
305 | ################################################################################################################ |
|
306 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
307 | " FROM tbl_tenants t, tbl_tenants_points tp, tbl_points p " |
|
308 | " WHERE t.id = %s AND t.id = tp.tenant_id AND tp.point_id = p.id " |
|
309 | " ORDER BY p.id ", (tenant['id'],)) |
|
310 | rows_points = cursor_system.fetchall() |
|
311 | if rows_points is not None and len(rows_points) > 0: |
|
312 | for row in rows_points: |
|
313 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
314 | ||
315 | ################################################################################################################ |
|
316 | # Step 6: query base period energy saving |
|
317 | ################################################################################################################ |
|
318 | base = dict() |
|
319 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
320 | for energy_category_id in energy_category_set: |
|
321 | kgce = energy_category_dict[energy_category_id]['kgce'] |
|
322 | kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
|
323 | ||
324 | base[energy_category_id] = dict() |
|
325 | base[energy_category_id]['timestamps'] = list() |
|
326 | base[energy_category_id]['values_plan'] = list() |
|
327 | base[energy_category_id]['values_actual'] = list() |
|
328 | base[energy_category_id]['values_saving'] = list() |
|
329 | base[energy_category_id]['subtotal_plan'] = Decimal(0.0) |
|
330 | base[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
|
331 | base[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
|
332 | base[energy_category_id]['subtotal_in_kgce_plan'] = Decimal(0.0) |
|
333 | base[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
|
334 | base[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
|
335 | base[energy_category_id]['subtotal_in_kgco2e_plan'] = Decimal(0.0) |
|
336 | base[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
|
337 | base[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
|
338 | # query base period's energy plan |
|
339 | cursor_energy_plan.execute(" SELECT start_datetime_utc, actual_value " |
|
340 | " FROM tbl_tenant_input_category_hourly " |
|
341 | " WHERE tenant_id = %s " |
|
342 | " AND energy_category_id = %s " |
|
343 | " AND start_datetime_utc >= %s " |
|
344 | " AND start_datetime_utc < %s " |
|
345 | " ORDER BY start_datetime_utc ", |
|
346 | (tenant['id'], |
|
347 | energy_category_id, |
|
348 | base_start_datetime_utc, |
|
349 | base_end_datetime_utc)) |
|
350 | rows_tenant_hourly = cursor_energy_plan.fetchall() |
|
351 | ||
352 | rows_tenant_periodically = utilities.aggregate_hourly_data_by_period(rows_tenant_hourly, |
|
353 | base_start_datetime_utc, |
|
354 | base_end_datetime_utc, |
|
355 | period_type) |
|
356 | for row_tenant_periodically in rows_tenant_periodically: |
|
357 | current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
358 | timedelta(minutes=timezone_offset) |
|
359 | if period_type == 'hourly': |
|
360 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
361 | elif period_type == 'daily': |
|
362 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
363 | elif period_type == 'weekly': |
|
364 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
365 | elif period_type == 'monthly': |
|
366 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
367 | elif period_type == 'yearly': |
|
368 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
369 | ||
370 | plan_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1] |
|
371 | base[energy_category_id]['timestamps'].append(current_datetime) |
|
372 | base[energy_category_id]['values_plan'].append(plan_value) |
|
373 | base[energy_category_id]['subtotal_plan'] += plan_value |
|
374 | base[energy_category_id]['subtotal_in_kgce_plan'] += plan_value * kgce |
|
375 | base[energy_category_id]['subtotal_in_kgco2e_plan'] += plan_value * kgco2e |
|
376 | ||
377 | # query base period's energy actual |
|
378 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
379 | " FROM tbl_tenant_input_category_hourly " |
|
380 | " WHERE tenant_id = %s " |
|
381 | " AND energy_category_id = %s " |
|
382 | " AND start_datetime_utc >= %s " |
|
383 | " AND start_datetime_utc < %s " |
|
384 | " ORDER BY start_datetime_utc ", |
|
385 | (tenant['id'], |
|
386 | energy_category_id, |
|
387 | base_start_datetime_utc, |
|
388 | base_end_datetime_utc)) |
|
389 | rows_tenant_hourly = cursor_energy.fetchall() |
|
390 | ||
391 | rows_tenant_periodically = utilities.aggregate_hourly_data_by_period(rows_tenant_hourly, |
|
392 | base_start_datetime_utc, |
|
393 | base_end_datetime_utc, |
|
394 | period_type) |
|
395 | for row_tenant_periodically in rows_tenant_periodically: |
|
396 | current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
397 | timedelta(minutes=timezone_offset) |
|
398 | if period_type == 'hourly': |
|
399 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
400 | elif period_type == 'daily': |
|
401 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
402 | elif period_type == 'weekly': |
|
403 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
404 | elif period_type == 'monthly': |
|
405 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
406 | elif period_type == 'yearly': |
|
407 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
408 | ||
409 | actual_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1] |
|
410 | base[energy_category_id]['values_actual'].append(actual_value) |
|
411 | base[energy_category_id]['subtotal_actual'] += actual_value |
|
412 | base[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
|
413 | base[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
|
414 | ||
415 | # calculate base period's energy saving |
|
416 | for i in range(len(base[energy_category_id]['values_plan'])): |
|
417 | base[energy_category_id]['values_saving'].append( |
|
418 | base[energy_category_id]['values_plan'][i] - |
|
419 | base[energy_category_id]['values_actual'][i]) |
|
420 | ||
421 | base[energy_category_id]['subtotal_saving'] = \ |
|
422 | base[energy_category_id]['subtotal_plan'] - \ |
|
423 | base[energy_category_id]['subtotal_actual'] |
|
424 | base[energy_category_id]['subtotal_in_kgce_saving'] = \ |
|
425 | base[energy_category_id]['subtotal_in_kgce_plan'] - \ |
|
426 | base[energy_category_id]['subtotal_in_kgce_actual'] |
|
427 | base[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
|
428 | base[energy_category_id]['subtotal_in_kgco2e_plan'] - \ |
|
429 | base[energy_category_id]['subtotal_in_kgco2e_actual'] |
|
430 | ################################################################################################################ |
|
431 | # Step 7: query reporting period energy saving |
|
432 | ################################################################################################################ |
|
433 | reporting = dict() |
|
434 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
435 | for energy_category_id in energy_category_set: |
|
436 | kgce = energy_category_dict[energy_category_id]['kgce'] |
|
437 | kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
|
438 | ||
439 | reporting[energy_category_id] = dict() |
|
440 | reporting[energy_category_id]['timestamps'] = list() |
|
441 | reporting[energy_category_id]['values_plan'] = list() |
|
442 | reporting[energy_category_id]['values_actual'] = list() |
|
443 | reporting[energy_category_id]['values_saving'] = list() |
|
444 | reporting[energy_category_id]['subtotal_plan'] = Decimal(0.0) |
|
445 | reporting[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
|
446 | reporting[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
|
447 | reporting[energy_category_id]['subtotal_in_kgce_plan'] = Decimal(0.0) |
|
448 | reporting[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
|
449 | reporting[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
|
450 | reporting[energy_category_id]['subtotal_in_kgco2e_plan'] = Decimal(0.0) |
|
451 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
|
452 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
|
453 | # query reporting period's energy plan |
|
454 | cursor_energy_plan.execute(" SELECT start_datetime_utc, actual_value " |
|
455 | " FROM tbl_tenant_input_category_hourly " |
|
456 | " WHERE tenant_id = %s " |
|
457 | " AND energy_category_id = %s " |
|
458 | " AND start_datetime_utc >= %s " |
|
459 | " AND start_datetime_utc < %s " |
|
460 | " ORDER BY start_datetime_utc ", |
|
461 | (tenant['id'], |
|
462 | energy_category_id, |
|
463 | reporting_start_datetime_utc, |
|
464 | reporting_end_datetime_utc)) |
|
465 | rows_tenant_hourly = cursor_energy_plan.fetchall() |
|
466 | ||
467 | rows_tenant_periodically = utilities.aggregate_hourly_data_by_period(rows_tenant_hourly, |
|
468 | reporting_start_datetime_utc, |
|
469 | reporting_end_datetime_utc, |
|
470 | period_type) |
|
471 | for row_tenant_periodically in rows_tenant_periodically: |
|
472 | current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
473 | timedelta(minutes=timezone_offset) |
|
474 | if period_type == 'hourly': |
|
475 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
476 | elif period_type == 'daily': |
|
477 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
478 | elif period_type == 'weekly': |
|
479 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
480 | elif period_type == 'monthly': |
|
481 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
482 | elif period_type == 'yearly': |
|
483 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
484 | ||
485 | plan_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1] |
|
486 | reporting[energy_category_id]['timestamps'].append(current_datetime) |
|
487 | reporting[energy_category_id]['values_plan'].append(plan_value) |
|
488 | reporting[energy_category_id]['subtotal_plan'] += plan_value |
|
489 | reporting[energy_category_id]['subtotal_in_kgce_plan'] += plan_value * kgce |
|
490 | reporting[energy_category_id]['subtotal_in_kgco2e_plan'] += plan_value * kgco2e |
|
491 | ||
492 | # query reporting period's energy actual |
|
493 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
494 | " FROM tbl_tenant_input_category_hourly " |
|
495 | " WHERE tenant_id = %s " |
|
496 | " AND energy_category_id = %s " |
|
497 | " AND start_datetime_utc >= %s " |
|
498 | " AND start_datetime_utc < %s " |
|
499 | " ORDER BY start_datetime_utc ", |
|
500 | (tenant['id'], |
|
501 | energy_category_id, |
|
502 | reporting_start_datetime_utc, |
|
503 | reporting_end_datetime_utc)) |
|
504 | rows_tenant_hourly = cursor_energy.fetchall() |
|
505 | ||
506 | rows_tenant_periodically = utilities.aggregate_hourly_data_by_period(rows_tenant_hourly, |
|
507 | reporting_start_datetime_utc, |
|
508 | reporting_end_datetime_utc, |
|
509 | period_type) |
|
510 | for row_tenant_periodically in rows_tenant_periodically: |
|
511 | current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
512 | timedelta(minutes=timezone_offset) |
|
513 | if period_type == 'hourly': |
|
514 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
515 | elif period_type == 'daily': |
|
516 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
517 | elif period_type == 'weekly': |
|
518 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
519 | elif period_type == 'monthly': |
|
520 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
521 | elif period_type == 'yearly': |
|
522 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
523 | ||
524 | actual_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1] |
|
525 | reporting[energy_category_id]['values_actual'].append(actual_value) |
|
526 | reporting[energy_category_id]['subtotal_actual'] += actual_value |
|
527 | reporting[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
|
528 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
|
529 | ||
530 | # calculate reporting period's energy savings |
|
531 | for i in range(len(reporting[energy_category_id]['values_plan'])): |
|
532 | reporting[energy_category_id]['values_saving'].append( |
|
533 | reporting[energy_category_id]['values_plan'][i] - |
|
534 | reporting[energy_category_id]['values_actual'][i]) |
|
535 | ||
536 | reporting[energy_category_id]['subtotal_saving'] = \ |
|
537 | reporting[energy_category_id]['subtotal_plan'] - \ |
|
538 | reporting[energy_category_id]['subtotal_actual'] |
|
539 | reporting[energy_category_id]['subtotal_in_kgce_saving'] = \ |
|
540 | reporting[energy_category_id]['subtotal_in_kgce_plan'] - \ |
|
541 | reporting[energy_category_id]['subtotal_in_kgce_actual'] |
|
542 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
|
543 | reporting[energy_category_id]['subtotal_in_kgco2e_plan'] - \ |
|
544 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] |
|
545 | ################################################################################################################ |
|
546 | # Step 8: query tariff data |
|
547 | ################################################################################################################ |
|
548 | parameters_data = dict() |
|
549 | parameters_data['names'] = list() |
|
550 | parameters_data['timestamps'] = list() |
|
551 | parameters_data['values'] = list() |
|
552 | if config.is_tariff_appended and energy_category_set is not None and len(energy_category_set) > 0 \ |
|
553 | and not is_quick_mode: |
|
554 | for energy_category_id in energy_category_set: |
|
555 | energy_category_tariff_dict = utilities.get_energy_category_tariffs(tenant['cost_center_id'], |
|
556 | energy_category_id, |
|
557 | reporting_start_datetime_utc, |
|
558 | reporting_end_datetime_utc) |
|
559 | tariff_timestamp_list = list() |
|
560 | tariff_value_list = list() |
|
561 | for k, v in energy_category_tariff_dict.items(): |
|
562 | # convert k from utc to local |
|
563 | k = k + timedelta(minutes=timezone_offset) |
|
564 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
|
565 | tariff_value_list.append(v) |
|
566 | ||
567 | parameters_data['names'].append(_('Tariff') + '-' + energy_category_dict[energy_category_id]['name']) |
|
568 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
569 | parameters_data['values'].append(tariff_value_list) |
|
570 | ||
571 | ################################################################################################################ |
|
572 | # Step 9: query associated sensors and points data |
|
573 | ################################################################################################################ |
|
574 | if not is_quick_mode: |
|
575 | for point in point_list: |
|
576 | point_values = [] |
|
577 | point_timestamps = [] |
|
578 | if point['object_type'] == 'ENERGY_VALUE': |
|
579 | query = (" SELECT utc_date_time, actual_value " |
|
580 | " FROM tbl_energy_value " |
|
581 | " WHERE point_id = %s " |
|
582 | " AND utc_date_time BETWEEN %s AND %s " |
|
583 | " ORDER BY utc_date_time ") |
|
584 | cursor_historical.execute(query, (point['id'], |
|
585 | reporting_start_datetime_utc, |
|
586 | reporting_end_datetime_utc)) |
|
587 | rows = cursor_historical.fetchall() |
|
588 | ||
589 | if rows is not None and len(rows) > 0: |
|
590 | for row in rows: |
|
591 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
592 | timedelta(minutes=timezone_offset) |
|
593 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
594 | point_timestamps.append(current_datetime) |
|
595 | point_values.append(row[1]) |
|
596 | elif point['object_type'] == 'ANALOG_VALUE': |
|
597 | query = (" SELECT utc_date_time, actual_value " |
|
598 | " FROM tbl_analog_value " |
|
599 | " WHERE point_id = %s " |
|
600 | " AND utc_date_time BETWEEN %s AND %s " |
|
601 | " ORDER BY utc_date_time ") |
|
602 | cursor_historical.execute(query, (point['id'], |
|
603 | reporting_start_datetime_utc, |
|
604 | reporting_end_datetime_utc)) |
|
605 | rows = cursor_historical.fetchall() |
|
606 | ||
607 | if rows is not None and len(rows) > 0: |
|
608 | for row in rows: |
|
609 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
610 | timedelta(minutes=timezone_offset) |
|
611 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
612 | point_timestamps.append(current_datetime) |
|
613 | point_values.append(row[1]) |
|
614 | elif point['object_type'] == 'DIGITAL_VALUE': |
|
615 | query = (" SELECT utc_date_time, actual_value " |
|
616 | " FROM tbl_digital_value " |
|
617 | " WHERE point_id = %s " |
|
618 | " AND utc_date_time BETWEEN %s AND %s " |
|
619 | " ORDER BY utc_date_time ") |
|
620 | cursor_historical.execute(query, (point['id'], |
|
621 | reporting_start_datetime_utc, |
|
622 | reporting_end_datetime_utc)) |
|
623 | rows = cursor_historical.fetchall() |
|
624 | ||
625 | if rows is not None and len(rows) > 0: |
|
626 | for row in rows: |
|
627 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
628 | timedelta(minutes=timezone_offset) |
|
629 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
630 | point_timestamps.append(current_datetime) |
|
631 | point_values.append(row[1]) |
|
632 | ||
633 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
|
634 | parameters_data['timestamps'].append(point_timestamps) |
|
635 | parameters_data['values'].append(point_values) |
|
636 | ||
637 | ################################################################################################################ |
|
638 | # Step 10: construct the report |
|
639 | ################################################################################################################ |
|
640 | if cursor_system: |
|
641 | cursor_system.close() |
|
642 | if cnx_system: |
|
643 | cnx_system.close() |
|
644 | ||
645 | if cursor_energy: |
|
646 | cursor_energy.close() |
|
647 | if cnx_energy: |
|
648 | cnx_energy.close() |
|
649 | ||
650 | if cursor_energy_plan: |
|
651 | cursor_energy_plan.close() |
|
652 | if cnx_energy_plan: |
|
653 | cnx_energy_plan.close() |
|
654 | ||
655 | if cursor_historical: |
|
656 | cursor_historical.close() |
|
657 | if cnx_historical: |
|
658 | cnx_historical.close() |
|
659 | ||
660 | result = dict() |
|
661 | ||
662 | result['tenant'] = dict() |
|
663 | result['tenant']['name'] = tenant['name'] |
|
664 | result['tenant']['area'] = tenant['area'] |
|
665 | ||
666 | result['base_period'] = dict() |
|
667 | result['base_period']['names'] = list() |
|
668 | result['base_period']['units'] = list() |
|
669 | result['base_period']['timestamps'] = list() |
|
670 | result['base_period']['values_saving'] = list() |
|
671 | result['base_period']['subtotals_saving'] = list() |
|
672 | result['base_period']['subtotals_in_kgce_saving'] = list() |
|
673 | result['base_period']['subtotals_in_kgco2e_saving'] = list() |
|
674 | result['base_period']['total_in_kgce_saving'] = Decimal(0.0) |
|
675 | result['base_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
|
676 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
677 | for energy_category_id in energy_category_set: |
|
678 | result['base_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
679 | result['base_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
680 | result['base_period']['timestamps'].append(base[energy_category_id]['timestamps']) |
|
681 | result['base_period']['values_saving'].append(base[energy_category_id]['values_saving']) |
|
682 | result['base_period']['subtotals_saving'].append(base[energy_category_id]['subtotal_saving']) |
|
683 | result['base_period']['subtotals_in_kgce_saving'].append( |
|
684 | base[energy_category_id]['subtotal_in_kgce_saving']) |
|
685 | result['base_period']['subtotals_in_kgco2e_saving'].append( |
|
686 | base[energy_category_id]['subtotal_in_kgco2e_saving']) |
|
687 | result['base_period']['total_in_kgce_saving'] += base[energy_category_id]['subtotal_in_kgce_saving'] |
|
688 | result['base_period']['total_in_kgco2e_saving'] += base[energy_category_id]['subtotal_in_kgco2e_saving'] |
|
689 | ||
690 | result['reporting_period'] = dict() |
|
691 | result['reporting_period']['names'] = list() |
|
692 | result['reporting_period']['energy_category_ids'] = list() |
|
693 | result['reporting_period']['units'] = list() |
|
694 | result['reporting_period']['timestamps'] = list() |
|
695 | result['reporting_period']['values_saving'] = list() |
|
696 | result['reporting_period']['rates_saving'] = list() |
|
697 | result['reporting_period']['subtotals_saving'] = list() |
|
698 | result['reporting_period']['subtotals_in_kgce_saving'] = list() |
|
699 | result['reporting_period']['subtotals_in_kgco2e_saving'] = list() |
|
700 | result['reporting_period']['subtotals_per_unit_area_saving'] = list() |
|
701 | result['reporting_period']['increment_rates_saving'] = list() |
|
702 | result['reporting_period']['total_in_kgce_saving'] = Decimal(0.0) |
|
703 | result['reporting_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
|
704 | result['reporting_period']['increment_rate_in_kgce_saving'] = Decimal(0.0) |
|
705 | result['reporting_period']['increment_rate_in_kgco2e_saving'] = Decimal(0.0) |
|
706 | ||
707 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
708 | for energy_category_id in energy_category_set: |
|
709 | result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
710 | result['reporting_period']['energy_category_ids'].append(energy_category_id) |
|
711 | result['reporting_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
712 | result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps']) |
|
713 | result['reporting_period']['values_saving'].append(reporting[energy_category_id]['values_saving']) |
|
714 | result['reporting_period']['subtotals_saving'].append(reporting[energy_category_id]['subtotal_saving']) |
|
715 | result['reporting_period']['subtotals_in_kgce_saving'].append( |
|
716 | reporting[energy_category_id]['subtotal_in_kgce_saving']) |
|
717 | result['reporting_period']['subtotals_in_kgco2e_saving'].append( |
|
718 | reporting[energy_category_id]['subtotal_in_kgco2e_saving']) |
|
719 | result['reporting_period']['subtotals_per_unit_area_saving'].append( |
|
720 | reporting[energy_category_id]['subtotal_saving'] / tenant['area'] |
|
721 | if tenant['area'] != Decimal(0.0) else None) |
|
722 | result['reporting_period']['increment_rates_saving'].append( |
|
723 | (reporting[energy_category_id]['subtotal_saving'] - base[energy_category_id]['subtotal_saving']) / |
|
724 | base[energy_category_id]['subtotal_saving'] |
|
725 | if base[energy_category_id]['subtotal_saving'] != Decimal(0.0) else None) |
|
726 | result['reporting_period']['total_in_kgce_saving'] += \ |
|
727 | reporting[energy_category_id]['subtotal_in_kgce_saving'] |
|
728 | result['reporting_period']['total_in_kgco2e_saving'] += \ |
|
729 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] |
|
730 | ||
731 | rate = list() |
|
732 | for index, value in enumerate(reporting[energy_category_id]['values_saving']): |
|
733 | if index < len(base[energy_category_id]['values_saving']) \ |
|
734 | and base[energy_category_id]['values_saving'][index] != Decimal(0.0) \ |
|
735 | and value != Decimal(0.0): |
|
736 | rate.append((value - base[energy_category_id]['values_saving'][index]) |
|
737 | / base[energy_category_id]['values_saving'][index]) |
|
738 | else: |
|
739 | rate.append(None) |
|
740 | result['reporting_period']['rates_saving'].append(rate) |
|
741 | ||
742 | result['reporting_period']['total_in_kgco2e_per_unit_area_saving'] = \ |
|
743 | result['reporting_period']['total_in_kgce_saving'] / tenant['area'] \ |
|
744 | if tenant['area'] != Decimal(0.0) else None |
|
745 | ||
746 | result['reporting_period']['increment_rate_in_kgce_saving'] = \ |
|
747 | (result['reporting_period']['total_in_kgce_saving'] - result['base_period']['total_in_kgce_saving']) / \ |
|
748 | result['base_period']['total_in_kgce_saving'] \ |
|
749 | if result['base_period']['total_in_kgce_saving'] != Decimal(0.0) else None |
|
750 | ||
751 | result['reporting_period']['total_in_kgce_per_unit_area_saving'] = \ |
|
752 | result['reporting_period']['total_in_kgco2e_saving'] / tenant['area'] if tenant['area'] > 0.0 else None |
|
753 | ||
754 | result['reporting_period']['increment_rate_in_kgco2e_saving'] = \ |
|
755 | (result['reporting_period']['total_in_kgco2e_saving'] - result['base_period']['total_in_kgco2e_saving']) / \ |
|
756 | result['base_period']['total_in_kgco2e_saving'] \ |
|
757 | if result['base_period']['total_in_kgco2e_saving'] != Decimal(0.0) else None |
|
758 | ||
759 | result['parameters'] = { |
|
760 | "names": parameters_data['names'], |
|
761 | "timestamps": parameters_data['timestamps'], |
|
762 | "values": parameters_data['values'] |
|
763 | } |
|
764 | ||
765 | # export result to Excel file and then encode the file to base64 string |
|
766 | if not is_quick_mode: |
|
767 | result['excel_bytes_base64'] = excelexporters.tenantplan.export(result, |
|
768 | tenant['name'], |
|
769 | base_period_start_datetime_local, |
|
770 | base_period_end_datetime_local, |
|
771 | reporting_period_start_datetime_local, |
|
772 | reporting_period_end_datetime_local, |
|
773 | period_type, |
|
774 | language) |
|
775 | ||
776 | resp.text = json.dumps(result) |
|
777 |
@@ 13-776 (lines=764) @@ | ||
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 store |
|
27 | # Step 3: query energy categories |
|
28 | # Step 4: query associated sensors |
|
29 | # Step 5: query associated points |
|
30 | # Step 6: query base period energy saving |
|
31 | # Step 7: query reporting period energy saving |
|
32 | # Step 8: query tariff data |
|
33 | # Step 9: query associated sensors and 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 | store_id = req.params.get('storeid') |
|
46 | store_uuid = req.params.get('storeuuid') |
|
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 store_id is None and store_uuid is None: |
|
59 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
60 | title='API.BAD_REQUEST', |
|
61 | description='API.INVALID_STORE_ID') |
|
62 | ||
63 | if store_id is not None: |
|
64 | store_id = str.strip(store_id) |
|
65 | if not store_id.isdigit() or int(store_id) <= 0: |
|
66 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
67 | title='API.BAD_REQUEST', |
|
68 | description='API.INVALID_STORE_ID') |
|
69 | ||
70 | if store_uuid is not None: |
|
71 | 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) |
|
72 | match = regex.match(str.strip(store_uuid)) |
|
73 | if not bool(match): |
|
74 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
75 | title='API.BAD_REQUEST', |
|
76 | description='API.INVALID_STORE_UUID') |
|
77 | ||
78 | if period_type is None: |
|
79 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
80 | description='API.INVALID_PERIOD_TYPE') |
|
81 | else: |
|
82 | period_type = str.strip(period_type) |
|
83 | if period_type not in ['hourly', 'daily', 'weekly', 'monthly', 'yearly']: |
|
84 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
85 | description='API.INVALID_PERIOD_TYPE') |
|
86 | ||
87 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
|
88 | if config.utc_offset[0] == '-': |
|
89 | timezone_offset = -timezone_offset |
|
90 | ||
91 | base_start_datetime_utc = None |
|
92 | if base_period_start_datetime_local is not None and len(str.strip(base_period_start_datetime_local)) > 0: |
|
93 | base_period_start_datetime_local = str.strip(base_period_start_datetime_local) |
|
94 | try: |
|
95 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
96 | except ValueError: |
|
97 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
98 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
|
99 | base_start_datetime_utc = \ |
|
100 | base_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
101 | # nomalize the start datetime |
|
102 | if config.minutes_to_count == 30 and base_start_datetime_utc.minute >= 30: |
|
103 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
|
104 | else: |
|
105 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
|
106 | ||
107 | base_end_datetime_utc = None |
|
108 | if base_period_end_datetime_local is not None and len(str.strip(base_period_end_datetime_local)) > 0: |
|
109 | base_period_end_datetime_local = str.strip(base_period_end_datetime_local) |
|
110 | try: |
|
111 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
112 | except ValueError: |
|
113 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
114 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
|
115 | base_end_datetime_utc = \ |
|
116 | base_end_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
117 | ||
118 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
|
119 | base_start_datetime_utc >= base_end_datetime_utc: |
|
120 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
121 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
|
122 | ||
123 | if reporting_period_start_datetime_local is None: |
|
124 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
125 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
126 | else: |
|
127 | reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) |
|
128 | try: |
|
129 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, |
|
130 | '%Y-%m-%dT%H:%M:%S') |
|
131 | except ValueError: |
|
132 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
133 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
134 | reporting_start_datetime_utc = \ |
|
135 | reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
136 | # nomalize the start datetime |
|
137 | if config.minutes_to_count == 30 and reporting_start_datetime_utc.minute >= 30: |
|
138 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
|
139 | else: |
|
140 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
|
141 | ||
142 | if reporting_period_end_datetime_local is None: |
|
143 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
144 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
145 | else: |
|
146 | reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) |
|
147 | try: |
|
148 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, |
|
149 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
150 | timedelta(minutes=timezone_offset) |
|
151 | except ValueError: |
|
152 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
153 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
154 | ||
155 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
|
156 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
157 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
|
158 | ||
159 | # if turn quick mode on, do not return parameters data and excel file |
|
160 | is_quick_mode = False |
|
161 | if quick_mode is not None and \ |
|
162 | len(str.strip(quick_mode)) > 0 and \ |
|
163 | str.lower(str.strip(quick_mode)) in ('true', 't', 'on', 'yes', 'y'): |
|
164 | is_quick_mode = True |
|
165 | ||
166 | trans = utilities.get_translation(language) |
|
167 | trans.install() |
|
168 | _ = trans.gettext |
|
169 | ||
170 | ################################################################################################################ |
|
171 | # Step 2: query the store |
|
172 | ################################################################################################################ |
|
173 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
|
174 | cursor_system = cnx_system.cursor() |
|
175 | ||
176 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
|
177 | cursor_energy = cnx_energy.cursor() |
|
178 | ||
179 | cnx_energy_baseline = mysql.connector.connect(**config.myems_energy_baseline_db) |
|
180 | cursor_energy_baseline = cnx_energy_baseline.cursor() |
|
181 | ||
182 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
|
183 | cursor_historical = cnx_historical.cursor() |
|
184 | ||
185 | if store_id is not None: |
|
186 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
187 | " FROM tbl_stores " |
|
188 | " WHERE id = %s ", (store_id,)) |
|
189 | row_store = cursor_system.fetchone() |
|
190 | elif store_uuid is not None: |
|
191 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
192 | " FROM tbl_stores " |
|
193 | " WHERE uuid = %s ", (store_uuid,)) |
|
194 | row_store = cursor_system.fetchone() |
|
195 | ||
196 | if row_store is None: |
|
197 | if cursor_system: |
|
198 | cursor_system.close() |
|
199 | if cnx_system: |
|
200 | cnx_system.close() |
|
201 | ||
202 | if cursor_energy: |
|
203 | cursor_energy.close() |
|
204 | if cnx_energy: |
|
205 | cnx_energy.close() |
|
206 | ||
207 | if cursor_energy_baseline: |
|
208 | cursor_energy_baseline.close() |
|
209 | if cnx_energy_baseline: |
|
210 | cnx_energy_baseline.close() |
|
211 | ||
212 | if cursor_historical: |
|
213 | cursor_historical.close() |
|
214 | if cnx_historical: |
|
215 | cnx_historical.close() |
|
216 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', description='API.STORE_NOT_FOUND') |
|
217 | ||
218 | store = dict() |
|
219 | store['id'] = row_store[0] |
|
220 | store['name'] = row_store[1] |
|
221 | store['area'] = row_store[2] |
|
222 | store['cost_center_id'] = row_store[3] |
|
223 | ||
224 | ################################################################################################################ |
|
225 | # Step 3: query energy categories |
|
226 | ################################################################################################################ |
|
227 | energy_category_set = set() |
|
228 | # query energy categories in base period |
|
229 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
230 | " FROM tbl_store_input_category_hourly " |
|
231 | " WHERE store_id = %s " |
|
232 | " AND start_datetime_utc >= %s " |
|
233 | " AND start_datetime_utc < %s ", |
|
234 | (store['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
235 | rows_energy_categories = cursor_energy.fetchall() |
|
236 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
|
237 | for row_energy_category in rows_energy_categories: |
|
238 | energy_category_set.add(row_energy_category[0]) |
|
239 | ||
240 | # query energy categories in reporting period |
|
241 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
242 | " FROM tbl_store_input_category_hourly " |
|
243 | " WHERE store_id = %s " |
|
244 | " AND start_datetime_utc >= %s " |
|
245 | " AND start_datetime_utc < %s ", |
|
246 | (store['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
247 | rows_energy_categories = cursor_energy.fetchall() |
|
248 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
|
249 | for row_energy_category in rows_energy_categories: |
|
250 | energy_category_set.add(row_energy_category[0]) |
|
251 | ||
252 | # query all energy categories in base period and reporting period |
|
253 | cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e " |
|
254 | " FROM tbl_energy_categories " |
|
255 | " ORDER BY id ", ) |
|
256 | rows_energy_categories = cursor_system.fetchall() |
|
257 | if rows_energy_categories is None or len(rows_energy_categories) == 0: |
|
258 | if cursor_system: |
|
259 | cursor_system.close() |
|
260 | if cnx_system: |
|
261 | cnx_system.close() |
|
262 | ||
263 | if cursor_energy: |
|
264 | cursor_energy.close() |
|
265 | if cnx_energy: |
|
266 | cnx_energy.close() |
|
267 | ||
268 | if cursor_energy_baseline: |
|
269 | cursor_energy_baseline.close() |
|
270 | if cnx_energy_baseline: |
|
271 | cnx_energy_baseline.close() |
|
272 | ||
273 | if cursor_historical: |
|
274 | cursor_historical.close() |
|
275 | if cnx_historical: |
|
276 | cnx_historical.close() |
|
277 | raise falcon.HTTPError(status=falcon.HTTP_404, |
|
278 | title='API.NOT_FOUND', |
|
279 | description='API.ENERGY_CATEGORY_NOT_FOUND') |
|
280 | energy_category_dict = dict() |
|
281 | for row_energy_category in rows_energy_categories: |
|
282 | if row_energy_category[0] in energy_category_set: |
|
283 | energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1], |
|
284 | "unit_of_measure": row_energy_category[2], |
|
285 | "kgce": row_energy_category[3], |
|
286 | "kgco2e": row_energy_category[4]} |
|
287 | ||
288 | ################################################################################################################ |
|
289 | # Step 4: query associated sensors |
|
290 | ################################################################################################################ |
|
291 | point_list = list() |
|
292 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
293 | " FROM tbl_stores st, tbl_sensors se, tbl_stores_sensors ss, " |
|
294 | " tbl_points p, tbl_sensors_points sp " |
|
295 | " WHERE st.id = %s AND st.id = ss.store_id AND ss.sensor_id = se.id " |
|
296 | " AND se.id = sp.sensor_id AND sp.point_id = p.id " |
|
297 | " ORDER BY p.id ", (store['id'],)) |
|
298 | rows_points = cursor_system.fetchall() |
|
299 | if rows_points is not None and len(rows_points) > 0: |
|
300 | for row in rows_points: |
|
301 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
302 | ||
303 | ################################################################################################################ |
|
304 | # Step 5: query associated points |
|
305 | ################################################################################################################ |
|
306 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
307 | " FROM tbl_stores s, tbl_stores_points sp, tbl_points p " |
|
308 | " WHERE s.id = %s AND s.id = sp.store_id AND sp.point_id = p.id " |
|
309 | " ORDER BY p.id ", (store['id'],)) |
|
310 | rows_points = cursor_system.fetchall() |
|
311 | if rows_points is not None and len(rows_points) > 0: |
|
312 | for row in rows_points: |
|
313 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
314 | ||
315 | ################################################################################################################ |
|
316 | # Step 6: query base period energy saving |
|
317 | ################################################################################################################ |
|
318 | base = dict() |
|
319 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
320 | for energy_category_id in energy_category_set: |
|
321 | kgce = energy_category_dict[energy_category_id]['kgce'] |
|
322 | kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
|
323 | ||
324 | base[energy_category_id] = dict() |
|
325 | base[energy_category_id]['timestamps'] = list() |
|
326 | base[energy_category_id]['values_baseline'] = list() |
|
327 | base[energy_category_id]['values_actual'] = list() |
|
328 | base[energy_category_id]['values_saving'] = list() |
|
329 | base[energy_category_id]['subtotal_baseline'] = Decimal(0.0) |
|
330 | base[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
|
331 | base[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
|
332 | base[energy_category_id]['subtotal_in_kgce_baseline'] = Decimal(0.0) |
|
333 | base[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
|
334 | base[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
|
335 | base[energy_category_id]['subtotal_in_kgco2e_baseline'] = Decimal(0.0) |
|
336 | base[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
|
337 | base[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
|
338 | # query base period's energy baseline |
|
339 | cursor_energy_baseline.execute(" SELECT start_datetime_utc, actual_value " |
|
340 | " FROM tbl_store_input_category_hourly " |
|
341 | " WHERE store_id = %s " |
|
342 | " AND energy_category_id = %s " |
|
343 | " AND start_datetime_utc >= %s " |
|
344 | " AND start_datetime_utc < %s " |
|
345 | " ORDER BY start_datetime_utc ", |
|
346 | (store['id'], |
|
347 | energy_category_id, |
|
348 | base_start_datetime_utc, |
|
349 | base_end_datetime_utc)) |
|
350 | rows_store_hourly = cursor_energy_baseline.fetchall() |
|
351 | ||
352 | rows_store_periodically = utilities.aggregate_hourly_data_by_period(rows_store_hourly, |
|
353 | base_start_datetime_utc, |
|
354 | base_end_datetime_utc, |
|
355 | period_type) |
|
356 | for row_store_periodically in rows_store_periodically: |
|
357 | current_datetime_local = row_store_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
358 | timedelta(minutes=timezone_offset) |
|
359 | if period_type == 'hourly': |
|
360 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
361 | elif period_type == 'daily': |
|
362 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
363 | elif period_type == 'weekly': |
|
364 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
365 | elif period_type == 'monthly': |
|
366 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
367 | elif period_type == 'yearly': |
|
368 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
369 | ||
370 | baseline_value = Decimal(0.0) if row_store_periodically[1] is None else row_store_periodically[1] |
|
371 | base[energy_category_id]['timestamps'].append(current_datetime) |
|
372 | base[energy_category_id]['values_baseline'].append(baseline_value) |
|
373 | base[energy_category_id]['subtotal_baseline'] += baseline_value |
|
374 | base[energy_category_id]['subtotal_in_kgce_baseline'] += baseline_value * kgce |
|
375 | base[energy_category_id]['subtotal_in_kgco2e_baseline'] += baseline_value * kgco2e |
|
376 | ||
377 | # query base period's energy actual |
|
378 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
379 | " FROM tbl_store_input_category_hourly " |
|
380 | " WHERE store_id = %s " |
|
381 | " AND energy_category_id = %s " |
|
382 | " AND start_datetime_utc >= %s " |
|
383 | " AND start_datetime_utc < %s " |
|
384 | " ORDER BY start_datetime_utc ", |
|
385 | (store['id'], |
|
386 | energy_category_id, |
|
387 | base_start_datetime_utc, |
|
388 | base_end_datetime_utc)) |
|
389 | rows_store_hourly = cursor_energy.fetchall() |
|
390 | ||
391 | rows_store_periodically = utilities.aggregate_hourly_data_by_period(rows_store_hourly, |
|
392 | base_start_datetime_utc, |
|
393 | base_end_datetime_utc, |
|
394 | period_type) |
|
395 | for row_store_periodically in rows_store_periodically: |
|
396 | current_datetime_local = row_store_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
397 | timedelta(minutes=timezone_offset) |
|
398 | if period_type == 'hourly': |
|
399 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
400 | elif period_type == 'daily': |
|
401 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
402 | elif period_type == 'weekly': |
|
403 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
404 | elif period_type == 'monthly': |
|
405 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
406 | elif period_type == 'yearly': |
|
407 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
408 | ||
409 | actual_value = Decimal(0.0) if row_store_periodically[1] is None else row_store_periodically[1] |
|
410 | base[energy_category_id]['values_actual'].append(actual_value) |
|
411 | base[energy_category_id]['subtotal_actual'] += actual_value |
|
412 | base[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
|
413 | base[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
|
414 | ||
415 | # calculate base period's energy savings |
|
416 | for i in range(len(base[energy_category_id]['values_baseline'])): |
|
417 | base[energy_category_id]['values_saving'].append( |
|
418 | base[energy_category_id]['values_baseline'][i] - |
|
419 | base[energy_category_id]['values_actual'][i]) |
|
420 | ||
421 | base[energy_category_id]['subtotal_saving'] = \ |
|
422 | base[energy_category_id]['subtotal_baseline'] - \ |
|
423 | base[energy_category_id]['subtotal_actual'] |
|
424 | base[energy_category_id]['subtotal_in_kgce_saving'] = \ |
|
425 | base[energy_category_id]['subtotal_in_kgce_baseline'] - \ |
|
426 | base[energy_category_id]['subtotal_in_kgce_actual'] |
|
427 | base[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
|
428 | base[energy_category_id]['subtotal_in_kgco2e_baseline'] - \ |
|
429 | base[energy_category_id]['subtotal_in_kgco2e_actual'] |
|
430 | ################################################################################################################ |
|
431 | # Step 7: query reporting period energy saving |
|
432 | ################################################################################################################ |
|
433 | reporting = dict() |
|
434 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
435 | for energy_category_id in energy_category_set: |
|
436 | kgce = energy_category_dict[energy_category_id]['kgce'] |
|
437 | kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
|
438 | ||
439 | reporting[energy_category_id] = dict() |
|
440 | reporting[energy_category_id]['timestamps'] = list() |
|
441 | reporting[energy_category_id]['values_baseline'] = list() |
|
442 | reporting[energy_category_id]['values_actual'] = list() |
|
443 | reporting[energy_category_id]['values_saving'] = list() |
|
444 | reporting[energy_category_id]['subtotal_baseline'] = Decimal(0.0) |
|
445 | reporting[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
|
446 | reporting[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
|
447 | reporting[energy_category_id]['subtotal_in_kgce_baseline'] = Decimal(0.0) |
|
448 | reporting[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
|
449 | reporting[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
|
450 | reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] = Decimal(0.0) |
|
451 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
|
452 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
|
453 | # query reporting period's energy baseline |
|
454 | cursor_energy_baseline.execute(" SELECT start_datetime_utc, actual_value " |
|
455 | " FROM tbl_store_input_category_hourly " |
|
456 | " WHERE store_id = %s " |
|
457 | " AND energy_category_id = %s " |
|
458 | " AND start_datetime_utc >= %s " |
|
459 | " AND start_datetime_utc < %s " |
|
460 | " ORDER BY start_datetime_utc ", |
|
461 | (store['id'], |
|
462 | energy_category_id, |
|
463 | reporting_start_datetime_utc, |
|
464 | reporting_end_datetime_utc)) |
|
465 | rows_store_hourly = cursor_energy_baseline.fetchall() |
|
466 | ||
467 | rows_store_periodically = utilities.aggregate_hourly_data_by_period(rows_store_hourly, |
|
468 | reporting_start_datetime_utc, |
|
469 | reporting_end_datetime_utc, |
|
470 | period_type) |
|
471 | for row_store_periodically in rows_store_periodically: |
|
472 | current_datetime_local = row_store_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
473 | timedelta(minutes=timezone_offset) |
|
474 | if period_type == 'hourly': |
|
475 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
476 | elif period_type == 'daily': |
|
477 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
478 | elif period_type == 'weekly': |
|
479 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
480 | elif period_type == 'monthly': |
|
481 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
482 | elif period_type == 'yearly': |
|
483 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
484 | ||
485 | baseline_value = Decimal(0.0) if row_store_periodically[1] is None else row_store_periodically[1] |
|
486 | reporting[energy_category_id]['timestamps'].append(current_datetime) |
|
487 | reporting[energy_category_id]['values_baseline'].append(baseline_value) |
|
488 | reporting[energy_category_id]['subtotal_baseline'] += baseline_value |
|
489 | reporting[energy_category_id]['subtotal_in_kgce_baseline'] += baseline_value * kgce |
|
490 | reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] += baseline_value * kgco2e |
|
491 | ||
492 | # query reporting period's energy actual |
|
493 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
494 | " FROM tbl_store_input_category_hourly " |
|
495 | " WHERE store_id = %s " |
|
496 | " AND energy_category_id = %s " |
|
497 | " AND start_datetime_utc >= %s " |
|
498 | " AND start_datetime_utc < %s " |
|
499 | " ORDER BY start_datetime_utc ", |
|
500 | (store['id'], |
|
501 | energy_category_id, |
|
502 | reporting_start_datetime_utc, |
|
503 | reporting_end_datetime_utc)) |
|
504 | rows_store_hourly = cursor_energy.fetchall() |
|
505 | ||
506 | rows_store_periodically = utilities.aggregate_hourly_data_by_period(rows_store_hourly, |
|
507 | reporting_start_datetime_utc, |
|
508 | reporting_end_datetime_utc, |
|
509 | period_type) |
|
510 | for row_store_periodically in rows_store_periodically: |
|
511 | current_datetime_local = row_store_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
512 | timedelta(minutes=timezone_offset) |
|
513 | if period_type == 'hourly': |
|
514 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
515 | elif period_type == 'daily': |
|
516 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
517 | elif period_type == 'weekly': |
|
518 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
519 | elif period_type == 'monthly': |
|
520 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
521 | elif period_type == 'yearly': |
|
522 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
523 | ||
524 | actual_value = Decimal(0.0) if row_store_periodically[1] is None else row_store_periodically[1] |
|
525 | reporting[energy_category_id]['values_actual'].append(actual_value) |
|
526 | reporting[energy_category_id]['subtotal_actual'] += actual_value |
|
527 | reporting[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
|
528 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
|
529 | ||
530 | # calculate reporting period's energy savings |
|
531 | for i in range(len(reporting[energy_category_id]['values_baseline'])): |
|
532 | reporting[energy_category_id]['values_saving'].append( |
|
533 | reporting[energy_category_id]['values_baseline'][i] - |
|
534 | reporting[energy_category_id]['values_actual'][i]) |
|
535 | ||
536 | reporting[energy_category_id]['subtotal_saving'] = \ |
|
537 | reporting[energy_category_id]['subtotal_baseline'] - \ |
|
538 | reporting[energy_category_id]['subtotal_actual'] |
|
539 | reporting[energy_category_id]['subtotal_in_kgce_saving'] = \ |
|
540 | reporting[energy_category_id]['subtotal_in_kgce_baseline'] - \ |
|
541 | reporting[energy_category_id]['subtotal_in_kgce_actual'] |
|
542 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
|
543 | reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] - \ |
|
544 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] |
|
545 | ################################################################################################################ |
|
546 | # Step 8: query tariff data |
|
547 | ################################################################################################################ |
|
548 | parameters_data = dict() |
|
549 | parameters_data['names'] = list() |
|
550 | parameters_data['timestamps'] = list() |
|
551 | parameters_data['values'] = list() |
|
552 | if config.is_tariff_appended and energy_category_set is not None and len(energy_category_set) > 0 \ |
|
553 | and not is_quick_mode: |
|
554 | for energy_category_id in energy_category_set: |
|
555 | energy_category_tariff_dict = utilities.get_energy_category_tariffs(store['cost_center_id'], |
|
556 | energy_category_id, |
|
557 | reporting_start_datetime_utc, |
|
558 | reporting_end_datetime_utc) |
|
559 | tariff_timestamp_list = list() |
|
560 | tariff_value_list = list() |
|
561 | for k, v in energy_category_tariff_dict.items(): |
|
562 | # convert k from utc to local |
|
563 | k = k + timedelta(minutes=timezone_offset) |
|
564 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
|
565 | tariff_value_list.append(v) |
|
566 | ||
567 | parameters_data['names'].append(_('Tariff') + '-' + energy_category_dict[energy_category_id]['name']) |
|
568 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
569 | parameters_data['values'].append(tariff_value_list) |
|
570 | ||
571 | ################################################################################################################ |
|
572 | # Step 9: query associated sensors and points data |
|
573 | ################################################################################################################ |
|
574 | if not is_quick_mode: |
|
575 | for point in point_list: |
|
576 | point_values = [] |
|
577 | point_timestamps = [] |
|
578 | if point['object_type'] == 'ENERGY_VALUE': |
|
579 | query = (" SELECT utc_date_time, actual_value " |
|
580 | " FROM tbl_energy_value " |
|
581 | " WHERE point_id = %s " |
|
582 | " AND utc_date_time BETWEEN %s AND %s " |
|
583 | " ORDER BY utc_date_time ") |
|
584 | cursor_historical.execute(query, (point['id'], |
|
585 | reporting_start_datetime_utc, |
|
586 | reporting_end_datetime_utc)) |
|
587 | rows = cursor_historical.fetchall() |
|
588 | ||
589 | if rows is not None and len(rows) > 0: |
|
590 | for row in rows: |
|
591 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
592 | timedelta(minutes=timezone_offset) |
|
593 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
594 | point_timestamps.append(current_datetime) |
|
595 | point_values.append(row[1]) |
|
596 | elif point['object_type'] == 'ANALOG_VALUE': |
|
597 | query = (" SELECT utc_date_time, actual_value " |
|
598 | " FROM tbl_analog_value " |
|
599 | " WHERE point_id = %s " |
|
600 | " AND utc_date_time BETWEEN %s AND %s " |
|
601 | " ORDER BY utc_date_time ") |
|
602 | cursor_historical.execute(query, (point['id'], |
|
603 | reporting_start_datetime_utc, |
|
604 | reporting_end_datetime_utc)) |
|
605 | rows = cursor_historical.fetchall() |
|
606 | ||
607 | if rows is not None and len(rows) > 0: |
|
608 | for row in rows: |
|
609 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
610 | timedelta(minutes=timezone_offset) |
|
611 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
612 | point_timestamps.append(current_datetime) |
|
613 | point_values.append(row[1]) |
|
614 | elif point['object_type'] == 'DIGITAL_VALUE': |
|
615 | query = (" SELECT utc_date_time, actual_value " |
|
616 | " FROM tbl_digital_value " |
|
617 | " WHERE point_id = %s " |
|
618 | " AND utc_date_time BETWEEN %s AND %s " |
|
619 | " ORDER BY utc_date_time ") |
|
620 | cursor_historical.execute(query, (point['id'], |
|
621 | reporting_start_datetime_utc, |
|
622 | reporting_end_datetime_utc)) |
|
623 | rows = cursor_historical.fetchall() |
|
624 | ||
625 | if rows is not None and len(rows) > 0: |
|
626 | for row in rows: |
|
627 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
628 | timedelta(minutes=timezone_offset) |
|
629 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
630 | point_timestamps.append(current_datetime) |
|
631 | point_values.append(row[1]) |
|
632 | ||
633 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
|
634 | parameters_data['timestamps'].append(point_timestamps) |
|
635 | parameters_data['values'].append(point_values) |
|
636 | ||
637 | ################################################################################################################ |
|
638 | # Step 10: construct the report |
|
639 | ################################################################################################################ |
|
640 | if cursor_system: |
|
641 | cursor_system.close() |
|
642 | if cnx_system: |
|
643 | cnx_system.close() |
|
644 | ||
645 | if cursor_energy: |
|
646 | cursor_energy.close() |
|
647 | if cnx_energy: |
|
648 | cnx_energy.close() |
|
649 | ||
650 | if cursor_energy_baseline: |
|
651 | cursor_energy_baseline.close() |
|
652 | if cnx_energy_baseline: |
|
653 | cnx_energy_baseline.close() |
|
654 | ||
655 | if cursor_historical: |
|
656 | cursor_historical.close() |
|
657 | if cnx_historical: |
|
658 | cnx_historical.close() |
|
659 | ||
660 | result = dict() |
|
661 | ||
662 | result['store'] = dict() |
|
663 | result['store']['name'] = store['name'] |
|
664 | result['store']['area'] = store['area'] |
|
665 | ||
666 | result['base_period'] = dict() |
|
667 | result['base_period']['names'] = list() |
|
668 | result['base_period']['units'] = list() |
|
669 | result['base_period']['timestamps'] = list() |
|
670 | result['base_period']['values_saving'] = list() |
|
671 | result['base_period']['subtotals_saving'] = list() |
|
672 | result['base_period']['subtotals_in_kgce_saving'] = list() |
|
673 | result['base_period']['subtotals_in_kgco2e_saving'] = list() |
|
674 | result['base_period']['total_in_kgce_saving'] = Decimal(0.0) |
|
675 | result['base_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
|
676 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
677 | for energy_category_id in energy_category_set: |
|
678 | result['base_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
679 | result['base_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
680 | result['base_period']['timestamps'].append(base[energy_category_id]['timestamps']) |
|
681 | result['base_period']['values_saving'].append(base[energy_category_id]['values_saving']) |
|
682 | result['base_period']['subtotals_saving'].append(base[energy_category_id]['subtotal_saving']) |
|
683 | result['base_period']['subtotals_in_kgce_saving'].append( |
|
684 | base[energy_category_id]['subtotal_in_kgce_saving']) |
|
685 | result['base_period']['subtotals_in_kgco2e_saving'].append( |
|
686 | base[energy_category_id]['subtotal_in_kgco2e_saving']) |
|
687 | result['base_period']['total_in_kgce_saving'] += base[energy_category_id]['subtotal_in_kgce_saving'] |
|
688 | result['base_period']['total_in_kgco2e_saving'] += base[energy_category_id]['subtotal_in_kgco2e_saving'] |
|
689 | ||
690 | result['reporting_period'] = dict() |
|
691 | result['reporting_period']['names'] = list() |
|
692 | result['reporting_period']['energy_category_ids'] = list() |
|
693 | result['reporting_period']['units'] = list() |
|
694 | result['reporting_period']['timestamps'] = list() |
|
695 | result['reporting_period']['values_saving'] = list() |
|
696 | result['reporting_period']['rates_saving'] = list() |
|
697 | result['reporting_period']['subtotals_saving'] = list() |
|
698 | result['reporting_period']['subtotals_in_kgce_saving'] = list() |
|
699 | result['reporting_period']['subtotals_in_kgco2e_saving'] = list() |
|
700 | result['reporting_period']['subtotals_per_unit_area_saving'] = list() |
|
701 | result['reporting_period']['increment_rates_saving'] = list() |
|
702 | result['reporting_period']['total_in_kgce_saving'] = Decimal(0.0) |
|
703 | result['reporting_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
|
704 | result['reporting_period']['increment_rate_in_kgce_saving'] = Decimal(0.0) |
|
705 | result['reporting_period']['increment_rate_in_kgco2e_saving'] = Decimal(0.0) |
|
706 | ||
707 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
708 | for energy_category_id in energy_category_set: |
|
709 | result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
710 | result['reporting_period']['energy_category_ids'].append(energy_category_id) |
|
711 | result['reporting_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
712 | result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps']) |
|
713 | result['reporting_period']['values_saving'].append(reporting[energy_category_id]['values_saving']) |
|
714 | result['reporting_period']['subtotals_saving'].append(reporting[energy_category_id]['subtotal_saving']) |
|
715 | result['reporting_period']['subtotals_in_kgce_saving'].append( |
|
716 | reporting[energy_category_id]['subtotal_in_kgce_saving']) |
|
717 | result['reporting_period']['subtotals_in_kgco2e_saving'].append( |
|
718 | reporting[energy_category_id]['subtotal_in_kgco2e_saving']) |
|
719 | result['reporting_period']['subtotals_per_unit_area_saving'].append( |
|
720 | reporting[energy_category_id]['subtotal_saving'] / store['area'] |
|
721 | if store['area'] > Decimal(0.0) else None) |
|
722 | result['reporting_period']['increment_rates_saving'].append( |
|
723 | (reporting[energy_category_id]['subtotal_saving'] - base[energy_category_id]['subtotal_saving']) / |
|
724 | base[energy_category_id]['subtotal_saving'] |
|
725 | if base[energy_category_id]['subtotal_saving'] != Decimal(0.0) else None) |
|
726 | result['reporting_period']['total_in_kgce_saving'] += \ |
|
727 | reporting[energy_category_id]['subtotal_in_kgce_saving'] |
|
728 | result['reporting_period']['total_in_kgco2e_saving'] += \ |
|
729 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] |
|
730 | ||
731 | rate = list() |
|
732 | for index, value in enumerate(reporting[energy_category_id]['values_saving']): |
|
733 | if index < len(base[energy_category_id]['values_saving']) \ |
|
734 | and base[energy_category_id]['values_saving'][index] != 0 and value != 0: |
|
735 | rate.append((value - base[energy_category_id]['values_saving'][index]) |
|
736 | / base[energy_category_id]['values_saving'][index]) |
|
737 | else: |
|
738 | rate.append(None) |
|
739 | result['reporting_period']['rates_saving'].append(rate) |
|
740 | ||
741 | result['reporting_period']['total_in_kgco2e_per_unit_area_saving'] = \ |
|
742 | result['reporting_period']['total_in_kgce_saving'] / store['area'] \ |
|
743 | if store['area'] > Decimal(0.0) else None |
|
744 | ||
745 | result['reporting_period']['increment_rate_in_kgce_saving'] = \ |
|
746 | (result['reporting_period']['total_in_kgce_saving'] - result['base_period']['total_in_kgce_saving']) / \ |
|
747 | result['base_period']['total_in_kgce_saving'] \ |
|
748 | if result['base_period']['total_in_kgce_saving'] != Decimal(0.0) else None |
|
749 | ||
750 | result['reporting_period']['total_in_kgce_per_unit_area_saving'] = \ |
|
751 | result['reporting_period']['total_in_kgco2e_saving'] / store['area'] \ |
|
752 | if store['area'] > Decimal(0.0) else None |
|
753 | ||
754 | result['reporting_period']['increment_rate_in_kgco2e_saving'] = \ |
|
755 | (result['reporting_period']['total_in_kgco2e_saving'] - result['base_period']['total_in_kgco2e_saving']) / \ |
|
756 | result['base_period']['total_in_kgco2e_saving'] \ |
|
757 | if result['base_period']['total_in_kgco2e_saving'] != Decimal(0.0) else None |
|
758 | ||
759 | result['parameters'] = { |
|
760 | "names": parameters_data['names'], |
|
761 | "timestamps": parameters_data['timestamps'], |
|
762 | "values": parameters_data['values'] |
|
763 | } |
|
764 | ||
765 | # export result to Excel file and then encode the file to base64 string |
|
766 | if not is_quick_mode: |
|
767 | result['excel_bytes_base64'] = excelexporters.storesaving.export(result, |
|
768 | store['name'], |
|
769 | base_period_start_datetime_local, |
|
770 | base_period_end_datetime_local, |
|
771 | reporting_period_start_datetime_local, |
|
772 | reporting_period_end_datetime_local, |
|
773 | period_type, |
|
774 | language) |
|
775 | ||
776 | resp.text = json.dumps(result) |
|
777 |
@@ 13-776 (lines=764) @@ | ||
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 store |
|
27 | # Step 3: query energy categories |
|
28 | # Step 4: query associated sensors |
|
29 | # Step 5: query associated points |
|
30 | # Step 6: query base period energy saving |
|
31 | # Step 7: query reporting period energy saving |
|
32 | # Step 8: query tariff data |
|
33 | # Step 9: query associated sensors and 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 | store_id = req.params.get('storeid') |
|
46 | store_uuid = req.params.get('storeuuid') |
|
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 store_id is None and store_uuid is None: |
|
59 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
60 | title='API.BAD_REQUEST', |
|
61 | description='API.INVALID_STORE_ID') |
|
62 | ||
63 | if store_id is not None: |
|
64 | store_id = str.strip(store_id) |
|
65 | if not store_id.isdigit() or int(store_id) <= 0: |
|
66 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
67 | title='API.BAD_REQUEST', |
|
68 | description='API.INVALID_STORE_ID') |
|
69 | ||
70 | if store_uuid is not None: |
|
71 | 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) |
|
72 | match = regex.match(str.strip(store_uuid)) |
|
73 | if not bool(match): |
|
74 | raise falcon.HTTPError(status=falcon.HTTP_400, |
|
75 | title='API.BAD_REQUEST', |
|
76 | description='API.INVALID_STORE_UUID') |
|
77 | ||
78 | if period_type is None: |
|
79 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
80 | description='API.INVALID_PERIOD_TYPE') |
|
81 | else: |
|
82 | period_type = str.strip(period_type) |
|
83 | if period_type not in ['hourly', 'daily', 'weekly', 'monthly', 'yearly']: |
|
84 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
85 | description='API.INVALID_PERIOD_TYPE') |
|
86 | ||
87 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
|
88 | if config.utc_offset[0] == '-': |
|
89 | timezone_offset = -timezone_offset |
|
90 | ||
91 | base_start_datetime_utc = None |
|
92 | if base_period_start_datetime_local is not None and len(str.strip(base_period_start_datetime_local)) > 0: |
|
93 | base_period_start_datetime_local = str.strip(base_period_start_datetime_local) |
|
94 | try: |
|
95 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
96 | except ValueError: |
|
97 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
98 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
|
99 | base_start_datetime_utc = \ |
|
100 | base_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
101 | # nomalize the start datetime |
|
102 | if config.minutes_to_count == 30 and base_start_datetime_utc.minute >= 30: |
|
103 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
|
104 | else: |
|
105 | base_start_datetime_utc = base_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
|
106 | ||
107 | base_end_datetime_utc = None |
|
108 | if base_period_end_datetime_local is not None and len(str.strip(base_period_end_datetime_local)) > 0: |
|
109 | base_period_end_datetime_local = str.strip(base_period_end_datetime_local) |
|
110 | try: |
|
111 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
112 | except ValueError: |
|
113 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
114 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
|
115 | base_end_datetime_utc = \ |
|
116 | base_end_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
117 | ||
118 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
|
119 | base_start_datetime_utc >= base_end_datetime_utc: |
|
120 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
121 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
|
122 | ||
123 | if reporting_period_start_datetime_local is None: |
|
124 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
125 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
126 | else: |
|
127 | reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) |
|
128 | try: |
|
129 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, |
|
130 | '%Y-%m-%dT%H:%M:%S') |
|
131 | except ValueError: |
|
132 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
133 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
134 | reporting_start_datetime_utc = \ |
|
135 | reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - timedelta(minutes=timezone_offset) |
|
136 | # nomalize the start datetime |
|
137 | if config.minutes_to_count == 30 and reporting_start_datetime_utc.minute >= 30: |
|
138 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=30, second=0, microsecond=0) |
|
139 | else: |
|
140 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(minute=0, second=0, microsecond=0) |
|
141 | ||
142 | if reporting_period_end_datetime_local is None: |
|
143 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
144 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
145 | else: |
|
146 | reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) |
|
147 | try: |
|
148 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, |
|
149 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
150 | timedelta(minutes=timezone_offset) |
|
151 | except ValueError: |
|
152 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
153 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
154 | ||
155 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
|
156 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
|
157 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
|
158 | ||
159 | # if turn quick mode on, do not return parameters data and excel file |
|
160 | is_quick_mode = False |
|
161 | if quick_mode is not None and \ |
|
162 | len(str.strip(quick_mode)) > 0 and \ |
|
163 | str.lower(str.strip(quick_mode)) in ('true', 't', 'on', 'yes', 'y'): |
|
164 | is_quick_mode = True |
|
165 | ||
166 | trans = utilities.get_translation(language) |
|
167 | trans.install() |
|
168 | _ = trans.gettext |
|
169 | ||
170 | ################################################################################################################ |
|
171 | # Step 2: query the store |
|
172 | ################################################################################################################ |
|
173 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
|
174 | cursor_system = cnx_system.cursor() |
|
175 | ||
176 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
|
177 | cursor_energy = cnx_energy.cursor() |
|
178 | ||
179 | cnx_energy_plan = mysql.connector.connect(**config.myems_energy_plan_db) |
|
180 | cursor_energy_plan = cnx_energy_plan.cursor() |
|
181 | ||
182 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
|
183 | cursor_historical = cnx_historical.cursor() |
|
184 | ||
185 | if store_id is not None: |
|
186 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
187 | " FROM tbl_stores " |
|
188 | " WHERE id = %s ", (store_id,)) |
|
189 | row_store = cursor_system.fetchone() |
|
190 | elif store_uuid is not None: |
|
191 | cursor_system.execute(" SELECT id, name, area, cost_center_id " |
|
192 | " FROM tbl_stores " |
|
193 | " WHERE uuid = %s ", (store_uuid,)) |
|
194 | row_store = cursor_system.fetchone() |
|
195 | ||
196 | if row_store is None: |
|
197 | if cursor_system: |
|
198 | cursor_system.close() |
|
199 | if cnx_system: |
|
200 | cnx_system.close() |
|
201 | ||
202 | if cursor_energy: |
|
203 | cursor_energy.close() |
|
204 | if cnx_energy: |
|
205 | cnx_energy.close() |
|
206 | ||
207 | if cursor_energy_plan: |
|
208 | cursor_energy_plan.close() |
|
209 | if cnx_energy_plan: |
|
210 | cnx_energy_plan.close() |
|
211 | ||
212 | if cursor_historical: |
|
213 | cursor_historical.close() |
|
214 | if cnx_historical: |
|
215 | cnx_historical.close() |
|
216 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', description='API.STORE_NOT_FOUND') |
|
217 | ||
218 | store = dict() |
|
219 | store['id'] = row_store[0] |
|
220 | store['name'] = row_store[1] |
|
221 | store['area'] = row_store[2] |
|
222 | store['cost_center_id'] = row_store[3] |
|
223 | ||
224 | ################################################################################################################ |
|
225 | # Step 3: query energy categories |
|
226 | ################################################################################################################ |
|
227 | energy_category_set = set() |
|
228 | # query energy categories in base period |
|
229 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
230 | " FROM tbl_store_input_category_hourly " |
|
231 | " WHERE store_id = %s " |
|
232 | " AND start_datetime_utc >= %s " |
|
233 | " AND start_datetime_utc < %s ", |
|
234 | (store['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
235 | rows_energy_categories = cursor_energy.fetchall() |
|
236 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
|
237 | for row_energy_category in rows_energy_categories: |
|
238 | energy_category_set.add(row_energy_category[0]) |
|
239 | ||
240 | # query energy categories in reporting period |
|
241 | cursor_energy.execute(" SELECT DISTINCT(energy_category_id) " |
|
242 | " FROM tbl_store_input_category_hourly " |
|
243 | " WHERE store_id = %s " |
|
244 | " AND start_datetime_utc >= %s " |
|
245 | " AND start_datetime_utc < %s ", |
|
246 | (store['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
247 | rows_energy_categories = cursor_energy.fetchall() |
|
248 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
|
249 | for row_energy_category in rows_energy_categories: |
|
250 | energy_category_set.add(row_energy_category[0]) |
|
251 | ||
252 | # query all energy categories in base period and reporting period |
|
253 | cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e " |
|
254 | " FROM tbl_energy_categories " |
|
255 | " ORDER BY id ", ) |
|
256 | rows_energy_categories = cursor_system.fetchall() |
|
257 | if rows_energy_categories is None or len(rows_energy_categories) == 0: |
|
258 | if cursor_system: |
|
259 | cursor_system.close() |
|
260 | if cnx_system: |
|
261 | cnx_system.close() |
|
262 | ||
263 | if cursor_energy: |
|
264 | cursor_energy.close() |
|
265 | if cnx_energy: |
|
266 | cnx_energy.close() |
|
267 | ||
268 | if cursor_energy_plan: |
|
269 | cursor_energy_plan.close() |
|
270 | if cnx_energy_plan: |
|
271 | cnx_energy_plan.close() |
|
272 | ||
273 | if cursor_historical: |
|
274 | cursor_historical.close() |
|
275 | if cnx_historical: |
|
276 | cnx_historical.close() |
|
277 | raise falcon.HTTPError(status=falcon.HTTP_404, |
|
278 | title='API.NOT_FOUND', |
|
279 | description='API.ENERGY_CATEGORY_NOT_FOUND') |
|
280 | energy_category_dict = dict() |
|
281 | for row_energy_category in rows_energy_categories: |
|
282 | if row_energy_category[0] in energy_category_set: |
|
283 | energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1], |
|
284 | "unit_of_measure": row_energy_category[2], |
|
285 | "kgce": row_energy_category[3], |
|
286 | "kgco2e": row_energy_category[4]} |
|
287 | ||
288 | ################################################################################################################ |
|
289 | # Step 4: query associated sensors |
|
290 | ################################################################################################################ |
|
291 | point_list = list() |
|
292 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
293 | " FROM tbl_stores st, tbl_sensors se, tbl_stores_sensors ss, " |
|
294 | " tbl_points p, tbl_sensors_points sp " |
|
295 | " WHERE st.id = %s AND st.id = ss.store_id AND ss.sensor_id = se.id " |
|
296 | " AND se.id = sp.sensor_id AND sp.point_id = p.id " |
|
297 | " ORDER BY p.id ", (store['id'],)) |
|
298 | rows_points = cursor_system.fetchall() |
|
299 | if rows_points is not None and len(rows_points) > 0: |
|
300 | for row in rows_points: |
|
301 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
302 | ||
303 | ################################################################################################################ |
|
304 | # Step 5: query associated points |
|
305 | ################################################################################################################ |
|
306 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
307 | " FROM tbl_stores s, tbl_stores_points sp, tbl_points p " |
|
308 | " WHERE s.id = %s AND s.id = sp.store_id AND sp.point_id = p.id " |
|
309 | " ORDER BY p.id ", (store['id'],)) |
|
310 | rows_points = cursor_system.fetchall() |
|
311 | if rows_points is not None and len(rows_points) > 0: |
|
312 | for row in rows_points: |
|
313 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
314 | ||
315 | ################################################################################################################ |
|
316 | # Step 6: query base period energy saving |
|
317 | ################################################################################################################ |
|
318 | base = dict() |
|
319 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
320 | for energy_category_id in energy_category_set: |
|
321 | kgce = energy_category_dict[energy_category_id]['kgce'] |
|
322 | kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
|
323 | ||
324 | base[energy_category_id] = dict() |
|
325 | base[energy_category_id]['timestamps'] = list() |
|
326 | base[energy_category_id]['values_plan'] = list() |
|
327 | base[energy_category_id]['values_actual'] = list() |
|
328 | base[energy_category_id]['values_saving'] = list() |
|
329 | base[energy_category_id]['subtotal_plan'] = Decimal(0.0) |
|
330 | base[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
|
331 | base[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
|
332 | base[energy_category_id]['subtotal_in_kgce_plan'] = Decimal(0.0) |
|
333 | base[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
|
334 | base[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
|
335 | base[energy_category_id]['subtotal_in_kgco2e_plan'] = Decimal(0.0) |
|
336 | base[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
|
337 | base[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
|
338 | # query base period's energy plan |
|
339 | cursor_energy_plan.execute(" SELECT start_datetime_utc, actual_value " |
|
340 | " FROM tbl_store_input_category_hourly " |
|
341 | " WHERE store_id = %s " |
|
342 | " AND energy_category_id = %s " |
|
343 | " AND start_datetime_utc >= %s " |
|
344 | " AND start_datetime_utc < %s " |
|
345 | " ORDER BY start_datetime_utc ", |
|
346 | (store['id'], |
|
347 | energy_category_id, |
|
348 | base_start_datetime_utc, |
|
349 | base_end_datetime_utc)) |
|
350 | rows_store_hourly = cursor_energy_plan.fetchall() |
|
351 | ||
352 | rows_store_periodically = utilities.aggregate_hourly_data_by_period(rows_store_hourly, |
|
353 | base_start_datetime_utc, |
|
354 | base_end_datetime_utc, |
|
355 | period_type) |
|
356 | for row_store_periodically in rows_store_periodically: |
|
357 | current_datetime_local = row_store_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
358 | timedelta(minutes=timezone_offset) |
|
359 | if period_type == 'hourly': |
|
360 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
361 | elif period_type == 'daily': |
|
362 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
363 | elif period_type == 'weekly': |
|
364 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
365 | elif period_type == 'monthly': |
|
366 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
367 | elif period_type == 'yearly': |
|
368 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
369 | ||
370 | plan_value = Decimal(0.0) if row_store_periodically[1] is None else row_store_periodically[1] |
|
371 | base[energy_category_id]['timestamps'].append(current_datetime) |
|
372 | base[energy_category_id]['values_plan'].append(plan_value) |
|
373 | base[energy_category_id]['subtotal_plan'] += plan_value |
|
374 | base[energy_category_id]['subtotal_in_kgce_plan'] += plan_value * kgce |
|
375 | base[energy_category_id]['subtotal_in_kgco2e_plan'] += plan_value * kgco2e |
|
376 | ||
377 | # query base period's energy actual |
|
378 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
379 | " FROM tbl_store_input_category_hourly " |
|
380 | " WHERE store_id = %s " |
|
381 | " AND energy_category_id = %s " |
|
382 | " AND start_datetime_utc >= %s " |
|
383 | " AND start_datetime_utc < %s " |
|
384 | " ORDER BY start_datetime_utc ", |
|
385 | (store['id'], |
|
386 | energy_category_id, |
|
387 | base_start_datetime_utc, |
|
388 | base_end_datetime_utc)) |
|
389 | rows_store_hourly = cursor_energy.fetchall() |
|
390 | ||
391 | rows_store_periodically = utilities.aggregate_hourly_data_by_period(rows_store_hourly, |
|
392 | base_start_datetime_utc, |
|
393 | base_end_datetime_utc, |
|
394 | period_type) |
|
395 | for row_store_periodically in rows_store_periodically: |
|
396 | current_datetime_local = row_store_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
397 | timedelta(minutes=timezone_offset) |
|
398 | if period_type == 'hourly': |
|
399 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
400 | elif period_type == 'daily': |
|
401 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
402 | elif period_type == 'weekly': |
|
403 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
404 | elif period_type == 'monthly': |
|
405 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
406 | elif period_type == 'yearly': |
|
407 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
408 | ||
409 | actual_value = Decimal(0.0) if row_store_periodically[1] is None else row_store_periodically[1] |
|
410 | base[energy_category_id]['values_actual'].append(actual_value) |
|
411 | base[energy_category_id]['subtotal_actual'] += actual_value |
|
412 | base[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
|
413 | base[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
|
414 | ||
415 | # calculate base period's energy savings |
|
416 | for i in range(len(base[energy_category_id]['values_plan'])): |
|
417 | base[energy_category_id]['values_saving'].append( |
|
418 | base[energy_category_id]['values_plan'][i] - |
|
419 | base[energy_category_id]['values_actual'][i]) |
|
420 | ||
421 | base[energy_category_id]['subtotal_saving'] = \ |
|
422 | base[energy_category_id]['subtotal_plan'] - \ |
|
423 | base[energy_category_id]['subtotal_actual'] |
|
424 | base[energy_category_id]['subtotal_in_kgce_saving'] = \ |
|
425 | base[energy_category_id]['subtotal_in_kgce_plan'] - \ |
|
426 | base[energy_category_id]['subtotal_in_kgce_actual'] |
|
427 | base[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
|
428 | base[energy_category_id]['subtotal_in_kgco2e_plan'] - \ |
|
429 | base[energy_category_id]['subtotal_in_kgco2e_actual'] |
|
430 | ################################################################################################################ |
|
431 | # Step 7: query reporting period energy saving |
|
432 | ################################################################################################################ |
|
433 | reporting = dict() |
|
434 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
435 | for energy_category_id in energy_category_set: |
|
436 | kgce = energy_category_dict[energy_category_id]['kgce'] |
|
437 | kgco2e = energy_category_dict[energy_category_id]['kgco2e'] |
|
438 | ||
439 | reporting[energy_category_id] = dict() |
|
440 | reporting[energy_category_id]['timestamps'] = list() |
|
441 | reporting[energy_category_id]['values_plan'] = list() |
|
442 | reporting[energy_category_id]['values_actual'] = list() |
|
443 | reporting[energy_category_id]['values_saving'] = list() |
|
444 | reporting[energy_category_id]['subtotal_plan'] = Decimal(0.0) |
|
445 | reporting[energy_category_id]['subtotal_actual'] = Decimal(0.0) |
|
446 | reporting[energy_category_id]['subtotal_saving'] = Decimal(0.0) |
|
447 | reporting[energy_category_id]['subtotal_in_kgce_plan'] = Decimal(0.0) |
|
448 | reporting[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0) |
|
449 | reporting[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0) |
|
450 | reporting[energy_category_id]['subtotal_in_kgco2e_plan'] = Decimal(0.0) |
|
451 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0) |
|
452 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0) |
|
453 | # query reporting period's energy plan |
|
454 | cursor_energy_plan.execute(" SELECT start_datetime_utc, actual_value " |
|
455 | " FROM tbl_store_input_category_hourly " |
|
456 | " WHERE store_id = %s " |
|
457 | " AND energy_category_id = %s " |
|
458 | " AND start_datetime_utc >= %s " |
|
459 | " AND start_datetime_utc < %s " |
|
460 | " ORDER BY start_datetime_utc ", |
|
461 | (store['id'], |
|
462 | energy_category_id, |
|
463 | reporting_start_datetime_utc, |
|
464 | reporting_end_datetime_utc)) |
|
465 | rows_store_hourly = cursor_energy_plan.fetchall() |
|
466 | ||
467 | rows_store_periodically = utilities.aggregate_hourly_data_by_period(rows_store_hourly, |
|
468 | reporting_start_datetime_utc, |
|
469 | reporting_end_datetime_utc, |
|
470 | period_type) |
|
471 | for row_store_periodically in rows_store_periodically: |
|
472 | current_datetime_local = row_store_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
473 | timedelta(minutes=timezone_offset) |
|
474 | if period_type == 'hourly': |
|
475 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
476 | elif period_type == 'daily': |
|
477 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
478 | elif period_type == 'weekly': |
|
479 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
480 | elif period_type == 'monthly': |
|
481 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
482 | elif period_type == 'yearly': |
|
483 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
484 | ||
485 | plan_value = Decimal(0.0) if row_store_periodically[1] is None else row_store_periodically[1] |
|
486 | reporting[energy_category_id]['timestamps'].append(current_datetime) |
|
487 | reporting[energy_category_id]['values_plan'].append(plan_value) |
|
488 | reporting[energy_category_id]['subtotal_plan'] += plan_value |
|
489 | reporting[energy_category_id]['subtotal_in_kgce_plan'] += plan_value * kgce |
|
490 | reporting[energy_category_id]['subtotal_in_kgco2e_plan'] += plan_value * kgco2e |
|
491 | ||
492 | # query reporting period's energy actual |
|
493 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
494 | " FROM tbl_store_input_category_hourly " |
|
495 | " WHERE store_id = %s " |
|
496 | " AND energy_category_id = %s " |
|
497 | " AND start_datetime_utc >= %s " |
|
498 | " AND start_datetime_utc < %s " |
|
499 | " ORDER BY start_datetime_utc ", |
|
500 | (store['id'], |
|
501 | energy_category_id, |
|
502 | reporting_start_datetime_utc, |
|
503 | reporting_end_datetime_utc)) |
|
504 | rows_store_hourly = cursor_energy.fetchall() |
|
505 | ||
506 | rows_store_periodically = utilities.aggregate_hourly_data_by_period(rows_store_hourly, |
|
507 | reporting_start_datetime_utc, |
|
508 | reporting_end_datetime_utc, |
|
509 | period_type) |
|
510 | for row_store_periodically in rows_store_periodically: |
|
511 | current_datetime_local = row_store_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
512 | timedelta(minutes=timezone_offset) |
|
513 | if period_type == 'hourly': |
|
514 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
515 | elif period_type == 'daily': |
|
516 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
517 | elif period_type == 'weekly': |
|
518 | current_datetime = current_datetime_local.isoformat()[0:10] |
|
519 | elif period_type == 'monthly': |
|
520 | current_datetime = current_datetime_local.isoformat()[0:7] |
|
521 | elif period_type == 'yearly': |
|
522 | current_datetime = current_datetime_local.isoformat()[0:4] |
|
523 | ||
524 | actual_value = Decimal(0.0) if row_store_periodically[1] is None else row_store_periodically[1] |
|
525 | reporting[energy_category_id]['values_actual'].append(actual_value) |
|
526 | reporting[energy_category_id]['subtotal_actual'] += actual_value |
|
527 | reporting[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce |
|
528 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e |
|
529 | ||
530 | # calculate reporting period's energy savings |
|
531 | for i in range(len(reporting[energy_category_id]['values_plan'])): |
|
532 | reporting[energy_category_id]['values_saving'].append( |
|
533 | reporting[energy_category_id]['values_plan'][i] - |
|
534 | reporting[energy_category_id]['values_actual'][i]) |
|
535 | ||
536 | reporting[energy_category_id]['subtotal_saving'] = \ |
|
537 | reporting[energy_category_id]['subtotal_plan'] - \ |
|
538 | reporting[energy_category_id]['subtotal_actual'] |
|
539 | reporting[energy_category_id]['subtotal_in_kgce_saving'] = \ |
|
540 | reporting[energy_category_id]['subtotal_in_kgce_plan'] - \ |
|
541 | reporting[energy_category_id]['subtotal_in_kgce_actual'] |
|
542 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = \ |
|
543 | reporting[energy_category_id]['subtotal_in_kgco2e_plan'] - \ |
|
544 | reporting[energy_category_id]['subtotal_in_kgco2e_actual'] |
|
545 | ################################################################################################################ |
|
546 | # Step 8: query tariff data |
|
547 | ################################################################################################################ |
|
548 | parameters_data = dict() |
|
549 | parameters_data['names'] = list() |
|
550 | parameters_data['timestamps'] = list() |
|
551 | parameters_data['values'] = list() |
|
552 | if config.is_tariff_appended and energy_category_set is not None and len(energy_category_set) > 0 \ |
|
553 | and not is_quick_mode: |
|
554 | for energy_category_id in energy_category_set: |
|
555 | energy_category_tariff_dict = utilities.get_energy_category_tariffs(store['cost_center_id'], |
|
556 | energy_category_id, |
|
557 | reporting_start_datetime_utc, |
|
558 | reporting_end_datetime_utc) |
|
559 | tariff_timestamp_list = list() |
|
560 | tariff_value_list = list() |
|
561 | for k, v in energy_category_tariff_dict.items(): |
|
562 | # convert k from utc to local |
|
563 | k = k + timedelta(minutes=timezone_offset) |
|
564 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
|
565 | tariff_value_list.append(v) |
|
566 | ||
567 | parameters_data['names'].append(_('Tariff') + '-' + energy_category_dict[energy_category_id]['name']) |
|
568 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
569 | parameters_data['values'].append(tariff_value_list) |
|
570 | ||
571 | ################################################################################################################ |
|
572 | # Step 9: query associated sensors and points data |
|
573 | ################################################################################################################ |
|
574 | if not is_quick_mode: |
|
575 | for point in point_list: |
|
576 | point_values = [] |
|
577 | point_timestamps = [] |
|
578 | if point['object_type'] == 'ENERGY_VALUE': |
|
579 | query = (" SELECT utc_date_time, actual_value " |
|
580 | " FROM tbl_energy_value " |
|
581 | " WHERE point_id = %s " |
|
582 | " AND utc_date_time BETWEEN %s AND %s " |
|
583 | " ORDER BY utc_date_time ") |
|
584 | cursor_historical.execute(query, (point['id'], |
|
585 | reporting_start_datetime_utc, |
|
586 | reporting_end_datetime_utc)) |
|
587 | rows = cursor_historical.fetchall() |
|
588 | ||
589 | if rows is not None and len(rows) > 0: |
|
590 | for row in rows: |
|
591 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
592 | timedelta(minutes=timezone_offset) |
|
593 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
594 | point_timestamps.append(current_datetime) |
|
595 | point_values.append(row[1]) |
|
596 | elif point['object_type'] == 'ANALOG_VALUE': |
|
597 | query = (" SELECT utc_date_time, actual_value " |
|
598 | " FROM tbl_analog_value " |
|
599 | " WHERE point_id = %s " |
|
600 | " AND utc_date_time BETWEEN %s AND %s " |
|
601 | " ORDER BY utc_date_time ") |
|
602 | cursor_historical.execute(query, (point['id'], |
|
603 | reporting_start_datetime_utc, |
|
604 | reporting_end_datetime_utc)) |
|
605 | rows = cursor_historical.fetchall() |
|
606 | ||
607 | if rows is not None and len(rows) > 0: |
|
608 | for row in rows: |
|
609 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
610 | timedelta(minutes=timezone_offset) |
|
611 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
612 | point_timestamps.append(current_datetime) |
|
613 | point_values.append(row[1]) |
|
614 | elif point['object_type'] == 'DIGITAL_VALUE': |
|
615 | query = (" SELECT utc_date_time, actual_value " |
|
616 | " FROM tbl_digital_value " |
|
617 | " WHERE point_id = %s " |
|
618 | " AND utc_date_time BETWEEN %s AND %s " |
|
619 | " ORDER BY utc_date_time ") |
|
620 | cursor_historical.execute(query, (point['id'], |
|
621 | reporting_start_datetime_utc, |
|
622 | reporting_end_datetime_utc)) |
|
623 | rows = cursor_historical.fetchall() |
|
624 | ||
625 | if rows is not None and len(rows) > 0: |
|
626 | for row in rows: |
|
627 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
628 | timedelta(minutes=timezone_offset) |
|
629 | current_datetime = current_datetime_local.isoformat()[0:19] |
|
630 | point_timestamps.append(current_datetime) |
|
631 | point_values.append(row[1]) |
|
632 | ||
633 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
|
634 | parameters_data['timestamps'].append(point_timestamps) |
|
635 | parameters_data['values'].append(point_values) |
|
636 | ||
637 | ################################################################################################################ |
|
638 | # Step 10: construct the report |
|
639 | ################################################################################################################ |
|
640 | if cursor_system: |
|
641 | cursor_system.close() |
|
642 | if cnx_system: |
|
643 | cnx_system.close() |
|
644 | ||
645 | if cursor_energy: |
|
646 | cursor_energy.close() |
|
647 | if cnx_energy: |
|
648 | cnx_energy.close() |
|
649 | ||
650 | if cursor_energy_plan: |
|
651 | cursor_energy_plan.close() |
|
652 | if cnx_energy_plan: |
|
653 | cnx_energy_plan.close() |
|
654 | ||
655 | if cursor_historical: |
|
656 | cursor_historical.close() |
|
657 | if cnx_historical: |
|
658 | cnx_historical.close() |
|
659 | ||
660 | result = dict() |
|
661 | ||
662 | result['store'] = dict() |
|
663 | result['store']['name'] = store['name'] |
|
664 | result['store']['area'] = store['area'] |
|
665 | ||
666 | result['base_period'] = dict() |
|
667 | result['base_period']['names'] = list() |
|
668 | result['base_period']['units'] = list() |
|
669 | result['base_period']['timestamps'] = list() |
|
670 | result['base_period']['values_saving'] = list() |
|
671 | result['base_period']['subtotals_saving'] = list() |
|
672 | result['base_period']['subtotals_in_kgce_saving'] = list() |
|
673 | result['base_period']['subtotals_in_kgco2e_saving'] = list() |
|
674 | result['base_period']['total_in_kgce_saving'] = Decimal(0.0) |
|
675 | result['base_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
|
676 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
677 | for energy_category_id in energy_category_set: |
|
678 | result['base_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
679 | result['base_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
680 | result['base_period']['timestamps'].append(base[energy_category_id]['timestamps']) |
|
681 | result['base_period']['values_saving'].append(base[energy_category_id]['values_saving']) |
|
682 | result['base_period']['subtotals_saving'].append(base[energy_category_id]['subtotal_saving']) |
|
683 | result['base_period']['subtotals_in_kgce_saving'].append( |
|
684 | base[energy_category_id]['subtotal_in_kgce_saving']) |
|
685 | result['base_period']['subtotals_in_kgco2e_saving'].append( |
|
686 | base[energy_category_id]['subtotal_in_kgco2e_saving']) |
|
687 | result['base_period']['total_in_kgce_saving'] += base[energy_category_id]['subtotal_in_kgce_saving'] |
|
688 | result['base_period']['total_in_kgco2e_saving'] += base[energy_category_id]['subtotal_in_kgco2e_saving'] |
|
689 | ||
690 | result['reporting_period'] = dict() |
|
691 | result['reporting_period']['names'] = list() |
|
692 | result['reporting_period']['energy_category_ids'] = list() |
|
693 | result['reporting_period']['units'] = list() |
|
694 | result['reporting_period']['timestamps'] = list() |
|
695 | result['reporting_period']['values_saving'] = list() |
|
696 | result['reporting_period']['rates_saving'] = list() |
|
697 | result['reporting_period']['subtotals_saving'] = list() |
|
698 | result['reporting_period']['subtotals_in_kgce_saving'] = list() |
|
699 | result['reporting_period']['subtotals_in_kgco2e_saving'] = list() |
|
700 | result['reporting_period']['subtotals_per_unit_area_saving'] = list() |
|
701 | result['reporting_period']['increment_rates_saving'] = list() |
|
702 | result['reporting_period']['total_in_kgce_saving'] = Decimal(0.0) |
|
703 | result['reporting_period']['total_in_kgco2e_saving'] = Decimal(0.0) |
|
704 | result['reporting_period']['increment_rate_in_kgce_saving'] = Decimal(0.0) |
|
705 | result['reporting_period']['increment_rate_in_kgco2e_saving'] = Decimal(0.0) |
|
706 | ||
707 | if energy_category_set is not None and len(energy_category_set) > 0: |
|
708 | for energy_category_id in energy_category_set: |
|
709 | result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name']) |
|
710 | result['reporting_period']['energy_category_ids'].append(energy_category_id) |
|
711 | result['reporting_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure']) |
|
712 | result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps']) |
|
713 | result['reporting_period']['values_saving'].append(reporting[energy_category_id]['values_saving']) |
|
714 | result['reporting_period']['subtotals_saving'].append(reporting[energy_category_id]['subtotal_saving']) |
|
715 | result['reporting_period']['subtotals_in_kgce_saving'].append( |
|
716 | reporting[energy_category_id]['subtotal_in_kgce_saving']) |
|
717 | result['reporting_period']['subtotals_in_kgco2e_saving'].append( |
|
718 | reporting[energy_category_id]['subtotal_in_kgco2e_saving']) |
|
719 | result['reporting_period']['subtotals_per_unit_area_saving'].append( |
|
720 | reporting[energy_category_id]['subtotal_saving'] / store['area'] |
|
721 | if store['area'] > Decimal(0.0) else None) |
|
722 | result['reporting_period']['increment_rates_saving'].append( |
|
723 | (reporting[energy_category_id]['subtotal_saving'] - base[energy_category_id]['subtotal_saving']) / |
|
724 | base[energy_category_id]['subtotal_saving'] |
|
725 | if base[energy_category_id]['subtotal_saving'] != Decimal(0.0) else None) |
|
726 | result['reporting_period']['total_in_kgce_saving'] += \ |
|
727 | reporting[energy_category_id]['subtotal_in_kgce_saving'] |
|
728 | result['reporting_period']['total_in_kgco2e_saving'] += \ |
|
729 | reporting[energy_category_id]['subtotal_in_kgco2e_saving'] |
|
730 | ||
731 | rate = list() |
|
732 | for index, value in enumerate(reporting[energy_category_id]['values_saving']): |
|
733 | if index < len(base[energy_category_id]['values_saving']) \ |
|
734 | and base[energy_category_id]['values_saving'][index] != 0 and value != 0: |
|
735 | rate.append((value - base[energy_category_id]['values_saving'][index]) |
|
736 | / base[energy_category_id]['values_saving'][index]) |
|
737 | else: |
|
738 | rate.append(None) |
|
739 | result['reporting_period']['rates_saving'].append(rate) |
|
740 | ||
741 | result['reporting_period']['total_in_kgco2e_per_unit_area_saving'] = \ |
|
742 | result['reporting_period']['total_in_kgce_saving'] / store['area'] \ |
|
743 | if store['area'] > Decimal(0.0) else None |
|
744 | ||
745 | result['reporting_period']['increment_rate_in_kgce_saving'] = \ |
|
746 | (result['reporting_period']['total_in_kgce_saving'] - result['base_period']['total_in_kgce_saving']) / \ |
|
747 | result['base_period']['total_in_kgce_saving'] \ |
|
748 | if result['base_period']['total_in_kgce_saving'] != Decimal(0.0) else None |
|
749 | ||
750 | result['reporting_period']['total_in_kgce_per_unit_area_saving'] = \ |
|
751 | result['reporting_period']['total_in_kgco2e_saving'] / store['area'] \ |
|
752 | if store['area'] > Decimal(0.0) else None |
|
753 | ||
754 | result['reporting_period']['increment_rate_in_kgco2e_saving'] = \ |
|
755 | (result['reporting_period']['total_in_kgco2e_saving'] - result['base_period']['total_in_kgco2e_saving']) / \ |
|
756 | result['base_period']['total_in_kgco2e_saving'] \ |
|
757 | if result['base_period']['total_in_kgco2e_saving'] != Decimal(0.0) else None |
|
758 | ||
759 | result['parameters'] = { |
|
760 | "names": parameters_data['names'], |
|
761 | "timestamps": parameters_data['timestamps'], |
|
762 | "values": parameters_data['values'] |
|
763 | } |
|
764 | ||
765 | # export result to Excel file and then encode the file to base64 string |
|
766 | if not is_quick_mode: |
|
767 | result['excel_bytes_base64'] = excelexporters.storeplan.export(result, |
|
768 | store['name'], |
|
769 | base_period_start_datetime_local, |
|
770 | base_period_end_datetime_local, |
|
771 | reporting_period_start_datetime_local, |
|
772 | reporting_period_end_datetime_local, |
|
773 | period_type, |
|
774 | language) |
|
775 | ||
776 | resp.text = json.dumps(result) |
|
777 |