| @@ 10-519 (lines=510) @@ | ||
| 7 | from decimal import Decimal |
|
| 8 | ||
| 9 | ||
| 10 | class Reporting: |
|
| 11 | @staticmethod |
|
| 12 | def __init__(): |
|
| 13 | pass |
|
| 14 | ||
| 15 | @staticmethod |
|
| 16 | def on_options(req, resp): |
|
| 17 | resp.status = falcon.HTTP_200 |
|
| 18 | ||
| 19 | #################################################################################################################### |
|
| 20 | # PROCEDURES |
|
| 21 | # Step 1: valid parameters |
|
| 22 | # Step 2: query the combined equipment |
|
| 23 | # Step 3: query energy items |
|
| 24 | # Step 4: query associated points |
|
| 25 | # Step 5: query base period energy input |
|
| 26 | # Step 6: query reporting period energy input |
|
| 27 | # Step 7: query tariff data |
|
| 28 | # Step 8: query associated points data |
|
| 29 | # Step 9: construct the report |
|
| 30 | #################################################################################################################### |
|
| 31 | @staticmethod |
|
| 32 | def on_get(req, resp): |
|
| 33 | print(req.params) |
|
| 34 | combined_equipment_id = req.params.get('combinedequipmentid') |
|
| 35 | period_type = req.params.get('periodtype') |
|
| 36 | base_start_datetime_local = req.params.get('baseperiodstartdatetime') |
|
| 37 | base_end_datetime_local = req.params.get('baseperiodenddatetime') |
|
| 38 | reporting_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
|
| 39 | reporting_end_datetime_local = req.params.get('reportingperiodenddatetime') |
|
| 40 | ||
| 41 | ################################################################################################################ |
|
| 42 | # Step 1: valid parameters |
|
| 43 | ################################################################################################################ |
|
| 44 | if combined_equipment_id is None: |
|
| 45 | raise falcon.HTTPError(falcon.HTTP_400, |
|
| 46 | title='API.BAD_REQUEST', |
|
| 47 | description='API.INVALID_COMBINED_EQUIPMENT_ID') |
|
| 48 | else: |
|
| 49 | combined_equipment_id = str.strip(combined_equipment_id) |
|
| 50 | if not combined_equipment_id.isdigit() or int(combined_equipment_id) <= 0: |
|
| 51 | raise falcon.HTTPError(falcon.HTTP_400, |
|
| 52 | title='API.BAD_REQUEST', |
|
| 53 | description='API.INVALID_COMBINED_EQUIPMENT_ID') |
|
| 54 | ||
| 55 | if period_type is None: |
|
| 56 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
|
| 57 | else: |
|
| 58 | period_type = str.strip(period_type) |
|
| 59 | if period_type not in ['hourly', 'daily', 'monthly', 'yearly']: |
|
| 60 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
|
| 61 | ||
| 62 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
|
| 63 | if config.utc_offset[0] == '-': |
|
| 64 | timezone_offset = -timezone_offset |
|
| 65 | ||
| 66 | base_start_datetime_utc = None |
|
| 67 | if base_start_datetime_local is not None and len(str.strip(base_start_datetime_local)) > 0: |
|
| 68 | base_start_datetime_local = str.strip(base_start_datetime_local) |
|
| 69 | try: |
|
| 70 | base_start_datetime_utc = datetime.strptime(base_start_datetime_local, |
|
| 71 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
| 72 | timedelta(minutes=timezone_offset) |
|
| 73 | except ValueError: |
|
| 74 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 75 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
|
| 76 | ||
| 77 | base_end_datetime_utc = None |
|
| 78 | if base_end_datetime_local is not None and len(str.strip(base_end_datetime_local)) > 0: |
|
| 79 | base_end_datetime_local = str.strip(base_end_datetime_local) |
|
| 80 | try: |
|
| 81 | base_end_datetime_utc = datetime.strptime(base_end_datetime_local, |
|
| 82 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
| 83 | timedelta(minutes=timezone_offset) |
|
| 84 | except ValueError: |
|
| 85 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 86 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
|
| 87 | ||
| 88 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
|
| 89 | base_start_datetime_utc >= base_end_datetime_utc: |
|
| 90 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 91 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
|
| 92 | ||
| 93 | if reporting_start_datetime_local is None: |
|
| 94 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 95 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
| 96 | else: |
|
| 97 | reporting_start_datetime_local = str.strip(reporting_start_datetime_local) |
|
| 98 | try: |
|
| 99 | reporting_start_datetime_utc = datetime.strptime(reporting_start_datetime_local, |
|
| 100 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
| 101 | timedelta(minutes=timezone_offset) |
|
| 102 | except ValueError: |
|
| 103 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 104 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
| 105 | ||
| 106 | if reporting_end_datetime_local is None: |
|
| 107 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 108 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
| 109 | else: |
|
| 110 | reporting_end_datetime_local = str.strip(reporting_end_datetime_local) |
|
| 111 | try: |
|
| 112 | reporting_end_datetime_utc = datetime.strptime(reporting_end_datetime_local, |
|
| 113 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
| 114 | timedelta(minutes=timezone_offset) |
|
| 115 | except ValueError: |
|
| 116 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 117 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
| 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 combined equipment |
|
| 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 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
|
| 133 | cursor_historical = cnx_historical.cursor() |
|
| 134 | ||
| 135 | cursor_system.execute(" SELECT id, name, cost_center_id " |
|
| 136 | " FROM tbl_combined_equipments " |
|
| 137 | " WHERE id = %s ", (combined_equipment_id,)) |
|
| 138 | row_combined_equipment = cursor_system.fetchone() |
|
| 139 | if row_combined_equipment is None: |
|
| 140 | if cursor_system: |
|
| 141 | cursor_system.close() |
|
| 142 | if cnx_system: |
|
| 143 | cnx_system.disconnect() |
|
| 144 | ||
| 145 | if cursor_energy: |
|
| 146 | cursor_energy.close() |
|
| 147 | if cnx_energy: |
|
| 148 | cnx_energy.disconnect() |
|
| 149 | ||
| 150 | if cnx_historical: |
|
| 151 | cnx_historical.close() |
|
| 152 | if cursor_historical: |
|
| 153 | cursor_historical.disconnect() |
|
| 154 | raise falcon.HTTPError(falcon.HTTP_404, |
|
| 155 | title='API.NOT_FOUND', |
|
| 156 | description='API.COMBINED_EQUIPMENT_NOT_FOUND') |
|
| 157 | ||
| 158 | combined_equipment = dict() |
|
| 159 | combined_equipment['id'] = row_combined_equipment[0] |
|
| 160 | combined_equipment['name'] = row_combined_equipment[1] |
|
| 161 | combined_equipment['cost_center_id'] = row_combined_equipment[2] |
|
| 162 | ||
| 163 | ################################################################################################################ |
|
| 164 | # Step 3: query energy items |
|
| 165 | ################################################################################################################ |
|
| 166 | energy_item_set = set() |
|
| 167 | # query energy items in base period |
|
| 168 | cursor_energy.execute(" SELECT DISTINCT(energy_item_id) " |
|
| 169 | " FROM tbl_combined_equipment_input_item_hourly " |
|
| 170 | " WHERE combined_equipment_id = %s " |
|
| 171 | " AND start_datetime_utc >= %s " |
|
| 172 | " AND start_datetime_utc < %s ", |
|
| 173 | (combined_equipment['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
| 174 | rows_energy_items = cursor_energy.fetchall() |
|
| 175 | if rows_energy_items is not None or len(rows_energy_items) > 0: |
|
| 176 | for row_item in rows_energy_items: |
|
| 177 | energy_item_set.add(row_item[0]) |
|
| 178 | ||
| 179 | # query energy items in reporting period |
|
| 180 | cursor_energy.execute(" SELECT DISTINCT(energy_item_id) " |
|
| 181 | " FROM tbl_combined_equipment_input_item_hourly " |
|
| 182 | " WHERE combined_equipment_id = %s " |
|
| 183 | " AND start_datetime_utc >= %s " |
|
| 184 | " AND start_datetime_utc < %s ", |
|
| 185 | (combined_equipment['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
| 186 | rows_energy_items = cursor_energy.fetchall() |
|
| 187 | if rows_energy_items is not None or len(rows_energy_items) > 0: |
|
| 188 | for row_item in rows_energy_items: |
|
| 189 | energy_item_set.add(row_item[0]) |
|
| 190 | ||
| 191 | # query all energy items in base period and reporting period |
|
| 192 | cursor_system.execute(" SELECT ei.id, ei.name, ei.energy_category_id, " |
|
| 193 | " ec.name AS energy_category_name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
|
| 194 | " FROM tbl_energy_items ei, tbl_energy_categories ec " |
|
| 195 | " WHERE ei.energy_category_id = ec.id " |
|
| 196 | " ORDER BY ei.id ", ) |
|
| 197 | rows_energy_items = cursor_system.fetchall() |
|
| 198 | if rows_energy_items is None or len(rows_energy_items) == 0: |
|
| 199 | if cursor_system: |
|
| 200 | cursor_system.close() |
|
| 201 | if cnx_system: |
|
| 202 | cnx_system.disconnect() |
|
| 203 | ||
| 204 | if cursor_energy: |
|
| 205 | cursor_energy.close() |
|
| 206 | if cnx_energy: |
|
| 207 | cnx_energy.disconnect() |
|
| 208 | ||
| 209 | if cnx_historical: |
|
| 210 | cnx_historical.close() |
|
| 211 | if cursor_historical: |
|
| 212 | cursor_historical.disconnect() |
|
| 213 | raise falcon.HTTPError(falcon.HTTP_404, |
|
| 214 | title='API.NOT_FOUND', |
|
| 215 | description='API.ENERGY_ITEM_NOT_FOUND') |
|
| 216 | energy_item_dict = dict() |
|
| 217 | for row_energy_item in rows_energy_items: |
|
| 218 | if row_energy_item[0] in energy_item_set: |
|
| 219 | energy_item_dict[row_energy_item[0]] = {"name": row_energy_item[1], |
|
| 220 | "energy_category_id": row_energy_item[2], |
|
| 221 | "energy_category_name": row_energy_item[3], |
|
| 222 | "unit_of_measure": row_energy_item[4], |
|
| 223 | "kgce": row_energy_item[5], |
|
| 224 | "kgco2e": row_energy_item[6]} |
|
| 225 | ||
| 226 | ################################################################################################################ |
|
| 227 | # Step 4: query associated points |
|
| 228 | ################################################################################################################ |
|
| 229 | point_list = list() |
|
| 230 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
| 231 | " FROM tbl_combined_equipments e, tbl_combined_equipments_parameters ep, tbl_points p " |
|
| 232 | " WHERE e.id = %s AND e.id = ep.combined_equipment_id AND ep.parameter_type = 'point' " |
|
| 233 | " AND ep.point_id = p.id " |
|
| 234 | " ORDER BY p.id ", (combined_equipment['id'],)) |
|
| 235 | rows_points = cursor_system.fetchall() |
|
| 236 | if rows_points is not None and len(rows_points) > 0: |
|
| 237 | for row in rows_points: |
|
| 238 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
| 239 | ||
| 240 | ################################################################################################################ |
|
| 241 | # Step 5: query base period energy input |
|
| 242 | ################################################################################################################ |
|
| 243 | base = dict() |
|
| 244 | if energy_item_set is not None and len(energy_item_set) > 0: |
|
| 245 | for energy_item_id in energy_item_set: |
|
| 246 | base[energy_item_id] = dict() |
|
| 247 | base[energy_item_id]['timestamps'] = list() |
|
| 248 | base[energy_item_id]['values'] = list() |
|
| 249 | base[energy_item_id]['subtotal'] = Decimal(0.0) |
|
| 250 | ||
| 251 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
| 252 | " FROM tbl_combined_equipment_input_item_hourly " |
|
| 253 | " WHERE combined_equipment_id = %s " |
|
| 254 | " AND energy_item_id = %s " |
|
| 255 | " AND start_datetime_utc >= %s " |
|
| 256 | " AND start_datetime_utc < %s " |
|
| 257 | " ORDER BY start_datetime_utc ", |
|
| 258 | (combined_equipment['id'], |
|
| 259 | energy_item_id, |
|
| 260 | base_start_datetime_utc, |
|
| 261 | base_end_datetime_utc)) |
|
| 262 | rows_combined_equipment_hourly = cursor_energy.fetchall() |
|
| 263 | ||
| 264 | rows_combined_equipment_periodically = \ |
|
| 265 | utilities.aggregate_hourly_data_by_period(rows_combined_equipment_hourly, |
|
| 266 | base_start_datetime_utc, |
|
| 267 | base_end_datetime_utc, |
|
| 268 | period_type) |
|
| 269 | for row_combined_equipment_periodically in rows_combined_equipment_periodically: |
|
| 270 | current_datetime_local = row_combined_equipment_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
| 271 | timedelta(minutes=timezone_offset) |
|
| 272 | if period_type == 'hourly': |
|
| 273 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
| 274 | elif period_type == 'daily': |
|
| 275 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
| 276 | elif period_type == 'monthly': |
|
| 277 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
| 278 | elif period_type == 'yearly': |
|
| 279 | current_datetime = current_datetime_local.strftime('%Y') |
|
| 280 | ||
| 281 | actual_value = Decimal(0.0) if row_combined_equipment_periodically[1] is None \ |
|
| 282 | else row_combined_equipment_periodically[1] |
|
| 283 | base[energy_item_id]['timestamps'].append(current_datetime) |
|
| 284 | base[energy_item_id]['values'].append(actual_value) |
|
| 285 | base[energy_item_id]['subtotal'] += actual_value |
|
| 286 | ||
| 287 | ################################################################################################################ |
|
| 288 | # Step 6: query reporting period energy input |
|
| 289 | ################################################################################################################ |
|
| 290 | reporting = dict() |
|
| 291 | if energy_item_set is not None and len(energy_item_set) > 0: |
|
| 292 | for energy_item_id in energy_item_set: |
|
| 293 | reporting[energy_item_id] = dict() |
|
| 294 | reporting[energy_item_id]['timestamps'] = list() |
|
| 295 | reporting[energy_item_id]['values'] = list() |
|
| 296 | reporting[energy_item_id]['subtotal'] = Decimal(0.0) |
|
| 297 | reporting[energy_item_id]['toppeak'] = Decimal(0.0) |
|
| 298 | reporting[energy_item_id]['onpeak'] = Decimal(0.0) |
|
| 299 | reporting[energy_item_id]['midpeak'] = Decimal(0.0) |
|
| 300 | reporting[energy_item_id]['offpeak'] = Decimal(0.0) |
|
| 301 | ||
| 302 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
| 303 | " FROM tbl_combined_equipment_input_item_hourly " |
|
| 304 | " WHERE combined_equipment_id = %s " |
|
| 305 | " AND energy_item_id = %s " |
|
| 306 | " AND start_datetime_utc >= %s " |
|
| 307 | " AND start_datetime_utc < %s " |
|
| 308 | " ORDER BY start_datetime_utc ", |
|
| 309 | (combined_equipment['id'], |
|
| 310 | energy_item_id, |
|
| 311 | reporting_start_datetime_utc, |
|
| 312 | reporting_end_datetime_utc)) |
|
| 313 | rows_combined_equipment_hourly = cursor_energy.fetchall() |
|
| 314 | ||
| 315 | rows_combined_equipment_periodically = \ |
|
| 316 | utilities.aggregate_hourly_data_by_period(rows_combined_equipment_hourly, |
|
| 317 | reporting_start_datetime_utc, |
|
| 318 | reporting_end_datetime_utc, |
|
| 319 | period_type) |
|
| 320 | for row_combined_equipment_periodically in rows_combined_equipment_periodically: |
|
| 321 | current_datetime_local = row_combined_equipment_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
| 322 | timedelta(minutes=timezone_offset) |
|
| 323 | if period_type == 'hourly': |
|
| 324 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
| 325 | elif period_type == 'daily': |
|
| 326 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
| 327 | elif period_type == 'monthly': |
|
| 328 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
| 329 | elif period_type == 'yearly': |
|
| 330 | current_datetime = current_datetime_local.strftime('%Y') |
|
| 331 | ||
| 332 | actual_value = Decimal(0.0) if row_combined_equipment_periodically[1] is None \ |
|
| 333 | else row_combined_equipment_periodically[1] |
|
| 334 | reporting[energy_item_id]['timestamps'].append(current_datetime) |
|
| 335 | reporting[energy_item_id]['values'].append(actual_value) |
|
| 336 | reporting[energy_item_id]['subtotal'] += actual_value |
|
| 337 | ||
| 338 | energy_category_tariff_dict = \ |
|
| 339 | utilities.get_energy_category_peak_types(combined_equipment['cost_center_id'], |
|
| 340 | energy_item_dict[energy_item_id]['energy_category_id'], |
|
| 341 | reporting_start_datetime_utc, |
|
| 342 | reporting_end_datetime_utc) |
|
| 343 | for row in rows_combined_equipment_hourly: |
|
| 344 | peak_type = energy_category_tariff_dict.get(row[0], None) |
|
| 345 | if peak_type == 'toppeak': |
|
| 346 | reporting[energy_item_id]['toppeak'] += row[1] |
|
| 347 | elif peak_type == 'onpeak': |
|
| 348 | reporting[energy_item_id]['onpeak'] += row[1] |
|
| 349 | elif peak_type == 'midpeak': |
|
| 350 | reporting[energy_item_id]['midpeak'] += row[1] |
|
| 351 | elif peak_type == 'offpeak': |
|
| 352 | reporting[energy_item_id]['offpeak'] += row[1] |
|
| 353 | ||
| 354 | ################################################################################################################ |
|
| 355 | # Step 7: query tariff data |
|
| 356 | ################################################################################################################ |
|
| 357 | parameters_data = dict() |
|
| 358 | parameters_data['names'] = list() |
|
| 359 | parameters_data['timestamps'] = list() |
|
| 360 | parameters_data['values'] = list() |
|
| 361 | if energy_item_set is not None and len(energy_item_set) > 0: |
|
| 362 | for energy_item_id in energy_item_set: |
|
| 363 | energy_category_tariff_dict = \ |
|
| 364 | utilities.get_energy_category_tariffs(combined_equipment['cost_center_id'], |
|
| 365 | energy_item_dict[energy_item_id]['energy_category_id'], |
|
| 366 | reporting_start_datetime_utc, |
|
| 367 | reporting_end_datetime_utc) |
|
| 368 | tariff_timestamp_list = list() |
|
| 369 | tariff_value_list = list() |
|
| 370 | for k, v in energy_category_tariff_dict.items(): |
|
| 371 | # convert k from utc to local |
|
| 372 | k = k + timedelta(minutes=timezone_offset) |
|
| 373 | tariff_timestamp_list.append(k.isoformat()[0:19][0:19]) |
|
| 374 | tariff_value_list.append(v) |
|
| 375 | ||
| 376 | parameters_data['names'].append('TARIFF-' + energy_item_dict[energy_item_id]['name']) |
|
| 377 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
| 378 | parameters_data['values'].append(tariff_value_list) |
|
| 379 | ||
| 380 | ################################################################################################################ |
|
| 381 | # Step 8: query associated points data |
|
| 382 | ################################################################################################################ |
|
| 383 | for point in point_list: |
|
| 384 | point_values = [] |
|
| 385 | point_timestamps = [] |
|
| 386 | if point['object_type'] == 'ANALOG_VALUE': |
|
| 387 | query = (" SELECT utc_date_time, actual_value " |
|
| 388 | " FROM tbl_analog_value " |
|
| 389 | " WHERE point_id = %s " |
|
| 390 | " AND utc_date_time BETWEEN %s AND %s " |
|
| 391 | " ORDER BY utc_date_time ") |
|
| 392 | cursor_historical.execute(query, (point['id'], |
|
| 393 | reporting_start_datetime_utc, |
|
| 394 | reporting_end_datetime_utc)) |
|
| 395 | rows = cursor_historical.fetchall() |
|
| 396 | ||
| 397 | if rows is not None and len(rows) > 0: |
|
| 398 | for row in rows: |
|
| 399 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
| 400 | timedelta(minutes=timezone_offset) |
|
| 401 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
| 402 | point_timestamps.append(current_datetime) |
|
| 403 | point_values.append(row[1]) |
|
| 404 | ||
| 405 | elif point['object_type'] == 'ENERGY_VALUE': |
|
| 406 | query = (" SELECT utc_date_time, actual_value " |
|
| 407 | " FROM tbl_energy_value " |
|
| 408 | " WHERE point_id = %s " |
|
| 409 | " AND utc_date_time BETWEEN %s AND %s " |
|
| 410 | " ORDER BY utc_date_time ") |
|
| 411 | cursor_historical.execute(query, (point['id'], |
|
| 412 | reporting_start_datetime_utc, |
|
| 413 | reporting_end_datetime_utc)) |
|
| 414 | rows = cursor_historical.fetchall() |
|
| 415 | ||
| 416 | if rows is not None and len(rows) > 0: |
|
| 417 | for row in rows: |
|
| 418 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
| 419 | timedelta(minutes=timezone_offset) |
|
| 420 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
| 421 | point_timestamps.append(current_datetime) |
|
| 422 | point_values.append(row[1]) |
|
| 423 | elif point['object_type'] == 'DIGITAL_VALUE': |
|
| 424 | query = (" SELECT utc_date_time, actual_value " |
|
| 425 | " FROM tbl_digital_value " |
|
| 426 | " WHERE point_id = %s " |
|
| 427 | " AND utc_date_time BETWEEN %s AND %s ") |
|
| 428 | cursor_historical.execute(query, (point['id'], |
|
| 429 | reporting_start_datetime_utc, |
|
| 430 | reporting_end_datetime_utc)) |
|
| 431 | rows = cursor_historical.fetchall() |
|
| 432 | ||
| 433 | if rows is not None and len(rows) > 0: |
|
| 434 | for row in rows: |
|
| 435 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
| 436 | timedelta(minutes=timezone_offset) |
|
| 437 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
| 438 | point_timestamps.append(current_datetime) |
|
| 439 | point_values.append(row[1]) |
|
| 440 | ||
| 441 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
|
| 442 | parameters_data['timestamps'].append(point_timestamps) |
|
| 443 | parameters_data['values'].append(point_values) |
|
| 444 | ||
| 445 | ################################################################################################################ |
|
| 446 | # Step 9: construct the report |
|
| 447 | ################################################################################################################ |
|
| 448 | if cursor_system: |
|
| 449 | cursor_system.close() |
|
| 450 | if cnx_system: |
|
| 451 | cnx_system.disconnect() |
|
| 452 | ||
| 453 | if cursor_energy: |
|
| 454 | cursor_energy.close() |
|
| 455 | if cnx_energy: |
|
| 456 | cnx_energy.disconnect() |
|
| 457 | ||
| 458 | result = dict() |
|
| 459 | ||
| 460 | result['combined_equipment'] = dict() |
|
| 461 | result['combined_equipment']['name'] = combined_equipment['name'] |
|
| 462 | ||
| 463 | result['base_period'] = dict() |
|
| 464 | result['base_period']['names'] = list() |
|
| 465 | result['base_period']['units'] = list() |
|
| 466 | result['base_period']['timestamps'] = list() |
|
| 467 | result['base_period']['values'] = list() |
|
| 468 | result['base_period']['subtotals'] = list() |
|
| 469 | if energy_item_set is not None and len(energy_item_set) > 0: |
|
| 470 | for energy_item_id in energy_item_set: |
|
| 471 | result['base_period']['names'].append(energy_item_dict[energy_item_id]['name']) |
|
| 472 | result['base_period']['units'].append(energy_item_dict[energy_item_id]['unit_of_measure']) |
|
| 473 | result['base_period']['timestamps'].append(base[energy_item_id]['timestamps']) |
|
| 474 | result['base_period']['values'].append(base[energy_item_id]['values']) |
|
| 475 | result['base_period']['subtotals'].append(base[energy_item_id]['subtotal']) |
|
| 476 | ||
| 477 | result['reporting_period'] = dict() |
|
| 478 | result['reporting_period']['names'] = list() |
|
| 479 | result['reporting_period']['energy_item_ids'] = list() |
|
| 480 | result['reporting_period']['energy_category_names'] = list() |
|
| 481 | result['reporting_period']['energy_category_ids'] = list() |
|
| 482 | result['reporting_period']['units'] = list() |
|
| 483 | result['reporting_period']['timestamps'] = list() |
|
| 484 | result['reporting_period']['values'] = list() |
|
| 485 | result['reporting_period']['subtotals'] = list() |
|
| 486 | result['reporting_period']['toppeaks'] = list() |
|
| 487 | result['reporting_period']['onpeaks'] = list() |
|
| 488 | result['reporting_period']['midpeaks'] = list() |
|
| 489 | result['reporting_period']['offpeaks'] = list() |
|
| 490 | result['reporting_period']['increment_rates'] = list() |
|
| 491 | ||
| 492 | if energy_item_set is not None and len(energy_item_set) > 0: |
|
| 493 | for energy_item_id in energy_item_set: |
|
| 494 | result['reporting_period']['names'].append(energy_item_dict[energy_item_id]['name']) |
|
| 495 | result['reporting_period']['energy_item_ids'].append(energy_item_id) |
|
| 496 | result['reporting_period']['energy_category_names'].append( |
|
| 497 | energy_item_dict[energy_item_id]['energy_category_name']) |
|
| 498 | result['reporting_period']['energy_category_ids'].append( |
|
| 499 | energy_item_dict[energy_item_id]['energy_category_id']) |
|
| 500 | result['reporting_period']['units'].append(energy_item_dict[energy_item_id]['unit_of_measure']) |
|
| 501 | result['reporting_period']['timestamps'].append(reporting[energy_item_id]['timestamps']) |
|
| 502 | result['reporting_period']['values'].append(reporting[energy_item_id]['values']) |
|
| 503 | result['reporting_period']['subtotals'].append(reporting[energy_item_id]['subtotal']) |
|
| 504 | result['reporting_period']['toppeaks'].append(reporting[energy_item_id]['toppeak']) |
|
| 505 | result['reporting_period']['onpeaks'].append(reporting[energy_item_id]['onpeak']) |
|
| 506 | result['reporting_period']['midpeaks'].append(reporting[energy_item_id]['midpeak']) |
|
| 507 | result['reporting_period']['offpeaks'].append(reporting[energy_item_id]['offpeak']) |
|
| 508 | result['reporting_period']['increment_rates'].append( |
|
| 509 | (reporting[energy_item_id]['subtotal'] - base[energy_item_id]['subtotal']) / |
|
| 510 | base[energy_item_id]['subtotal'] |
|
| 511 | if base[energy_item_id]['subtotal'] > 0.0 else None) |
|
| 512 | ||
| 513 | result['parameters'] = { |
|
| 514 | "names": parameters_data['names'], |
|
| 515 | "timestamps": parameters_data['timestamps'], |
|
| 516 | "values": parameters_data['values'] |
|
| 517 | } |
|
| 518 | ||
| 519 | resp.body = json.dumps(result) |
|
| 520 | ||
| @@ 10-511 (lines=502) @@ | ||
| 7 | from decimal import Decimal |
|
| 8 | ||
| 9 | ||
| 10 | class Reporting: |
|
| 11 | @staticmethod |
|
| 12 | def __init__(): |
|
| 13 | pass |
|
| 14 | ||
| 15 | @staticmethod |
|
| 16 | def on_options(req, resp): |
|
| 17 | resp.status = falcon.HTTP_200 |
|
| 18 | ||
| 19 | #################################################################################################################### |
|
| 20 | # PROCEDURES |
|
| 21 | # Step 1: valid parameters |
|
| 22 | # Step 2: query the equipment |
|
| 23 | # Step 3: query energy items |
|
| 24 | # Step 4: query associated points |
|
| 25 | # Step 5: query base period energy input |
|
| 26 | # Step 6: query reporting period energy input |
|
| 27 | # Step 7: query tariff data |
|
| 28 | # Step 8: query associated points data |
|
| 29 | # Step 9: construct the report |
|
| 30 | #################################################################################################################### |
|
| 31 | @staticmethod |
|
| 32 | def on_get(req, resp): |
|
| 33 | print(req.params) |
|
| 34 | equipment_id = req.params.get('equipmentid') |
|
| 35 | period_type = req.params.get('periodtype') |
|
| 36 | base_start_datetime_local = req.params.get('baseperiodstartdatetime') |
|
| 37 | base_end_datetime_local = req.params.get('baseperiodenddatetime') |
|
| 38 | reporting_start_datetime_local = req.params.get('reportingperiodstartdatetime') |
|
| 39 | reporting_end_datetime_local = req.params.get('reportingperiodenddatetime') |
|
| 40 | ||
| 41 | ################################################################################################################ |
|
| 42 | # Step 1: valid parameters |
|
| 43 | ################################################################################################################ |
|
| 44 | if equipment_id is None: |
|
| 45 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_EQUIPMENT_ID') |
|
| 46 | else: |
|
| 47 | equipment_id = str.strip(equipment_id) |
|
| 48 | if not equipment_id.isdigit() or int(equipment_id) <= 0: |
|
| 49 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_EQUIPMENT_ID') |
|
| 50 | ||
| 51 | if period_type is None: |
|
| 52 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
|
| 53 | else: |
|
| 54 | period_type = str.strip(period_type) |
|
| 55 | if period_type not in ['hourly', 'daily', 'monthly', 'yearly']: |
|
| 56 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE') |
|
| 57 | ||
| 58 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
|
| 59 | if config.utc_offset[0] == '-': |
|
| 60 | timezone_offset = -timezone_offset |
|
| 61 | ||
| 62 | base_start_datetime_utc = None |
|
| 63 | if base_start_datetime_local is not None and len(str.strip(base_start_datetime_local)) > 0: |
|
| 64 | base_start_datetime_local = str.strip(base_start_datetime_local) |
|
| 65 | try: |
|
| 66 | base_start_datetime_utc = datetime.strptime(base_start_datetime_local, |
|
| 67 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
| 68 | timedelta(minutes=timezone_offset) |
|
| 69 | except ValueError: |
|
| 70 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 71 | description="API.INVALID_BASE_PERIOD_START_DATETIME") |
|
| 72 | ||
| 73 | base_end_datetime_utc = None |
|
| 74 | if base_end_datetime_local is not None and len(str.strip(base_end_datetime_local)) > 0: |
|
| 75 | base_end_datetime_local = str.strip(base_end_datetime_local) |
|
| 76 | try: |
|
| 77 | base_end_datetime_utc = datetime.strptime(base_end_datetime_local, |
|
| 78 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
| 79 | timedelta(minutes=timezone_offset) |
|
| 80 | except ValueError: |
|
| 81 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 82 | description="API.INVALID_BASE_PERIOD_END_DATETIME") |
|
| 83 | ||
| 84 | if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \ |
|
| 85 | base_start_datetime_utc >= base_end_datetime_utc: |
|
| 86 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 87 | description='API.INVALID_BASE_PERIOD_END_DATETIME') |
|
| 88 | ||
| 89 | if reporting_start_datetime_local is None: |
|
| 90 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 91 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
| 92 | else: |
|
| 93 | reporting_start_datetime_local = str.strip(reporting_start_datetime_local) |
|
| 94 | try: |
|
| 95 | reporting_start_datetime_utc = datetime.strptime(reporting_start_datetime_local, |
|
| 96 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
| 97 | timedelta(minutes=timezone_offset) |
|
| 98 | except ValueError: |
|
| 99 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 100 | description="API.INVALID_REPORTING_PERIOD_START_DATETIME") |
|
| 101 | ||
| 102 | if reporting_end_datetime_local is None: |
|
| 103 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 104 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
| 105 | else: |
|
| 106 | reporting_end_datetime_local = str.strip(reporting_end_datetime_local) |
|
| 107 | try: |
|
| 108 | reporting_end_datetime_utc = datetime.strptime(reporting_end_datetime_local, |
|
| 109 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
|
| 110 | timedelta(minutes=timezone_offset) |
|
| 111 | except ValueError: |
|
| 112 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 113 | description="API.INVALID_REPORTING_PERIOD_END_DATETIME") |
|
| 114 | ||
| 115 | if reporting_start_datetime_utc >= reporting_end_datetime_utc: |
|
| 116 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
|
| 117 | description='API.INVALID_REPORTING_PERIOD_END_DATETIME') |
|
| 118 | ||
| 119 | ################################################################################################################ |
|
| 120 | # Step 2: query the equipment |
|
| 121 | ################################################################################################################ |
|
| 122 | cnx_system = mysql.connector.connect(**config.myems_system_db) |
|
| 123 | cursor_system = cnx_system.cursor() |
|
| 124 | ||
| 125 | cnx_energy = mysql.connector.connect(**config.myems_energy_db) |
|
| 126 | cursor_energy = cnx_energy.cursor() |
|
| 127 | ||
| 128 | cnx_historical = mysql.connector.connect(**config.myems_historical_db) |
|
| 129 | cursor_historical = cnx_historical.cursor() |
|
| 130 | ||
| 131 | cursor_system.execute(" SELECT id, name, cost_center_id " |
|
| 132 | " FROM tbl_equipments " |
|
| 133 | " WHERE id = %s ", (equipment_id,)) |
|
| 134 | row_equipment = cursor_system.fetchone() |
|
| 135 | if row_equipment 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 | ||
| 146 | if cnx_historical: |
|
| 147 | cnx_historical.close() |
|
| 148 | if cursor_historical: |
|
| 149 | cursor_historical.disconnect() |
|
| 150 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.EQUIPMENT_NOT_FOUND') |
|
| 151 | ||
| 152 | equipment = dict() |
|
| 153 | equipment['id'] = row_equipment[0] |
|
| 154 | equipment['name'] = row_equipment[1] |
|
| 155 | equipment['cost_center_id'] = row_equipment[2] |
|
| 156 | ||
| 157 | ################################################################################################################ |
|
| 158 | # Step 3: query energy items |
|
| 159 | ################################################################################################################ |
|
| 160 | energy_item_set = set() |
|
| 161 | # query energy items in base period |
|
| 162 | cursor_energy.execute(" SELECT DISTINCT(energy_item_id) " |
|
| 163 | " FROM tbl_equipment_input_item_hourly " |
|
| 164 | " WHERE equipment_id = %s " |
|
| 165 | " AND start_datetime_utc >= %s " |
|
| 166 | " AND start_datetime_utc < %s ", |
|
| 167 | (equipment['id'], base_start_datetime_utc, base_end_datetime_utc)) |
|
| 168 | rows_energy_items = cursor_energy.fetchall() |
|
| 169 | if rows_energy_items is not None or len(rows_energy_items) > 0: |
|
| 170 | for row_item in rows_energy_items: |
|
| 171 | energy_item_set.add(row_item[0]) |
|
| 172 | ||
| 173 | # query energy items in reporting period |
|
| 174 | cursor_energy.execute(" SELECT DISTINCT(energy_item_id) " |
|
| 175 | " FROM tbl_equipment_input_item_hourly " |
|
| 176 | " WHERE equipment_id = %s " |
|
| 177 | " AND start_datetime_utc >= %s " |
|
| 178 | " AND start_datetime_utc < %s ", |
|
| 179 | (equipment['id'], reporting_start_datetime_utc, reporting_end_datetime_utc)) |
|
| 180 | rows_energy_items = cursor_energy.fetchall() |
|
| 181 | if rows_energy_items is not None or len(rows_energy_items) > 0: |
|
| 182 | for row_item in rows_energy_items: |
|
| 183 | energy_item_set.add(row_item[0]) |
|
| 184 | ||
| 185 | # query all energy items in base period and reporting period |
|
| 186 | cursor_system.execute(" SELECT ei.id, ei.name, ei.energy_category_id, " |
|
| 187 | " ec.name AS energy_category_name, ec.unit_of_measure, ec.kgce, ec.kgco2e " |
|
| 188 | " FROM tbl_energy_items ei, tbl_energy_categories ec " |
|
| 189 | " WHERE ei.energy_category_id = ec.id " |
|
| 190 | " ORDER BY ei.id ", ) |
|
| 191 | rows_energy_items = cursor_system.fetchall() |
|
| 192 | if rows_energy_items is None or len(rows_energy_items) == 0: |
|
| 193 | if cursor_system: |
|
| 194 | cursor_system.close() |
|
| 195 | if cnx_system: |
|
| 196 | cnx_system.disconnect() |
|
| 197 | ||
| 198 | if cursor_energy: |
|
| 199 | cursor_energy.close() |
|
| 200 | if cnx_energy: |
|
| 201 | cnx_energy.disconnect() |
|
| 202 | ||
| 203 | if cnx_historical: |
|
| 204 | cnx_historical.close() |
|
| 205 | if cursor_historical: |
|
| 206 | cursor_historical.disconnect() |
|
| 207 | raise falcon.HTTPError(falcon.HTTP_404, |
|
| 208 | title='API.NOT_FOUND', |
|
| 209 | description='API.ENERGY_ITEM_NOT_FOUND') |
|
| 210 | energy_item_dict = dict() |
|
| 211 | for row_energy_item in rows_energy_items: |
|
| 212 | if row_energy_item[0] in energy_item_set: |
|
| 213 | energy_item_dict[row_energy_item[0]] = {"name": row_energy_item[1], |
|
| 214 | "energy_category_id": row_energy_item[2], |
|
| 215 | "energy_category_name": row_energy_item[3], |
|
| 216 | "unit_of_measure": row_energy_item[4], |
|
| 217 | "kgce": row_energy_item[5], |
|
| 218 | "kgco2e": row_energy_item[6]} |
|
| 219 | ||
| 220 | ################################################################################################################ |
|
| 221 | # Step 4: query associated points |
|
| 222 | ################################################################################################################ |
|
| 223 | point_list = list() |
|
| 224 | cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type " |
|
| 225 | " FROM tbl_equipments e, tbl_equipments_parameters ep, tbl_points p " |
|
| 226 | " WHERE e.id = %s AND e.id = ep.equipment_id AND ep.parameter_type = 'point' " |
|
| 227 | " AND ep.point_id = p.id " |
|
| 228 | " ORDER BY p.id ", (equipment['id'],)) |
|
| 229 | rows_points = cursor_system.fetchall() |
|
| 230 | if rows_points is not None and len(rows_points) > 0: |
|
| 231 | for row in rows_points: |
|
| 232 | point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]}) |
|
| 233 | ||
| 234 | ################################################################################################################ |
|
| 235 | # Step 5: query base period energy input |
|
| 236 | ################################################################################################################ |
|
| 237 | base = dict() |
|
| 238 | if energy_item_set is not None and len(energy_item_set) > 0: |
|
| 239 | for energy_item_id in energy_item_set: |
|
| 240 | base[energy_item_id] = dict() |
|
| 241 | base[energy_item_id]['timestamps'] = list() |
|
| 242 | base[energy_item_id]['values'] = list() |
|
| 243 | base[energy_item_id]['subtotal'] = Decimal(0.0) |
|
| 244 | ||
| 245 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
| 246 | " FROM tbl_equipment_input_item_hourly " |
|
| 247 | " WHERE equipment_id = %s " |
|
| 248 | " AND energy_item_id = %s " |
|
| 249 | " AND start_datetime_utc >= %s " |
|
| 250 | " AND start_datetime_utc < %s " |
|
| 251 | " ORDER BY start_datetime_utc ", |
|
| 252 | (equipment['id'], |
|
| 253 | energy_item_id, |
|
| 254 | base_start_datetime_utc, |
|
| 255 | base_end_datetime_utc)) |
|
| 256 | rows_equipment_hourly = cursor_energy.fetchall() |
|
| 257 | ||
| 258 | rows_equipment_periodically = utilities.aggregate_hourly_data_by_period(rows_equipment_hourly, |
|
| 259 | base_start_datetime_utc, |
|
| 260 | base_end_datetime_utc, |
|
| 261 | period_type) |
|
| 262 | for row_equipment_periodically in rows_equipment_periodically: |
|
| 263 | current_datetime_local = row_equipment_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
| 264 | timedelta(minutes=timezone_offset) |
|
| 265 | if period_type == 'hourly': |
|
| 266 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
| 267 | elif period_type == 'daily': |
|
| 268 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
| 269 | elif period_type == 'monthly': |
|
| 270 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
| 271 | elif period_type == 'yearly': |
|
| 272 | current_datetime = current_datetime_local.strftime('%Y') |
|
| 273 | ||
| 274 | actual_value = Decimal(0.0) if row_equipment_periodically[1] is None \ |
|
| 275 | else row_equipment_periodically[1] |
|
| 276 | base[energy_item_id]['timestamps'].append(current_datetime) |
|
| 277 | base[energy_item_id]['values'].append(actual_value) |
|
| 278 | base[energy_item_id]['subtotal'] += actual_value |
|
| 279 | ||
| 280 | ################################################################################################################ |
|
| 281 | # Step 6: query reporting period energy input |
|
| 282 | ################################################################################################################ |
|
| 283 | reporting = dict() |
|
| 284 | if energy_item_set is not None and len(energy_item_set) > 0: |
|
| 285 | for energy_item_id in energy_item_set: |
|
| 286 | reporting[energy_item_id] = dict() |
|
| 287 | reporting[energy_item_id]['timestamps'] = list() |
|
| 288 | reporting[energy_item_id]['values'] = list() |
|
| 289 | reporting[energy_item_id]['subtotal'] = Decimal(0.0) |
|
| 290 | reporting[energy_item_id]['toppeak'] = Decimal(0.0) |
|
| 291 | reporting[energy_item_id]['onpeak'] = Decimal(0.0) |
|
| 292 | reporting[energy_item_id]['midpeak'] = Decimal(0.0) |
|
| 293 | reporting[energy_item_id]['offpeak'] = Decimal(0.0) |
|
| 294 | ||
| 295 | cursor_energy.execute(" SELECT start_datetime_utc, actual_value " |
|
| 296 | " FROM tbl_equipment_input_item_hourly " |
|
| 297 | " WHERE equipment_id = %s " |
|
| 298 | " AND energy_item_id = %s " |
|
| 299 | " AND start_datetime_utc >= %s " |
|
| 300 | " AND start_datetime_utc < %s " |
|
| 301 | " ORDER BY start_datetime_utc ", |
|
| 302 | (equipment['id'], |
|
| 303 | energy_item_id, |
|
| 304 | reporting_start_datetime_utc, |
|
| 305 | reporting_end_datetime_utc)) |
|
| 306 | rows_equipment_hourly = cursor_energy.fetchall() |
|
| 307 | ||
| 308 | rows_equipment_periodically = utilities.aggregate_hourly_data_by_period(rows_equipment_hourly, |
|
| 309 | reporting_start_datetime_utc, |
|
| 310 | reporting_end_datetime_utc, |
|
| 311 | period_type) |
|
| 312 | for row_equipment_periodically in rows_equipment_periodically: |
|
| 313 | current_datetime_local = row_equipment_periodically[0].replace(tzinfo=timezone.utc) + \ |
|
| 314 | timedelta(minutes=timezone_offset) |
|
| 315 | if period_type == 'hourly': |
|
| 316 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
| 317 | elif period_type == 'daily': |
|
| 318 | current_datetime = current_datetime_local.strftime('%Y-%m-%d') |
|
| 319 | elif period_type == 'monthly': |
|
| 320 | current_datetime = current_datetime_local.strftime('%Y-%m') |
|
| 321 | elif period_type == 'yearly': |
|
| 322 | current_datetime = current_datetime_local.strftime('%Y') |
|
| 323 | ||
| 324 | actual_value = Decimal(0.0) if row_equipment_periodically[1] is None \ |
|
| 325 | else row_equipment_periodically[1] |
|
| 326 | reporting[energy_item_id]['timestamps'].append(current_datetime) |
|
| 327 | reporting[energy_item_id]['values'].append(actual_value) |
|
| 328 | reporting[energy_item_id]['subtotal'] += actual_value |
|
| 329 | ||
| 330 | energy_category_tariff_dict = \ |
|
| 331 | utilities.get_energy_category_peak_types(equipment['cost_center_id'], |
|
| 332 | energy_item_dict[energy_item_id]['energy_category_id'], |
|
| 333 | reporting_start_datetime_utc, |
|
| 334 | reporting_end_datetime_utc) |
|
| 335 | for row in rows_equipment_hourly: |
|
| 336 | peak_type = energy_category_tariff_dict.get(row[0], None) |
|
| 337 | if peak_type == 'toppeak': |
|
| 338 | reporting[energy_item_id]['toppeak'] += row[1] |
|
| 339 | elif peak_type == 'onpeak': |
|
| 340 | reporting[energy_item_id]['onpeak'] += row[1] |
|
| 341 | elif peak_type == 'midpeak': |
|
| 342 | reporting[energy_item_id]['midpeak'] += row[1] |
|
| 343 | elif peak_type == 'offpeak': |
|
| 344 | reporting[energy_item_id]['offpeak'] += row[1] |
|
| 345 | ||
| 346 | ################################################################################################################ |
|
| 347 | # Step 7: query tariff data |
|
| 348 | ################################################################################################################ |
|
| 349 | parameters_data = dict() |
|
| 350 | parameters_data['names'] = list() |
|
| 351 | parameters_data['timestamps'] = list() |
|
| 352 | parameters_data['values'] = list() |
|
| 353 | if energy_item_set is not None and len(energy_item_set) > 0: |
|
| 354 | for energy_item_id in energy_item_set: |
|
| 355 | energy_category_tariff_dict = \ |
|
| 356 | utilities.get_energy_category_tariffs(equipment['cost_center_id'], |
|
| 357 | energy_item_dict[energy_item_id]['energy_category_id'], |
|
| 358 | reporting_start_datetime_utc, |
|
| 359 | reporting_end_datetime_utc) |
|
| 360 | tariff_timestamp_list = list() |
|
| 361 | tariff_value_list = list() |
|
| 362 | for k, v in energy_category_tariff_dict.items(): |
|
| 363 | # convert k from utc to local |
|
| 364 | k = k + timedelta(minutes=timezone_offset) |
|
| 365 | tariff_timestamp_list.append(k.isoformat()[0:19][0:19]) |
|
| 366 | tariff_value_list.append(v) |
|
| 367 | ||
| 368 | parameters_data['names'].append('TARIFF-' + energy_item_dict[energy_item_id]['name']) |
|
| 369 | parameters_data['timestamps'].append(tariff_timestamp_list) |
|
| 370 | parameters_data['values'].append(tariff_value_list) |
|
| 371 | ||
| 372 | ################################################################################################################ |
|
| 373 | # Step 8: query associated points data |
|
| 374 | ################################################################################################################ |
|
| 375 | for point in point_list: |
|
| 376 | point_values = [] |
|
| 377 | point_timestamps = [] |
|
| 378 | if point['object_type'] == 'ANALOG_VALUE': |
|
| 379 | query = (" SELECT utc_date_time, actual_value " |
|
| 380 | " FROM tbl_analog_value " |
|
| 381 | " WHERE point_id = %s " |
|
| 382 | " AND utc_date_time BETWEEN %s AND %s " |
|
| 383 | " ORDER BY utc_date_time ") |
|
| 384 | cursor_historical.execute(query, (point['id'], |
|
| 385 | reporting_start_datetime_utc, |
|
| 386 | reporting_end_datetime_utc)) |
|
| 387 | rows = cursor_historical.fetchall() |
|
| 388 | ||
| 389 | if rows is not None and len(rows) > 0: |
|
| 390 | for row in rows: |
|
| 391 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
| 392 | timedelta(minutes=timezone_offset) |
|
| 393 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
| 394 | point_timestamps.append(current_datetime) |
|
| 395 | point_values.append(row[1]) |
|
| 396 | ||
| 397 | elif point['object_type'] == 'ENERGY_VALUE': |
|
| 398 | query = (" SELECT utc_date_time, actual_value " |
|
| 399 | " FROM tbl_energy_value " |
|
| 400 | " WHERE point_id = %s " |
|
| 401 | " AND utc_date_time BETWEEN %s AND %s " |
|
| 402 | " ORDER BY utc_date_time ") |
|
| 403 | cursor_historical.execute(query, (point['id'], |
|
| 404 | reporting_start_datetime_utc, |
|
| 405 | reporting_end_datetime_utc)) |
|
| 406 | rows = cursor_historical.fetchall() |
|
| 407 | ||
| 408 | if rows is not None and len(rows) > 0: |
|
| 409 | for row in rows: |
|
| 410 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
| 411 | timedelta(minutes=timezone_offset) |
|
| 412 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
| 413 | point_timestamps.append(current_datetime) |
|
| 414 | point_values.append(row[1]) |
|
| 415 | elif point['object_type'] == 'DIGITAL_VALUE': |
|
| 416 | query = (" SELECT utc_date_time, actual_value " |
|
| 417 | " FROM tbl_digital_value " |
|
| 418 | " WHERE point_id = %s " |
|
| 419 | " AND utc_date_time BETWEEN %s AND %s ") |
|
| 420 | cursor_historical.execute(query, (point['id'], |
|
| 421 | reporting_start_datetime_utc, |
|
| 422 | reporting_end_datetime_utc)) |
|
| 423 | rows = cursor_historical.fetchall() |
|
| 424 | ||
| 425 | if rows is not None and len(rows) > 0: |
|
| 426 | for row in rows: |
|
| 427 | current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \ |
|
| 428 | timedelta(minutes=timezone_offset) |
|
| 429 | current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S') |
|
| 430 | point_timestamps.append(current_datetime) |
|
| 431 | point_values.append(row[1]) |
|
| 432 | ||
| 433 | parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')') |
|
| 434 | parameters_data['timestamps'].append(point_timestamps) |
|
| 435 | parameters_data['values'].append(point_values) |
|
| 436 | ||
| 437 | ################################################################################################################ |
|
| 438 | # Step 9: construct the report |
|
| 439 | ################################################################################################################ |
|
| 440 | if cursor_system: |
|
| 441 | cursor_system.close() |
|
| 442 | if cnx_system: |
|
| 443 | cnx_system.disconnect() |
|
| 444 | ||
| 445 | if cursor_energy: |
|
| 446 | cursor_energy.close() |
|
| 447 | if cnx_energy: |
|
| 448 | cnx_energy.disconnect() |
|
| 449 | ||
| 450 | result = dict() |
|
| 451 | ||
| 452 | result['equipment'] = dict() |
|
| 453 | result['equipment']['name'] = equipment['name'] |
|
| 454 | ||
| 455 | result['base_period'] = dict() |
|
| 456 | result['base_period']['names'] = list() |
|
| 457 | result['base_period']['units'] = list() |
|
| 458 | result['base_period']['timestamps'] = list() |
|
| 459 | result['base_period']['values'] = list() |
|
| 460 | result['base_period']['subtotals'] = list() |
|
| 461 | if energy_item_set is not None and len(energy_item_set) > 0: |
|
| 462 | for energy_item_id in energy_item_set: |
|
| 463 | result['base_period']['names'].append(energy_item_dict[energy_item_id]['name']) |
|
| 464 | result['base_period']['units'].append(energy_item_dict[energy_item_id]['unit_of_measure']) |
|
| 465 | result['base_period']['timestamps'].append(base[energy_item_id]['timestamps']) |
|
| 466 | result['base_period']['values'].append(base[energy_item_id]['values']) |
|
| 467 | result['base_period']['subtotals'].append(base[energy_item_id]['subtotal']) |
|
| 468 | ||
| 469 | result['reporting_period'] = dict() |
|
| 470 | result['reporting_period']['names'] = list() |
|
| 471 | result['reporting_period']['energy_item_ids'] = list() |
|
| 472 | result['reporting_period']['energy_category_names'] = list() |
|
| 473 | result['reporting_period']['energy_category_ids'] = list() |
|
| 474 | result['reporting_period']['units'] = list() |
|
| 475 | result['reporting_period']['timestamps'] = list() |
|
| 476 | result['reporting_period']['values'] = list() |
|
| 477 | result['reporting_period']['subtotals'] = list() |
|
| 478 | result['reporting_period']['toppeaks'] = list() |
|
| 479 | result['reporting_period']['onpeaks'] = list() |
|
| 480 | result['reporting_period']['midpeaks'] = list() |
|
| 481 | result['reporting_period']['offpeaks'] = list() |
|
| 482 | result['reporting_period']['increment_rates'] = list() |
|
| 483 | ||
| 484 | if energy_item_set is not None and len(energy_item_set) > 0: |
|
| 485 | for energy_item_id in energy_item_set: |
|
| 486 | result['reporting_period']['names'].append(energy_item_dict[energy_item_id]['name']) |
|
| 487 | result['reporting_period']['energy_item_ids'].append(energy_item_id) |
|
| 488 | result['reporting_period']['energy_category_names'].append( |
|
| 489 | energy_item_dict[energy_item_id]['energy_category_name']) |
|
| 490 | result['reporting_period']['energy_category_ids'].append( |
|
| 491 | energy_item_dict[energy_item_id]['energy_category_id']) |
|
| 492 | result['reporting_period']['units'].append(energy_item_dict[energy_item_id]['unit_of_measure']) |
|
| 493 | result['reporting_period']['timestamps'].append(reporting[energy_item_id]['timestamps']) |
|
| 494 | result['reporting_period']['values'].append(reporting[energy_item_id]['values']) |
|
| 495 | result['reporting_period']['subtotals'].append(reporting[energy_item_id]['subtotal']) |
|
| 496 | result['reporting_period']['toppeaks'].append(reporting[energy_item_id]['toppeak']) |
|
| 497 | result['reporting_period']['onpeaks'].append(reporting[energy_item_id]['onpeak']) |
|
| 498 | result['reporting_period']['midpeaks'].append(reporting[energy_item_id]['midpeak']) |
|
| 499 | result['reporting_period']['offpeaks'].append(reporting[energy_item_id]['offpeak']) |
|
| 500 | result['reporting_period']['increment_rates'].append( |
|
| 501 | (reporting[energy_item_id]['subtotal'] - base[energy_item_id]['subtotal']) / |
|
| 502 | base[energy_item_id]['subtotal'] |
|
| 503 | if base[energy_item_id]['subtotal'] > 0.0 else None) |
|
| 504 | ||
| 505 | result['parameters'] = { |
|
| 506 | "names": parameters_data['names'], |
|
| 507 | "timestamps": parameters_data['timestamps'], |
|
| 508 | "values": parameters_data['values'] |
|
| 509 | } |
|
| 510 | ||
| 511 | resp.body = json.dumps(result) |
|
| 512 | ||