store_energy_input_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 store_energy_input_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 stores
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 stores
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 store_energy_input_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_stores "
43
                                     " ORDER BY id ")
44
            rows_stores = cursor_system_db.fetchall()
45
46
            if rows_stores is None or len(rows_stores) == 0:
47
                print("There isn't any stores ")
48
                # sleep and continue the outer loop to reconnect the database
49
                time.sleep(60)
50
                continue
51
52
            store_list = list()
53
            for row in rows_stores:
54
                store_list.append({"id": row[0], "name": row[1]})
55
56
        except Exception as e:
57
            logger.error("Error in step 1.2 of store_energy_input_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 stores in MyEMS System Database")
68
69
        # shuffle the store list for randomly calculating the meter hourly value
70
        random.shuffle(store_list)
0 ignored issues
show
introduced by
The variable store_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, store_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 input meters associated with the store
93
#   Step 2: get all input virtual meters associated with the store
94
#   Step 3: get all input offline meters associated with the store
95
#   Step 4: determine start datetime and end datetime to aggregate
96
#   Step 5: for each meter in list, get energy input data from energy database
97
#   Step 6: for each virtual meter in list, get energy input data from energy database
98
#   Step 7: for each offline meter in list, get energy input 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 View Code Duplication
def worker(store):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
107
    ####################################################################################################################
108
    # Step 1: get all input meters associated with the store
109
    ####################################################################################################################
110
    print("Step 1: get all input meters associated with the store " + str(store['name']))
111
112
    meter_list = list()
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 store_energy_input_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
    try:
128
        cursor_system_db.execute(" SELECT m.id, m.name, m.energy_category_id "
129
                                 " FROM tbl_meters m, tbl_stores_meters sm "
130
                                 " WHERE m.id = sm.meter_id "
131
                                 "       AND m.is_counted = true "
132
                                 "       AND sm.store_id = %s ",
133
                                 (store['id'],))
134
        rows_meters = cursor_system_db.fetchall()
135
136
        if rows_meters is not None and len(rows_meters) > 0:
137
            for row in rows_meters:
138
                meter_list.append({"id": row[0],
139
                                   "name": row[1],
140
                                   "energy_category_id": row[2]})
141
142
    except Exception as e:
143
        error_string = "Error in step 1.2 of store_energy_input_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 input virtual meters associated with the store
153
    ####################################################################################################################
154
    print("Step 2: get all input virtual meters associated with the store")
155
    virtual_meter_list = list()
156
157
    try:
158
        cursor_system_db.execute(" SELECT m.id, m.name, m.energy_category_id "
159
                                 " FROM tbl_virtual_meters m, tbl_stores_virtual_meters sm "
160
                                 " WHERE m.id = sm.virtual_meter_id "
161
                                 "       AND m.is_counted = true "
162
                                 "       AND sm.store_id = %s ",
163
                                 (store['id'],))
164
        rows_virtual_meters = cursor_system_db.fetchall()
165
166
        if rows_virtual_meters is not None and len(rows_virtual_meters) > 0:
167
            for row in rows_virtual_meters:
168
                virtual_meter_list.append({"id": row[0],
169
                                           "name": row[1],
170
                                           "energy_category_id": row[2]})
171
172
    except Exception as e:
173
        error_string = "Error in step 2.1 of store_energy_input_category.worker " + str(e)
174
        if cursor_system_db:
175
            cursor_system_db.close()
176
        if cnx_system_db:
177
            cnx_system_db.close()
178
        print(error_string)
179
        return error_string
180
181
    ####################################################################################################################
182
    # Step 3: get all input offline meters associated with the store
183
    ####################################################################################################################
184
    print("Step 3: get all input offline meters associated with the store")
185
186
    offline_meter_list = list()
187
188
    try:
189
        cursor_system_db.execute(" SELECT m.id, m.name, m.energy_category_id "
190
                                 " FROM tbl_offline_meters m, tbl_stores_offline_meters sm "
191
                                 " WHERE m.id = sm.offline_meter_id "
192
                                 "       AND m.is_counted = true "
193
                                 "       AND sm.store_id = %s ",
194
                                 (store['id'],))
195
        rows_offline_meters = cursor_system_db.fetchall()
196
197
        if rows_offline_meters is not None and len(rows_offline_meters) > 0:
198
            for row in rows_offline_meters:
199
                offline_meter_list.append({"id": row[0],
200
                                           "name": row[1],
201
                                           "energy_category_id": row[2]})
202
203
    except Exception as e:
204
        error_string = "Error in step 3.1 of store_energy_input_category.worker " + str(e)
205
        print(error_string)
206
        return error_string
207
    finally:
208
        if cursor_system_db:
209
            cursor_system_db.close()
210
        if cnx_system_db:
211
            cnx_system_db.close()
212
213
    ####################################################################################################################
214
    # stop to the next store if this store is empty
215
    ####################################################################################################################
216
    if (meter_list is None or len(meter_list) == 0) and \
217
            (virtual_meter_list is None or len(virtual_meter_list) == 0) and \
218
            (offline_meter_list is None or len(offline_meter_list) == 0):
219
        print("This is an empty store ")
220
        return None
221
222
    ####################################################################################################################
223
    # Step 4: determine start datetime and end datetime to aggregate
224
    ####################################################################################################################
225
    print("Step 4: determine start datetime and end datetime to aggregate")
226
    cnx_energy_db = None
227
    cursor_energy_db = None
228
    try:
229
        cnx_energy_db = mysql.connector.connect(**config.myems_energy_db)
230
        cursor_energy_db = cnx_energy_db.cursor()
231
    except Exception as e:
232
        error_string = "Error in step 4.1 of store_energy_input_category.worker " + str(e)
233
        if cursor_energy_db:
234
            cursor_energy_db.close()
235
        if cnx_energy_db:
236
            cnx_energy_db.close()
237
        print(error_string)
238
        return error_string
239
240
    try:
241
        query = (" SELECT MAX(start_datetime_utc) "
242
                 " FROM tbl_store_input_category_hourly "
243
                 " WHERE store_id = %s ")
244
        cursor_energy_db.execute(query, (store['id'],))
245
        row_datetime = cursor_energy_db.fetchone()
246
        start_datetime_utc = datetime.strptime(config.start_datetime_utc, '%Y-%m-%d %H:%M:%S')
247
        start_datetime_utc = start_datetime_utc.replace(minute=0, second=0, microsecond=0, tzinfo=None)
248
249
        if row_datetime is not None and len(row_datetime) > 0 and isinstance(row_datetime[0], datetime):
250
            # replace second and microsecond with 0
251
            # note: do not replace minute in case of calculating in half hourly
252
            start_datetime_utc = row_datetime[0].replace(second=0, microsecond=0, tzinfo=None)
253
            # start from the next time slot
254
            start_datetime_utc += timedelta(minutes=config.minutes_to_count)
255
256
        end_datetime_utc = datetime.utcnow().replace(second=0, microsecond=0, tzinfo=None)
257
258
        print("start_datetime_utc: " + start_datetime_utc.isoformat()[0:19]
259
              + "end_datetime_utc: " + end_datetime_utc.isoformat()[0:19])
260
261
    except Exception as e:
262
        error_string = "Error in step 4.2 of store_energy_input_category.worker " + str(e)
263
        if cursor_energy_db:
264
            cursor_energy_db.close()
265
        if cnx_energy_db:
266
            cnx_energy_db.close()
267
        print(error_string)
268
        return error_string
269
270
    ####################################################################################################################
271
    # Step 5: for each meter in list, get energy input data from energy database
272
    ####################################################################################################################
273
    energy_meter_hourly = dict()
274
    try:
275
        if meter_list is not None and len(meter_list) > 0:
276
            for meter in meter_list:
277
                meter_id = str(meter['id'])
278
279
                query = (" SELECT start_datetime_utc, actual_value "
280
                         " FROM tbl_meter_hourly "
281
                         " WHERE meter_id = %s "
282
                         "       AND start_datetime_utc >= %s "
283
                         "       AND start_datetime_utc < %s "
284
                         " ORDER BY start_datetime_utc ")
285
                cursor_energy_db.execute(query, (meter_id, start_datetime_utc, end_datetime_utc,))
286
                rows_energy_values = cursor_energy_db.fetchall()
287
                if rows_energy_values is None or len(rows_energy_values) == 0:
288
                    energy_meter_hourly[meter_id] = None
289
                else:
290
                    energy_meter_hourly[meter_id] = dict()
291
                    for row_energy_value in rows_energy_values:
292
                        energy_meter_hourly[meter_id][row_energy_value[0]] = row_energy_value[1]
293
    except Exception as e:
294
        error_string = "Error in step 5.1 of store_energy_input_category.worker " + str(e)
295
        if cursor_energy_db:
296
            cursor_energy_db.close()
297
        if cnx_energy_db:
298
            cnx_energy_db.close()
299
        print(error_string)
300
        return error_string
301
302
    ####################################################################################################################
303
    # Step 6: for each virtual meter in list, get energy input data from energy database
304
    ####################################################################################################################
305
    energy_virtual_meter_hourly = dict()
306
    if virtual_meter_list is not None and len(virtual_meter_list) > 0:
307
        try:
308
            for virtual_meter in virtual_meter_list:
309
                virtual_meter_id = str(virtual_meter['id'])
310
311
                query = (" SELECT start_datetime_utc, actual_value "
312
                         " FROM tbl_virtual_meter_hourly "
313
                         " WHERE virtual_meter_id = %s "
314
                         "       AND start_datetime_utc >= %s "
315
                         "       AND start_datetime_utc < %s "
316
                         " ORDER BY start_datetime_utc ")
317
                cursor_energy_db.execute(query, (virtual_meter_id, start_datetime_utc, end_datetime_utc,))
318
                rows_energy_values = cursor_energy_db.fetchall()
319
                if rows_energy_values is None or len(rows_energy_values) == 0:
320
                    energy_virtual_meter_hourly[virtual_meter_id] = None
321
                else:
322
                    energy_virtual_meter_hourly[virtual_meter_id] = dict()
323
                    for row_energy_value in rows_energy_values:
324
                        energy_virtual_meter_hourly[virtual_meter_id][row_energy_value[0]] = row_energy_value[1]
325
        except Exception as e:
326
            error_string = "Error in step 6.1 of store_energy_input_category.worker " + str(e)
327
            if cursor_energy_db:
328
                cursor_energy_db.close()
329
            if cnx_energy_db:
330
                cnx_energy_db.close()
331
            print(error_string)
332
            return error_string
333
334
    ####################################################################################################################
335
    # Step 7: for each offline meter in list, get energy input data from energy database
336
    ####################################################################################################################
337
    energy_offline_meter_hourly = dict()
338
    if offline_meter_list is not None and len(offline_meter_list) > 0:
339
        try:
340
            for offline_meter in offline_meter_list:
341
                offline_meter_id = str(offline_meter['id'])
342
343
                query = (" SELECT start_datetime_utc, actual_value "
344
                         " FROM tbl_offline_meter_hourly "
345
                         " WHERE offline_meter_id = %s "
346
                         "       AND start_datetime_utc >= %s "
347
                         "       AND start_datetime_utc < %s "
348
                         " ORDER BY start_datetime_utc ")
349
                cursor_energy_db.execute(query, (offline_meter_id, start_datetime_utc, end_datetime_utc,))
350
                rows_energy_values = cursor_energy_db.fetchall()
351
                if rows_energy_values is None or len(rows_energy_values) == 0:
352
                    energy_offline_meter_hourly[offline_meter_id] = None
353
                else:
354
                    energy_offline_meter_hourly[offline_meter_id] = dict()
355
                    for row_energy_value in rows_energy_values:
356
                        energy_offline_meter_hourly[offline_meter_id][row_energy_value[0]] = row_energy_value[1]
357
358
        except Exception as e:
359
            error_string = "Error in step 7.1 of store_energy_input_category.worker " + str(e)
360
            if cursor_energy_db:
361
                cursor_energy_db.close()
362
            if cnx_energy_db:
363
                cnx_energy_db.close()
364
            print(error_string)
365
            return error_string
366
367
    ####################################################################################################################
368
    # Step 8: determine common time slot to aggregate
369
    ####################################################################################################################
370
371
    common_start_datetime_utc = start_datetime_utc
372
    common_end_datetime_utc = end_datetime_utc
373
374
    print("Getting common time slot of energy values for all meters")
375
    if energy_meter_hourly is not None and len(energy_meter_hourly) > 0:
376
        for meter_id, energy_hourly in energy_meter_hourly.items():
377
            if energy_hourly is None or len(energy_hourly) == 0:
378
                common_start_datetime_utc = None
379
                common_end_datetime_utc = None
380
                break
381
            else:
382
                if common_start_datetime_utc < min(energy_hourly.keys()):
383
                    common_start_datetime_utc = min(energy_hourly.keys())
384
                if common_end_datetime_utc > max(energy_hourly.keys()):
385
                    common_end_datetime_utc = max(energy_hourly.keys())
386
387
    print("Getting common time slot of energy values for all virtual meters")
388
    if common_start_datetime_utc is not None and common_start_datetime_utc is not None:
389
        if energy_virtual_meter_hourly is not None and len(energy_virtual_meter_hourly) > 0:
390
            for meter_id, energy_hourly in energy_virtual_meter_hourly.items():
391
                if energy_hourly is None or len(energy_hourly) == 0:
392
                    common_start_datetime_utc = None
393
                    common_end_datetime_utc = None
394
                    break
395
                else:
396
                    if common_start_datetime_utc < min(energy_hourly.keys()):
397
                        common_start_datetime_utc = min(energy_hourly.keys())
398
                    if common_end_datetime_utc > max(energy_hourly.keys()):
399
                        common_end_datetime_utc = max(energy_hourly.keys())
400
401
    print("Getting common time slot of energy values for all offline meters")
402
    if common_start_datetime_utc is not None and common_start_datetime_utc is not None:
403
        if energy_offline_meter_hourly is not None and len(energy_offline_meter_hourly) > 0:
404
            for meter_id, energy_hourly in energy_offline_meter_hourly.items():
405
                if energy_hourly is None or len(energy_hourly) == 0:
406
                    common_start_datetime_utc = None
407
                    common_end_datetime_utc = None
408
                    break
409
                else:
410
                    if common_start_datetime_utc < min(energy_hourly.keys()):
411
                        common_start_datetime_utc = min(energy_hourly.keys())
412
                    if common_end_datetime_utc > max(energy_hourly.keys()):
413
                        common_end_datetime_utc = max(energy_hourly.keys())
414
415
    if (energy_meter_hourly is None or len(energy_meter_hourly) == 0) and \
416
            (energy_virtual_meter_hourly is None or len(energy_virtual_meter_hourly) == 0) and \
417
            (energy_offline_meter_hourly is None or len(energy_offline_meter_hourly) == 0):
418
        # There isn't any energy data
419
        print("There isn't any energy data")
420
        # continue the for store loop to the next store
421
        print("continue the for store loop to the next store")
422
        if cursor_energy_db:
423
            cursor_energy_db.close()
424
        if cnx_energy_db:
425
            cnx_energy_db.close()
426
        return None
427
428
    print("common_start_datetime_utc: " + str(common_start_datetime_utc))
429
    print("common_end_datetime_utc: " + str(common_end_datetime_utc))
430
431
    ####################################################################################################################
432
    # Step 9: aggregate energy data in the common time slot by energy categories and hourly
433
    ####################################################################################################################
434
435
    print("Step 9: aggregate energy data in the common time slot by energy categories and hourly")
436
    aggregated_values = list()
437
    try:
438
        current_datetime_utc = common_start_datetime_utc
439
        while common_start_datetime_utc is not None \
440
                and common_end_datetime_utc is not None \
441
                and current_datetime_utc <= common_end_datetime_utc:
442
            aggregated_value = dict()
443
            aggregated_value['start_datetime_utc'] = current_datetime_utc
444
            aggregated_value['meta_data'] = dict()
445
446
            if meter_list is not None and len(meter_list) > 0:
447
                for meter in meter_list:
448
                    meter_id = str(meter['id'])
449
                    energy_category_id = meter['energy_category_id']
450
                    actual_value = energy_meter_hourly[meter_id].get(current_datetime_utc, Decimal(0.0))
451
                    aggregated_value['meta_data'][energy_category_id] = \
452
                        aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
453
454
            if virtual_meter_list is not None and len(virtual_meter_list) > 0:
455
                for virtual_meter in virtual_meter_list:
456
                    virtual_meter_id = str(virtual_meter['id'])
457
                    energy_category_id = virtual_meter['energy_category_id']
458
                    actual_value = energy_virtual_meter_hourly[virtual_meter_id].get(current_datetime_utc, Decimal(0.0))
459
                    aggregated_value['meta_data'][energy_category_id] = \
460
                        aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
461
462
            if offline_meter_list is not None and len(offline_meter_list) > 0:
463
                for offline_meter in offline_meter_list:
464
                    offline_meter_id = str(offline_meter['id'])
465
                    energy_category_id = offline_meter['energy_category_id']
466
                    actual_value = energy_offline_meter_hourly[offline_meter_id].get(current_datetime_utc, Decimal(0.0))
467
                    aggregated_value['meta_data'][energy_category_id] = \
468
                        aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
469
470
            aggregated_values.append(aggregated_value)
471
472
            current_datetime_utc += timedelta(minutes=config.minutes_to_count)
473
474
    except Exception as e:
475
        error_string = "Error in step 9 of store_energy_input_category.worker " + str(e)
476
        if cursor_energy_db:
477
            cursor_energy_db.close()
478
        if cnx_energy_db:
479
            cnx_energy_db.close()
480
        print(error_string)
481
        return error_string
482
483
    ####################################################################################################################
484
    # Step 10: save energy data to energy database
485
    ####################################################################################################################
486
    print("Step 10: save energy data to energy database")
487
488
    if len(aggregated_values) > 0:
489
        try:
490
            add_values = (" INSERT INTO tbl_store_input_category_hourly "
491
                          "             (store_id, "
492
                          "              energy_category_id, "
493
                          "              start_datetime_utc, "
494
                          "              actual_value) "
495
                          " VALUES  ")
496
497
            for aggregated_value in aggregated_values:
498
                for energy_category_id, actual_value in aggregated_value['meta_data'].items():
499
                    add_values += " (" + str(store['id']) + ","
500
                    add_values += " " + str(energy_category_id) + ","
501
                    add_values += "'" + aggregated_value['start_datetime_utc'].isoformat()[0:19] + "',"
502
                    add_values += str(actual_value) + "), "
503
            print("add_values:" + add_values)
504
            # trim ", " at the end of string and then execute
505
            cursor_energy_db.execute(add_values[:-2])
506
            cnx_energy_db.commit()
507
508
        except Exception as e:
509
            error_string = "Error in step 10.1 of store_energy_input_category.worker " + str(e)
510
            print(error_string)
511
            return error_string
512
        finally:
513
            if cursor_energy_db:
514
                cursor_energy_db.close()
515
            if cnx_energy_db:
516
                cnx_energy_db.close()
517
    else:
518
        if cursor_energy_db:
519
            cursor_energy_db.close()
520
        if cnx_energy_db:
521
            cnx_energy_db.close()
522