@@ 11-325 (lines=315) @@ | ||
8 | import excelexporters.virtualmeterenergy |
|
9 | ||
10 | ||
11 | class Reporting: |
|
12 | @staticmethod |
|
13 | def __init__(): |
|
14 | pass |
|
15 | ||
16 | @staticmethod |
|
17 | def on_options(req, resp): |
|
18 | resp.status = falcon.HTTP_200 |
|
19 | ||
20 | #################################################################################################################### |
|
21 | # PROCEDURES |
|
22 | # Step 1: valid parameters |
|
23 | # Step 2: query the virtual meter and energy category |
|
24 | # Step 3: query base period energy consumption |
|
25 | # Step 4: query reporting period energy consumption |
|
26 | # Step 5: query tariff data |
|
27 | # Step 6: construct the report |
|
28 | #################################################################################################################### |
|
29 | @staticmethod |
|
30 | def on_get(req, resp): |
|
31 | print(req.params) |
|
32 | virtual_meter_id = req.params.get('virtualmeterid') |
|
33 | period_type = req.params.get('periodtype') |
|
34 | base_period_start_datetime_local = req.params.get('baseperiodstartdatetime') |
|
35 | base_period_end_datetime_local = req.params.get('baseperiodenddatetime') |
|
36 | reporting_period_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
|
37 | reporting_period_end_datetime_local = req.params.get('reportingperiodenddatetime') |
|
38 | ||
39 | ################################################################################################################ |
|
40 | # Step 1: valid parameters |
|
41 | ################################################################################################################ |
|
42 | if virtual_meter_id is None: |
|
43 | raise falcon.HTTPError(falcon.HTTP_400, |
|
44 | title='API.BAD_REQUEST', |
|
45 | description='API.INVALID_VIRTUAL_METER_ID') |
|
46 | else: |
|
47 | virtual_meter_id = str.strip(virtual_meter_id) |
|
48 | if not virtual_meter_id.isdigit() or int(virtual_meter_id) <= 0: |
|
49 | raise falcon.HTTPError(falcon.HTTP_400, |
|
50 | title='API.BAD_REQUEST', |
|
51 | description='API.INVALID_VIRTUAL_METER_ID') |
|
52 | ||
53 | if period_type is None: |
|
54 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
|
55 | else: |
|
56 | period_type = str.strip(period_type) |
|
57 | if period_type not in ['hourly', 'daily', 'monthly', 'yearly']: |
|
58 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
|
59 | ||
60 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
|
61 | if config.utc_offset[0] == '-': |
|
62 | timezone_offset = -timezone_offset |
|
63 | ||
64 | base_start_datetime_utc = None |
|
65 | if base_period_start_datetime_local is not None and len(str.strip(base_period_start_datetime_local)) > 0: |
|
66 | base_period_start_datetime_local = str.strip(base_period_start_datetime_local) |
|
67 | try: |
|
68 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
69 | except ValueError: |
|
70 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
71 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
|
72 | base_start_datetime_utc = base_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
73 | timedelta(minutes=timezone_offset) |
|
74 | ||
75 | base_end_datetime_utc = None |
|
76 | if base_period_end_datetime_local is not None and len(str.strip(base_period_end_datetime_local)) > 0: |
|
77 | base_period_end_datetime_local = str.strip(base_period_end_datetime_local) |
|
78 | try: |
|
79 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S') |
|
80 | except ValueError: |
|
81 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
82 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
|
83 | base_end_datetime_utc = base_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
84 | timedelta(minutes=timezone_offset) |
|
85 | ||
86 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
|
87 | base_start_datetime_utc >= base_end_datetime_utc: |
|
88 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
89 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
|
90 | ||
91 | if reporting_period_start_datetime_local is None: |
|
92 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
93 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
94 | else: |
|
95 | reporting_period_start_datetime_local = str.strip(reporting_period_start_datetime_local) |
|
96 | try: |
|
97 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local, |
|
98 | '%Y-%m-%dT%H:%M:%S') |
|
99 | except ValueError: |
|
100 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
101 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
102 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
103 | timedelta(minutes=timezone_offset) |
|
104 | ||
105 | if reporting_period_end_datetime_local is None: |
|
106 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
107 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
108 | else: |
|
109 | reporting_period_end_datetime_local = str.strip(reporting_period_end_datetime_local) |
|
110 | try: |
|
111 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local, |
|
112 | '%Y-%m-%dT%H:%M:%S') |
|
113 | except ValueError: |
|
114 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
115 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
116 | reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
117 | timedelta(minutes=timezone_offset) |
|
118 | ||
119 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
|
120 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
121 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
|
122 | ||
123 | ################################################################################################################ |
|
124 | # Step 2: query the virtual meter and energy category |
|
125 | ################################################################################################################ |
|
126 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
|
127 | cursor_system = cnx_system.cursor() |
|
128 | ||
129 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
|
130 | cursor_energy = cnx_energy.cursor() |
|
131 | ||
132 | cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, " |
|
133 | " ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
|
134 | " FROM tbl_virtual_meters m, tbl_energy_categories ec " |
|
135 | " WHERE m.id = %s AND m.energy_category_id = ec.id ", (virtual_meter_id,)) |
|
136 | row_virtual_meter = cursor_system.fetchone() |
|
137 | if row_virtual_meter is None: |
|
138 | if cursor_system: |
|
139 | cursor_system.close() |
|
140 | if cnx_system: |
|
141 | cnx_system.disconnect() |
|
142 | ||
143 | if cursor_energy: |
|
144 | cursor_energy.close() |
|
145 | if cnx_energy: |
|
146 | cnx_energy.disconnect() |
|
147 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.VIRTUAL_METER_NOT_FOUND') |
|
148 | ||
149 | virtual_meter = dict() |
|
150 | virtual_meter['id'] = row_virtual_meter[0] |
|
151 | virtual_meter['name'] = row_virtual_meter[1] |
|
152 | virtual_meter['cost_center_id'] = row_virtual_meter[2] |
|
153 | virtual_meter['energy_category_id'] = row_virtual_meter[3] |
|
154 | virtual_meter['energy_category_name'] = row_virtual_meter[4] |
|
155 | virtual_meter['unit_of_measure'] = row_virtual_meter[5] |
|
156 | virtual_meter['kgce'] = row_virtual_meter[6] |
|
157 | virtual_meter['kgco2e'] = row_virtual_meter[7] |
|
158 | ||
159 | ################################################################################################################ |
|
160 | # Step 3: query base period energy consumption |
|
161 | ################################################################################################################ |
|
162 | query = (" SELECT start_datetime_utc, actual_value " |
|
163 | " FROM tbl_virtual_meter_hourly " |
|
164 | " WHERE virtual_meter_id = %s " |
|
165 | " AND start_datetime_utc >= %s " |
|
166 | " AND start_datetime_utc < %s " |
|
167 | " ORDER BY start_datetime_utc ") |
|
168 | cursor_energy.execute(query, (virtual_meter['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
169 | rows_virtual_meter_hourly = cursor_energy.fetchall() |
|
170 | ||
171 | rows_virtual_meter_periodically = \ |
|
172 | utilities.aggregate_hourly_data_by_period(rows_virtual_meter_hourly, |
|
173 | base_start_datetime_utc, |
|
174 | base_end_datetime_utc, |
|
175 | period_type) |
|
176 | base = dict() |
|
177 | base['timestamps'] = list() |
|
178 | base['values'] = list() |
|
179 | base['total_in_category'] = Decimal(0.0) |
|
180 | base['total_in_kgce'] = Decimal(0.0) |
|
181 | base['total_in_kgco2e'] = Decimal(0.0) |
|
182 | ||
183 | for row_virtual_meter_periodically in rows_virtual_meter_periodically: |
|
184 | current_datetime_local = row_virtual_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
185 | timedelta(minutes=timezone_offset) |
|
186 | if period_type == 'hourly': |
|
187 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
188 | elif period_type == 'daily': |
|
189 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
190 | elif period_type == 'monthly': |
|
191 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
192 | elif period_type == 'yearly': |
|
193 | current_datetime = current_datetime_local.strftime('%Y') |
|
194 | ||
195 | actual_value = Decimal(0.0) if row_virtual_meter_periodically[1] is None \ |
|
196 | else row_virtual_meter_periodically[1] |
|
197 | base['timestamps'].append(current_datetime) |
|
198 | base['values'].append(actual_value) |
|
199 | base['total_in_category'] += actual_value |
|
200 | base['total_in_kgce'] += actual_value * virtual_meter['kgce'] |
|
201 | base['total_in_kgco2e'] += actual_value * virtual_meter['kgco2e'] |
|
202 | ||
203 | ################################################################################################################ |
|
204 | # Step 3: query reporting period energy consumption |
|
205 | ################################################################################################################ |
|
206 | query = (" SELECT start_datetime_utc, actual_value " |
|
207 | " FROM tbl_virtual_meter_hourly " |
|
208 | " WHERE virtual_meter_id = %s " |
|
209 | " AND start_datetime_utc >= %s " |
|
210 | " AND start_datetime_utc < %s " |
|
211 | " ORDER BY start_datetime_utc ") |
|
212 | cursor_energy.execute(query, (virtual_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
213 | rows_virtual_meter_hourly = cursor_energy.fetchall() |
|
214 | ||
215 | rows_virtual_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_virtual_meter_hourly, |
|
216 | reporting_start_datetime_utc, |
|
217 | reporting_end_datetime_utc, |
|
218 | period_type) |
|
219 | reporting = dict() |
|
220 | reporting['timestamps'] = list() |
|
221 | reporting['values'] = list() |
|
222 | reporting['total_in_category'] = Decimal(0.0) |
|
223 | reporting['total_in_kgce'] = Decimal(0.0) |
|
224 | reporting['total_in_kgco2e'] = Decimal(0.0) |
|
225 | ||
226 | for row_virtual_meter_periodically in rows_virtual_meter_periodically: |
|
227 | current_datetime_local = row_virtual_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
228 | timedelta(minutes=timezone_offset) |
|
229 | if period_type == 'hourly': |
|
230 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
231 | elif period_type == 'daily': |
|
232 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
233 | elif period_type == 'monthly': |
|
234 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
235 | elif period_type == 'yearly': |
|
236 | current_datetime = current_datetime_local.strftime('%Y') |
|
237 | ||
238 | actual_value = Decimal(0.0) if row_virtual_meter_periodically[1] is None \ |
|
239 | else row_virtual_meter_periodically[1] |
|
240 | ||
241 | reporting['timestamps'].append(current_datetime) |
|
242 | reporting['values'].append(actual_value) |
|
243 | reporting['total_in_category'] += actual_value |
|
244 | reporting['total_in_kgce'] += actual_value * virtual_meter['kgce'] |
|
245 | reporting['total_in_kgco2e'] += actual_value * virtual_meter['kgco2e'] |
|
246 | ||
247 | ################################################################################################################ |
|
248 | # Step 5: query tariff data |
|
249 | ################################################################################################################ |
|
250 | parameters_data = dict() |
|
251 | parameters_data['names'] = list() |
|
252 | parameters_data['timestamps'] = list() |
|
253 | parameters_data['values'] = list() |
|
254 | ||
255 | tariff_dict = utilities.get_energy_category_tariffs(virtual_meter['cost_center_id'], |
|
256 | virtual_meter['energy_category_id'], |
|
257 | reporting_start_datetime_utc, |
|
258 | reporting_end_datetime_utc) |
|
259 | tariff_timestamp_list = list() |
|
260 | tariff_value_list = list() |
|
261 | for k, v in tariff_dict.items(): |
|
262 | # convert k from utc to local |
|
263 | k = k + timedelta(minutes=timezone_offset) |
|
264 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
|
265 | tariff_value_list.append(v) |
|
266 | ||
267 | parameters_data['names'].append('TARIFF-' + virtual_meter['energy_category_name']) |
|
268 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
269 | parameters_data['values'].append(tariff_value_list) |
|
270 | ||
271 | ################################################################################################################ |
|
272 | # Step 6: construct the report |
|
273 | ################################################################################################################ |
|
274 | if cursor_system: |
|
275 | cursor_system.close() |
|
276 | if cnx_system: |
|
277 | cnx_system.disconnect() |
|
278 | ||
279 | if cursor_energy: |
|
280 | cursor_energy.close() |
|
281 | if cnx_energy: |
|
282 | cnx_energy.disconnect() |
|
283 | ||
284 | result = { |
|
285 | "virtual_meter": { |
|
286 | "cost_center_id": virtual_meter['cost_center_id'], |
|
287 | "energy_category_id": virtual_meter['energy_category_id'], |
|
288 | "energy_category_name": virtual_meter['energy_category_name'], |
|
289 | "unit_of_measure": virtual_meter['unit_of_measure'], |
|
290 | "kgce": virtual_meter['kgce'], |
|
291 | "kgco2e": virtual_meter['kgco2e'], |
|
292 | }, |
|
293 | "base_period": { |
|
294 | "total_in_category": base['total_in_category'], |
|
295 | "total_in_kgce": base['total_in_kgce'], |
|
296 | "total_in_kgco2e": base['total_in_kgco2e'], |
|
297 | "timestamps": base['timestamps'], |
|
298 | "values": base['values'], |
|
299 | }, |
|
300 | "reporting_period": { |
|
301 | "increment_rate": |
|
302 | (reporting['total_in_category'] - base['total_in_category']) / base['total_in_category'] |
|
303 | if base['total_in_category'] > 0 else None, |
|
304 | "total_in_category": reporting['total_in_category'], |
|
305 | "total_in_kgce": reporting['total_in_kgce'], |
|
306 | "total_in_kgco2e": reporting['total_in_kgco2e'], |
|
307 | "timestamps": reporting['timestamps'], |
|
308 | "values": reporting['values'], |
|
309 | }, |
|
310 | "parameters": { |
|
311 | "names": parameters_data['names'], |
|
312 | "timestamps": parameters_data['timestamps'], |
|
313 | "values": parameters_data['values'] |
|
314 | }, |
|
315 | } |
|
316 | ||
317 | # export result to Excel file and then encode the file to base64 string |
|
318 | result['excel_bytes_base64'] = \ |
|
319 | excelexporters.virtualmeterenergy.export(result, |
|
320 | virtual_meter['name'], |
|
321 | reporting_period_start_datetime_local, |
|
322 | reporting_period_end_datetime_local, |
|
323 | period_type) |
|
324 | ||
325 | resp.body = json.dumps(result) |
|
326 |
@@ 11-322 (lines=312) @@ | ||
8 | import excelexporters.offlinemeterenergy |
|
9 | ||
10 | ||
11 | class Reporting: |
|
12 | @staticmethod |
|
13 | def __init__(): |
|
14 | pass |
|
15 | ||
16 | @staticmethod |
|
17 | def on_options(req, resp): |
|
18 | resp.status = falcon.HTTP_200 |
|
19 | ||
20 | #################################################################################################################### |
|
21 | # PROCEDURES |
|
22 | # Step 1: valid parameters |
|
23 | # Step 2: query the offline meter and energy category |
|
24 | # Step 3: query base period energy consumption |
|
25 | # Step 4: query reporting period energy consumption |
|
26 | # Step 5: query tariff data |
|
27 | # Step 6: construct the report |
|
28 | #################################################################################################################### |
|
29 | @staticmethod |
|
30 | def on_get(req, resp): |
|
31 | print(req.params) |
|
32 | offline_meter_id = req.params.get('offlinemeterid') |
|
33 | period_type = req.params.get('periodtype') |
|
34 | base_period_start_datetime = req.params.get('baseperiodstartdatetime') |
|
35 | base_period_end_datetime = req.params.get('baseperiodenddatetime') |
|
36 | reporting_period_start_datetime = req.params.get('reportingperiodstartdatetime') |
|
37 | reporting_period_end_datetime = req.params.get('reportingperiodenddatetime') |
|
38 | ||
39 | ################################################################################################################ |
|
40 | # Step 1: valid parameters |
|
41 | ################################################################################################################ |
|
42 | if offline_meter_id is None: |
|
43 | raise falcon.HTTPError(falcon.HTTP_400, |
|
44 | title='API.BAD_REQUEST', |
|
45 | description='API.INVALID_OFFLINE_METER_ID') |
|
46 | else: |
|
47 | offline_meter_id = str.strip(offline_meter_id) |
|
48 | if not offline_meter_id.isdigit() or int(offline_meter_id) <= 0: |
|
49 | raise falcon.HTTPError(falcon.HTTP_400, |
|
50 | title='API.BAD_REQUEST', |
|
51 | description='API.INVALID_OFFLINE_METER_ID') |
|
52 | ||
53 | if period_type is None: |
|
54 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
|
55 | else: |
|
56 | period_type = str.strip(period_type) |
|
57 | if period_type not in ['hourly', 'daily', 'monthly', 'yearly']: |
|
58 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
|
59 | ||
60 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
|
61 | if config.utc_offset[0] == '-': |
|
62 | timezone_offset = -timezone_offset |
|
63 | ||
64 | base_start_datetime_utc = None |
|
65 | if base_period_start_datetime is not None and len(str.strip(base_period_start_datetime)) > 0: |
|
66 | base_period_start_datetime = str.strip(base_period_start_datetime) |
|
67 | try: |
|
68 | base_start_datetime_utc = datetime.strptime(base_period_start_datetime, '%Y-%m-%dT%H:%M:%S') |
|
69 | except ValueError: |
|
70 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
71 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
|
72 | base_start_datetime_utc = base_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
73 | timedelta(minutes=timezone_offset) |
|
74 | ||
75 | base_end_datetime_utc = None |
|
76 | if base_period_end_datetime is not None and len(str.strip(base_period_end_datetime)) > 0: |
|
77 | base_period_end_datetime = str.strip(base_period_end_datetime) |
|
78 | try: |
|
79 | base_end_datetime_utc = datetime.strptime(base_period_end_datetime, '%Y-%m-%dT%H:%M:%S') |
|
80 | except ValueError: |
|
81 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
82 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
|
83 | base_end_datetime_utc = base_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
84 | timedelta(minutes=timezone_offset) |
|
85 | ||
86 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
|
87 | base_start_datetime_utc >= base_end_datetime_utc: |
|
88 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
89 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
|
90 | ||
91 | if reporting_period_start_datetime is None: |
|
92 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
93 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
94 | else: |
|
95 | reporting_period_start_datetime = str.strip(reporting_period_start_datetime) |
|
96 | try: |
|
97 | reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime, '%Y-%m-%dT%H:%M:%S') |
|
98 | except ValueError: |
|
99 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
100 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
101 | reporting_start_datetime_utc = reporting_start_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
102 | timedelta(minutes=timezone_offset) |
|
103 | ||
104 | if reporting_period_end_datetime is None: |
|
105 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
106 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
107 | else: |
|
108 | reporting_period_end_datetime = str.strip(reporting_period_end_datetime) |
|
109 | try: |
|
110 | reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime, '%Y-%m-%dT%H:%M:%S') |
|
111 | except ValueError: |
|
112 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
113 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
114 | reporting_end_datetime_utc = reporting_end_datetime_utc.replace(tzinfo=timezone.utc) - \ |
|
115 | timedelta(minutes=timezone_offset) |
|
116 | ||
117 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
|
118 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
119 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
|
120 | ||
121 | ################################################################################################################ |
|
122 | # Step 2: query the offline meter and energy category |
|
123 | ################################################################################################################ |
|
124 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
|
125 | cursor_system = cnx_system.cursor() |
|
126 | ||
127 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
|
128 | cursor_energy = cnx_energy.cursor() |
|
129 | ||
130 | cursor_system.execute(" SELECT m.id, m.name, m.cost_center_id, m.energy_category_id, " |
|
131 | " ec.name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
|
132 | " FROM tbl_offline_meters m, tbl_energy_categories ec " |
|
133 | " WHERE m.id = %s AND m.energy_category_id = ec.id ", (offline_meter_id,)) |
|
134 | row_offline_meter = cursor_system.fetchone() |
|
135 | if row_offline_meter is None: |
|
136 | if cursor_system: |
|
137 | cursor_system.close() |
|
138 | if cnx_system: |
|
139 | cnx_system.disconnect() |
|
140 | ||
141 | if cursor_energy: |
|
142 | cursor_energy.close() |
|
143 | if cnx_energy: |
|
144 | cnx_energy.disconnect() |
|
145 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.OFFLINE_METER_NOT_FOUND') |
|
146 | ||
147 | offline_meter = dict() |
|
148 | offline_meter['id'] = row_offline_meter[0] |
|
149 | offline_meter['name'] = row_offline_meter[1] |
|
150 | offline_meter['cost_center_id'] = row_offline_meter[2] |
|
151 | offline_meter['energy_category_id'] = row_offline_meter[3] |
|
152 | offline_meter['energy_category_name'] = row_offline_meter[4] |
|
153 | offline_meter['unit_of_measure'] = row_offline_meter[5] |
|
154 | offline_meter['kgce'] = row_offline_meter[6] |
|
155 | offline_meter['kgco2e'] = row_offline_meter[7] |
|
156 | ||
157 | ################################################################################################################ |
|
158 | # Step 3: query base period energy consumption |
|
159 | ################################################################################################################ |
|
160 | query = (" SELECT start_datetime_utc, actual_value " |
|
161 | " FROM tbl_offline_meter_hourly " |
|
162 | " WHERE offline_meter_id = %s " |
|
163 | " AND start_datetime_utc >= %s " |
|
164 | " AND start_datetime_utc < %s " |
|
165 | " ORDER BY start_datetime_utc ") |
|
166 | cursor_energy.execute(query, (offline_meter['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
167 | rows_offline_meter_hourly = cursor_energy.fetchall() |
|
168 | ||
169 | rows_offline_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_offline_meter_hourly, |
|
170 | base_start_datetime_utc, |
|
171 | base_end_datetime_utc, |
|
172 | period_type) |
|
173 | base = dict() |
|
174 | base['timestamps'] = list() |
|
175 | base['values'] = list() |
|
176 | base['total_in_category'] = Decimal(0.0) |
|
177 | base['total_in_kgce'] = Decimal(0.0) |
|
178 | base['total_in_kgco2e'] = Decimal(0.0) |
|
179 | ||
180 | for row_offline_meter_periodically in rows_offline_meter_periodically: |
|
181 | current_datetime_local = row_offline_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
182 | timedelta(minutes=timezone_offset) |
|
183 | if period_type == 'hourly': |
|
184 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
185 | elif period_type == 'daily': |
|
186 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
187 | elif period_type == 'monthly': |
|
188 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
189 | elif period_type == 'yearly': |
|
190 | current_datetime = current_datetime_local.strftime('%Y') |
|
191 | ||
192 | actual_value = Decimal(0.0) if row_offline_meter_periodically[1] is None \ |
|
193 | else row_offline_meter_periodically[1] |
|
194 | base['timestamps'].append(current_datetime) |
|
195 | base['values'].append(actual_value) |
|
196 | base['total_in_category'] += actual_value |
|
197 | base['total_in_kgce'] += actual_value * offline_meter['kgce'] |
|
198 | base['total_in_kgco2e'] += actual_value * offline_meter['kgco2e'] |
|
199 | ################################################################################################################ |
|
200 | # Step 4: query reporting period energy consumption |
|
201 | ################################################################################################################ |
|
202 | ||
203 | query = (" SELECT start_datetime_utc, actual_value " |
|
204 | " FROM tbl_offline_meter_hourly " |
|
205 | " WHERE offline_meter_id = %s " |
|
206 | " AND start_datetime_utc >= %s " |
|
207 | " AND start_datetime_utc < %s " |
|
208 | " ORDER BY start_datetime_utc ") |
|
209 | cursor_energy.execute(query, (offline_meter['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
210 | rows_offline_meter_hourly = cursor_energy.fetchall() |
|
211 | ||
212 | rows_offline_meter_periodically = utilities.aggregate_hourly_data_by_period(rows_offline_meter_hourly, |
|
213 | reporting_start_datetime_utc, |
|
214 | reporting_end_datetime_utc, |
|
215 | period_type) |
|
216 | reporting = dict() |
|
217 | reporting['timestamps'] = list() |
|
218 | reporting['values'] = list() |
|
219 | reporting['total_in_category'] = Decimal(0.0) |
|
220 | reporting['total_in_kgce'] = Decimal(0.0) |
|
221 | reporting['total_in_kgco2e'] = Decimal(0.0) |
|
222 | ||
223 | for row_offline_meter_periodically in rows_offline_meter_periodically: |
|
224 | current_datetime_local = row_offline_meter_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
225 | timedelta(minutes=timezone_offset) |
|
226 | if period_type == 'hourly': |
|
227 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
228 | elif period_type == 'daily': |
|
229 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
230 | elif period_type == 'monthly': |
|
231 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
232 | elif period_type == 'yearly': |
|
233 | current_datetime = current_datetime_local.strftime('%Y') |
|
234 | ||
235 | actual_value = Decimal(0.0) if row_offline_meter_periodically[1] is None \ |
|
236 | else row_offline_meter_periodically[1] |
|
237 | ||
238 | reporting['timestamps'].append(current_datetime) |
|
239 | reporting['values'].append(actual_value) |
|
240 | reporting['total_in_category'] += actual_value |
|
241 | reporting['total_in_kgce'] += actual_value * offline_meter['kgce'] |
|
242 | reporting['total_in_kgco2e'] += actual_value * offline_meter['kgco2e'] |
|
243 | ||
244 | ################################################################################################################ |
|
245 | # Step 5: query tariff data |
|
246 | ################################################################################################################ |
|
247 | parameters_data = dict() |
|
248 | parameters_data['names'] = list() |
|
249 | parameters_data['timestamps'] = list() |
|
250 | parameters_data['values'] = list() |
|
251 | ||
252 | tariff_dict = utilities.get_energy_category_tariffs(offline_meter['cost_center_id'], |
|
253 | offline_meter['energy_category_id'], |
|
254 | reporting_start_datetime_utc, |
|
255 | reporting_end_datetime_utc) |
|
256 | tariff_timestamp_list = list() |
|
257 | tariff_value_list = list() |
|
258 | for k, v in tariff_dict.items(): |
|
259 | # convert k from utc to local |
|
260 | k = k + timedelta(minutes=timezone_offset) |
|
261 | tariff_timestamp_list.append(k.isoformat()[0:19]) |
|
262 | tariff_value_list.append(v) |
|
263 | ||
264 | parameters_data['names'].append('TARIFF-' + offline_meter['energy_category_name']) |
|
265 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
266 | parameters_data['values'].append(tariff_value_list) |
|
267 | ||
268 | ################################################################################################################ |
|
269 | # Step 6: construct the report |
|
270 | ################################################################################################################ |
|
271 | if cursor_system: |
|
272 | cursor_system.close() |
|
273 | if cnx_system: |
|
274 | cnx_system.disconnect() |
|
275 | ||
276 | if cursor_energy: |
|
277 | cursor_energy.close() |
|
278 | if cnx_energy: |
|
279 | cnx_energy.disconnect() |
|
280 | ||
281 | result = { |
|
282 | "offline_meter": { |
|
283 | "cost_center_id": offline_meter['cost_center_id'], |
|
284 | "energy_category_id": offline_meter['energy_category_id'], |
|
285 | "energy_category_name": offline_meter['energy_category_name'], |
|
286 | "unit_of_measure": offline_meter['unit_of_measure'], |
|
287 | "kgce": offline_meter['kgce'], |
|
288 | "kgco2e": offline_meter['kgco2e'], |
|
289 | }, |
|
290 | "base_period": { |
|
291 | "total_in_category": base['total_in_category'], |
|
292 | "total_in_kgce": base['total_in_kgce'], |
|
293 | "total_in_kgco2e": base['total_in_kgco2e'], |
|
294 | "timestamps": base['timestamps'], |
|
295 | "values": base['values'], |
|
296 | }, |
|
297 | "reporting_period": { |
|
298 | "increment_rate": |
|
299 | (reporting['total_in_category'] - base['total_in_category']) / base['total_in_category'] |
|
300 | if base['total_in_category'] > 0 else None, |
|
301 | "total_in_category": reporting['total_in_category'], |
|
302 | "total_in_kgce": reporting['total_in_kgce'], |
|
303 | "total_in_kgco2e": reporting['total_in_kgco2e'], |
|
304 | "timestamps": reporting['timestamps'], |
|
305 | "values": reporting['values'], |
|
306 | }, |
|
307 | "parameters": { |
|
308 | "names": parameters_data['names'], |
|
309 | "timestamps": parameters_data['timestamps'], |
|
310 | "values": parameters_data['values'] |
|
311 | }, |
|
312 | } |
|
313 | ||
314 | # export result to Excel file and then encode the file to base64 string |
|
315 | result['excel_bytes_base64'] = \ |
|
316 | excelexporters.offlinemeterenergy.export(result, |
|
317 | offline_meter['name'], |
|
318 | reporting_period_start_datetime, |
|
319 | reporting_period_end_datetime, |
|
320 | period_type) |
|
321 | ||
322 | resp.body = json.dumps(result) |
|
323 |