space_energy_output_category.main()   F
last analyzed

Complexity

Conditions 14

Size

Total Lines 70
Code Lines 46

Duplication

Lines 70
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 46
dl 70
loc 70
rs 3.6
c 0
b 0
f 0
cc 14
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like space_energy_output_category.main() 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 time
2
from datetime import datetime, timedelta
3
from decimal import Decimal
4
import mysql.connector
5
from multiprocessing import Pool
6
import random
7
import config
8
9
10
########################################################################################################################
11
# PROCEDURES
12
# Step 1: get all spaces
13
# Step 2: Create multiprocessing pool to call worker in parallel
14
########################################################################################################################
15
16
17 View Code Duplication
def main(logger):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
18
19
    while True:
20
        # the outermost while loop
21
        ################################################################################################################
22
        # Step 1: get all spaces
23
        ################################################################################################################
24
        cnx_system_db = None
25
        cursor_system_db = None
26
        try:
27
            cnx_system_db = mysql.connector.connect(**config.myems_system_db)
28
            cursor_system_db = cnx_system_db.cursor()
29
        except Exception as e:
30
            logger.error("Error in step 1.1 of space_energy_output_category.main " + str(e))
31
            if cursor_system_db:
32
                cursor_system_db.close()
33
            if cnx_system_db:
34
                cnx_system_db.close()
35
            # sleep and continue the outer loop to reconnect the database
36
            time.sleep(60)
37
            continue
38
        print("Connected to MyEMS System Database")
39
40
        try:
41
            cursor_system_db.execute(" SELECT id, name "
42
                                     " FROM tbl_spaces "
43
                                     " ORDER BY id ")
44
            rows_spaces = cursor_system_db.fetchall()
45
46
            if rows_spaces is None or len(rows_spaces) == 0:
47
                print("There isn't any spaces ")
48
                # sleep and continue the outer loop to reconnect the database
49
                time.sleep(60)
50
                continue
51
52
            space_list = list()
53
            for row in rows_spaces:
54
                space_list.append({"id": row[0], "name": row[1]})
55
56
        except Exception as e:
57
            logger.error("Error in step 1.2 of space_energy_output_category.main " + str(e))
58
            # sleep and continue the outer loop to reconnect the database
59
            time.sleep(60)
60
            continue
61
        finally:
62
            if cursor_system_db:
63
                cursor_system_db.close()
64
            if cnx_system_db:
65
                cnx_system_db.close()
66
67
        print("Got all spaces in MyEMS System Database")
68
69
        # shuffle the space list for randomly calculating the meter hourly value
70
        random.shuffle(space_list)
0 ignored issues
show
introduced by
The variable space_list does not seem to be defined for all execution paths.
Loading history...
71
72
        ################################################################################################################
73
        # Step 2: Create multiprocessing pool to call worker in parallel
74
        ################################################################################################################
75
        p = Pool(processes=config.pool_size)
76
        error_list = p.map(worker, space_list)
77
        p.close()
78
        p.join()
79
80
        for error in error_list:
81
            if error is not None and len(error) > 0:
82
                logger.error(error)
83
84
        print("go to sleep 300 seconds...")
85
        time.sleep(300)
86
        print("wake from sleep, and continue to work...")
87
    # end of outer while
88
89
90
########################################################################################################################
91
# PROCEDURES:
92
#   Step 1: get all combined equipments associated with the space
93
#   Step 2: get all equipments associated with the space
94
#   Step 3: get all child spaces associated with the space
95
#   Step 4: determine start datetime and end datetime to aggregate
96
#   Step 5: for each combined equipment in list, get energy output data from energy database
97
#   Step 6: for each equipment in list, get energy output data from energy database
98
#   Step 7: for each child space in list, get energy output data from energy database
99
#   Step 8: determine common time slot to aggregate
100
#   Step 9: aggregate energy data in the common time slot by energy categories and hourly
101
#   Step 10: save energy data to energy database
102
#
103
# NOTE: returns None or the error string because that the logger object cannot be passed in as parameter
104
########################################################################################################################
105
106
def worker(space):
107
108
    ####################################################################################################################
109
    # Step 1: get all combined equipments associated with the space
110
    ####################################################################################################################
111
    print("Step 1: get all combined equipments associated with the space")
112
113
    cnx_system_db = None
114
    cursor_system_db = None
115
    try:
116
        cnx_system_db = mysql.connector.connect(**config.myems_system_db)
117
        cursor_system_db = cnx_system_db.cursor()
118
    except Exception as e:
119
        error_string = "Error in step 1.1 of space_energy_output_category.worker " + str(e)
120
        if cursor_system_db:
121
            cursor_system_db.close()
122
        if cnx_system_db:
123
            cnx_system_db.close()
124
        print(error_string)
125
        return error_string
126
127
    combined_equipment_list = list()
128
    try:
129
        cursor_system_db.execute(" SELECT e.id, e.name "
130
                                 " FROM tbl_combined_equipments e, tbl_spaces_combined_equipments se "
131
                                 " WHERE e.id = se.combined_equipment_id "
132
                                 "       AND e.is_output_counted = true "
133
                                 "       AND se.space_id = %s ",
134
                                 (space['id'],))
135
        rows_combined_equipments = cursor_system_db.fetchall()
136
137
        if rows_combined_equipments is not None and len(rows_combined_equipments) > 0:
138
            for row in rows_combined_equipments:
139
                combined_equipment_list.append({"id": row[0],
140
                                                "name": row[1]})
141
142
    except Exception as e:
143
        error_string = "Error in step 1.2 of space_energy_output_category.worker " + str(e)
144
        if cursor_system_db:
145
            cursor_system_db.close()
146
        if cnx_system_db:
147
            cnx_system_db.close()
148
        print(error_string)
149
        return error_string
150
151
    ####################################################################################################################
152
    # Step 2: get all equipments associated with the space
153
    ####################################################################################################################
154
    print("Step 2: get all equipments associated with the space")
155
156
    equipment_list = list()
157
    try:
158
        cursor_system_db.execute(" SELECT e.id, e.name "
159
                                 " FROM tbl_equipments e, tbl_spaces_equipments se "
160
                                 " WHERE e.id = se.equipment_id "
161
                                 "       AND e.is_output_counted = true "
162
                                 "       AND se.space_id = %s ",
163
                                 (space['id'],))
164
        rows_equipments = cursor_system_db.fetchall()
165
166
        if rows_equipments is not None and len(rows_equipments) > 0:
167
            for row in rows_equipments:
168
                equipment_list.append({"id": row[0],
169
                                       "name": row[1]})
170
171
    except Exception as e:
172
        error_string = "Error in step 2.2 of space_energy_output_category.worker " + str(e)
173
        if cursor_system_db:
174
            cursor_system_db.close()
175
        if cnx_system_db:
176
            cnx_system_db.close()
177
        print(error_string)
178
        return error_string
179
180
    ####################################################################################################################
181
    # Step 3: get all child spaces associated with the space
182
    ####################################################################################################################
183
    print("Step 3: get all child spaces associated with the space")
184
185
    child_space_list = list()
186
    try:
187
        cursor_system_db.execute(" SELECT id, name "
188
                                 " FROM tbl_spaces "
189
                                 " WHERE is_output_counted = true "
190
                                 "       AND parent_space_id = %s ",
191
                                 (space['id'],))
192
        rows_child_spaces = cursor_system_db.fetchall()
193
194
        if rows_child_spaces is not None and len(rows_child_spaces) > 0:
195
            for row in rows_child_spaces:
196
                child_space_list.append({"id": row[0],
197
                                         "name": row[1]})
198
199
    except Exception as e:
200
        error_string = "Error in step 3 of space_energy_output_category.worker " + str(e)
201
        print(error_string)
202
        return error_string
203
    finally:
204
        if cursor_system_db:
205
            cursor_system_db.close()
206
        if cnx_system_db:
207
            cnx_system_db.close()
208
209
    if ((combined_equipment_list is None or len(combined_equipment_list) == 0) and
210
            (equipment_list is None or len(equipment_list) == 0) and
211
            (child_space_list is None or len(child_space_list) == 0)):
212
        print("This is an empty space ")
213
        return None
214
215
    ####################################################################################################################
216
    # Step 4: determine start datetime and end datetime to aggregate
217
    ####################################################################################################################
218
    print("Step 4: determine start datetime and end datetime to aggregate")
219
    cnx_energy_db = None
220
    cursor_energy_db = None
221
    try:
222
        cnx_energy_db = mysql.connector.connect(**config.myems_energy_db)
223
        cursor_energy_db = cnx_energy_db.cursor()
224
    except Exception as e:
225
        error_string = "Error in step 4.1 of space_energy_output_category.worker " + str(e)
226
        if cursor_energy_db:
227
            cursor_energy_db.close()
228
        if cnx_energy_db:
229
            cnx_energy_db.close()
230
        print(error_string)
231
        return error_string
232
233
    try:
234
        query = (" SELECT MAX(start_datetime_utc) "
235
                 " FROM tbl_space_output_category_hourly "
236
                 " WHERE space_id = %s ")
237
        cursor_energy_db.execute(query, (space['id'],))
238
        row_datetime = cursor_energy_db.fetchone()
239
        start_datetime_utc = datetime.strptime(config.start_datetime_utc, '%Y-%m-%d %H:%M:%S')
240
        start_datetime_utc = start_datetime_utc.replace(minute=0, second=0, microsecond=0, tzinfo=None)
241
242
        if row_datetime is not None and len(row_datetime) > 0 and isinstance(row_datetime[0], datetime):
243
            # replace second and microsecond with 0
244
            # note: do not replace minute in case of calculating in half hourly
245
            start_datetime_utc = row_datetime[0].replace(second=0, microsecond=0, tzinfo=None)
246
            # start from the next time slot
247
            start_datetime_utc += timedelta(minutes=config.minutes_to_count)
248
249
        end_datetime_utc = datetime.utcnow().replace(second=0, microsecond=0, tzinfo=None)
250
251
        print("start_datetime_utc: " + start_datetime_utc.isoformat()[0:19]
252
              + "end_datetime_utc: " + end_datetime_utc.isoformat()[0:19])
253
254
    except Exception as e:
255
        error_string = "Error in step 4.2 of space_energy_output_category.worker " + str(e)
256
        if cursor_energy_db:
257
            cursor_energy_db.close()
258
        if cnx_energy_db:
259
            cnx_energy_db.close()
260
        print(error_string)
261
        return error_string
262
263
    ####################################################################################################################
264
    # Step 5: for each combined equipment in list, get energy output data from energy database
265
    ####################################################################################################################
266
    energy_combined_equipment_hourly = dict()
267
    if combined_equipment_list is not None and len(combined_equipment_list) > 0:
268
        try:
269
            for combined_equipment in combined_equipment_list:
270
                combined_equipment_id = str(combined_equipment['id'])
271
                query = (" SELECT start_datetime_utc, energy_category_id, actual_value "
272
                         " FROM tbl_combined_equipment_output_category_hourly "
273
                         " WHERE combined_equipment_id = %s "
274
                         "       AND start_datetime_utc >= %s "
275
                         "       AND start_datetime_utc < %s "
276
                         " ORDER BY start_datetime_utc ")
277
                cursor_energy_db.execute(query, (combined_equipment_id, start_datetime_utc, end_datetime_utc,))
278
                rows_energy_values = cursor_energy_db.fetchall()
279
                if rows_energy_values is None or len(rows_energy_values) == 0:
280
                    energy_combined_equipment_hourly[combined_equipment_id] = None
281
                else:
282
                    energy_combined_equipment_hourly[combined_equipment_id] = dict()
283
                    for row_value in rows_energy_values:
284
                        current_datetime_utc = row_value[0]
285
                        if current_datetime_utc not in energy_combined_equipment_hourly[combined_equipment_id]:
286
                            energy_combined_equipment_hourly[combined_equipment_id][current_datetime_utc] = dict()
287
                        energy_category_id = row_value[1]
288
                        actual_value = row_value[2]
289
                        energy_combined_equipment_hourly[combined_equipment_id][current_datetime_utc][energy_category_id] = \
290
                            actual_value
291
        except Exception as e:
292
            error_string = "Error in step 5 of space_energy_output_category.worker " + str(e)
293
            if cursor_energy_db:
294
                cursor_energy_db.close()
295
            if cnx_energy_db:
296
                cnx_energy_db.close()
297
            print(error_string)
298
            return error_string
299
300
    ####################################################################################################################
301
    # Step 6: for each equipment in list, get energy output data from energy database
302
    ####################################################################################################################
303
    energy_equipment_hourly = dict()
304
    if equipment_list is not None and len(equipment_list) > 0:
305
        try:
306
            for equipment in equipment_list:
307
                equipment_id = str(equipment['id'])
308
                query = (" SELECT start_datetime_utc, energy_category_id, actual_value "
309
                         " FROM tbl_equipment_output_category_hourly "
310
                         " WHERE equipment_id = %s "
311
                         "       AND start_datetime_utc >= %s "
312
                         "       AND start_datetime_utc < %s "
313
                         " ORDER BY start_datetime_utc ")
314
                cursor_energy_db.execute(query, (equipment_id, start_datetime_utc, end_datetime_utc,))
315
                rows_energy_values = cursor_energy_db.fetchall()
316
                if rows_energy_values is None or len(rows_energy_values) == 0:
317
                    energy_equipment_hourly[equipment_id] = None
318
                else:
319
                    energy_equipment_hourly[equipment_id] = dict()
320
                    for row_value in rows_energy_values:
321
                        current_datetime_utc = row_value[0]
322
                        if current_datetime_utc not in energy_equipment_hourly[equipment_id]:
323
                            energy_equipment_hourly[equipment_id][current_datetime_utc] = dict()
324
                        energy_category_id = row_value[1]
325
                        actual_value = row_value[2]
326
                        energy_equipment_hourly[equipment_id][current_datetime_utc][energy_category_id] = \
327
                            actual_value
328
        except Exception as e:
329
            error_string = "Error in step 6 of space_energy_output_category.worker " + str(e)
330
            if cursor_energy_db:
331
                cursor_energy_db.close()
332
            if cnx_energy_db:
333
                cnx_energy_db.close()
334
            print(error_string)
335
            return error_string
336
337
    ####################################################################################################################
338
    # Step 7: for each child space in list, get energy output data from energy database
339
    ####################################################################################################################
340
    energy_child_space_hourly = dict()
341
    if child_space_list is not None and len(child_space_list) > 0:
342
        try:
343
            for child_space in child_space_list:
344
                child_space_id = str(child_space['id'])
345
346
                query = (" SELECT start_datetime_utc, energy_category_id, actual_value "
347
                         " FROM tbl_space_output_category_hourly "
348
                         " WHERE space_id = %s "
349
                         "       AND start_datetime_utc >= %s "
350
                         "       AND start_datetime_utc < %s "
351
                         " ORDER BY start_datetime_utc ")
352
                cursor_energy_db.execute(query, (child_space_id, start_datetime_utc, end_datetime_utc,))
353
                rows_energy_values = cursor_energy_db.fetchall()
354
                if rows_energy_values is None or len(rows_energy_values) == 0:
355
                    energy_child_space_hourly[child_space_id] = None
356
                else:
357
                    energy_child_space_hourly[child_space_id] = dict()
358
                    for row_energy_value in rows_energy_values:
359
                        current_datetime_utc = row_energy_value[0]
360
                        if current_datetime_utc not in energy_child_space_hourly[child_space_id]:
361
                            energy_child_space_hourly[child_space_id][current_datetime_utc] = dict()
362
                        energy_category_id = row_energy_value[1]
363
                        actual_value = row_energy_value[2]
364
                        energy_child_space_hourly[child_space_id][current_datetime_utc][energy_category_id] = actual_value
365
        except Exception as e:
366
            error_string = "Error in step 7 of space_energy_output_category.worker " + str(e)
367
            if cursor_energy_db:
368
                cursor_energy_db.close()
369
            if cnx_energy_db:
370
                cnx_energy_db.close()
371
            print(error_string)
372
            return error_string
373
374
    ####################################################################################################################
375
    # Step 8: determine common time slot to aggregate
376
    ####################################################################################################################
377
378
    common_start_datetime_utc = start_datetime_utc
379
    common_end_datetime_utc = end_datetime_utc
380
381
    print("Getting common time slot of energy values for all combined equipments")
382
    if common_start_datetime_utc is not None and common_start_datetime_utc is not None:
383
        if energy_combined_equipment_hourly is not None and len(energy_combined_equipment_hourly) > 0:
384
            for combined_equipment_id, energy_hourly in energy_combined_equipment_hourly.items():
385
                if energy_hourly is None or len(energy_hourly) == 0:
386
                    common_start_datetime_utc = None
387
                    common_end_datetime_utc = None
388
                    break
389
                else:
390
                    if common_start_datetime_utc < min(energy_hourly.keys()):
391
                        common_start_datetime_utc = min(energy_hourly.keys())
392
                    if common_end_datetime_utc > max(energy_hourly.keys()):
393
                        common_end_datetime_utc = max(energy_hourly.keys())
394
395
    print("Getting common time slot of energy values for all equipments...")
396
    if common_start_datetime_utc is not None and common_start_datetime_utc is not None:
397
        if energy_equipment_hourly is not None and len(energy_equipment_hourly) > 0:
398
            for equipment_id, energy_hourly in energy_equipment_hourly.items():
399
                if energy_hourly is None or len(energy_hourly) == 0:
400
                    common_start_datetime_utc = None
401
                    common_end_datetime_utc = None
402
                    break
403
                else:
404
                    if common_start_datetime_utc < min(energy_hourly.keys()):
405
                        common_start_datetime_utc = min(energy_hourly.keys())
406
                    if common_end_datetime_utc > max(energy_hourly.keys()):
407
                        common_end_datetime_utc = max(energy_hourly.keys())
408
409
    print("Getting common time slot of energy values for all child spaces...")
410
    if common_start_datetime_utc is not None and common_start_datetime_utc is not None:
411
        if energy_child_space_hourly is not None and len(energy_child_space_hourly) > 0:
412
            for child_space_id, energy_hourly in energy_child_space_hourly.items():
413
                if energy_hourly is None or len(energy_hourly) == 0:
414
                    common_start_datetime_utc = None
415
                    common_end_datetime_utc = None
416
                    break
417
                else:
418
                    if common_start_datetime_utc < min(energy_hourly.keys()):
419
                        common_start_datetime_utc = min(energy_hourly.keys())
420
                    if common_end_datetime_utc > max(energy_hourly.keys()):
421
                        common_end_datetime_utc = max(energy_hourly.keys())
422
423
    if (energy_combined_equipment_hourly is None or len(energy_combined_equipment_hourly) == 0) and \
424
            (energy_equipment_hourly is None or len(energy_equipment_hourly) == 0) and \
425
            (energy_child_space_hourly is None or len(energy_child_space_hourly) == 0):
426
        # There isn't any energy data
427
        print("There isn't any energy data")
428
        # continue the for space loop to the next space
429
        print("continue the for space loop to the next space")
430
        if cursor_energy_db:
431
            cursor_energy_db.close()
432
        if cnx_energy_db:
433
            cnx_energy_db.close()
434
        return None
435
436
    print("common_start_datetime_utc: " + str(common_start_datetime_utc))
437
    print("common_end_datetime_utc: " + str(common_end_datetime_utc))
438
439
    ####################################################################################################################
440
    # Step 9: aggregate energy data in the common time slot by energy categories and hourly
441
    ####################################################################################################################
442
443
    print("Step 9: aggregate energy data in the common time slot by energy categories and hourly")
444
    aggregated_values = list()
445
    try:
446
        current_datetime_utc = common_start_datetime_utc
447
        while common_start_datetime_utc is not None \
448
                and common_end_datetime_utc is not None \
449
                and current_datetime_utc <= common_end_datetime_utc:
450
            aggregated_value = dict()
451
            aggregated_value['start_datetime_utc'] = current_datetime_utc
452
            aggregated_value['meta_data'] = dict()
453
454
            if combined_equipment_list is not None and len(combined_equipment_list) > 0:
455
                for combined_equipment in combined_equipment_list:
456
                    combined_equipment_id = str(combined_equipment['id'])
457
                    meta_data_dict = \
458
                        energy_combined_equipment_hourly[combined_equipment_id].get(current_datetime_utc, None)
459
                    if meta_data_dict is not None and len(meta_data_dict) > 0:
460
                        for energy_category_id, actual_value in meta_data_dict.items():
461
                            aggregated_value['meta_data'][energy_category_id] = \
462
                                aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
463
464
            if equipment_list is not None and len(equipment_list) > 0:
465
                for equipment in equipment_list:
466
                    equipment_id = str(equipment['id'])
467
                    meta_data_dict = energy_equipment_hourly[equipment_id].get(current_datetime_utc, None)
468
                    if meta_data_dict is not None and len(meta_data_dict) > 0:
469
                        for energy_category_id, actual_value in meta_data_dict.items():
470
                            aggregated_value['meta_data'][energy_category_id] = \
471
                                aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
472
473
            if child_space_list is not None and len(child_space_list) > 0:
474
                for child_space in child_space_list:
475
                    child_space_id = str(child_space['id'])
476
                    meta_data_dict = energy_child_space_hourly[child_space_id].get(current_datetime_utc, None)
477
                    if meta_data_dict is not None and len(meta_data_dict) > 0:
478
                        for energy_category_id, actual_value in meta_data_dict.items():
479
                            aggregated_value['meta_data'][energy_category_id] = \
480
                                aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
481
482
            aggregated_values.append(aggregated_value)
483
484
            current_datetime_utc += timedelta(minutes=config.minutes_to_count)
485
486
    except Exception as e:
487
        error_string = "Error in step 9 of space_energy_output_category.worker " + str(e)
488
        if cursor_energy_db:
489
            cursor_energy_db.close()
490
        if cnx_energy_db:
491
            cnx_energy_db.close()
492
        print(error_string)
493
        return error_string
494
495
    ####################################################################################################################
496
    # Step 10: save energy data to energy database
497
    ####################################################################################################################
498
    print("Step 10: save energy data to energy database")
499
500
    if len(aggregated_values) > 0:
501
        try:
502
            add_values = (" INSERT INTO tbl_space_output_category_hourly "
503
                          "             (space_id, "
504
                          "              energy_category_id, "
505
                          "              start_datetime_utc, "
506
                          "              actual_value) "
507
                          " VALUES  ")
508
509
            for aggregated_value in aggregated_values:
510
                for energy_category_id, actual_value in aggregated_value['meta_data'].items():
511
                    add_values += " (" + str(space['id']) + ","
512
                    add_values += " " + str(energy_category_id) + ","
513
                    add_values += "'" + aggregated_value['start_datetime_utc'].isoformat()[0:19] + "',"
514
                    add_values += str(actual_value) + "), "
515
            print("add_values:" + add_values)
516
            # trim ", " at the end of string and then execute
517
            cursor_energy_db.execute(add_values[:-2])
518
            cnx_energy_db.commit()
519
520
        except Exception as e:
521
            error_string = "Error in step 8 of space_energy_output_category.worker " + str(e)
522
            print(error_string)
523
            return error_string
524
        finally:
525
            if cursor_energy_db:
526
                cursor_energy_db.close()
527
            if cnx_energy_db:
528
                cnx_energy_db.close()
529
    else:
530
        if cursor_energy_db:
531
            cursor_energy_db.close()
532
        if cnx_energy_db:
533
            cnx_energy_db.close()
534