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