space_energy_input_category.worker()   F
last analyzed

Complexity

Conditions 330

Size

Total Lines 964
Code Lines 686

Duplication

Lines 964
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 686
dl 964
loc 964
rs 0
c 0
b 0
f 0
cc 330
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_input_category.worker() 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_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_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_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 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 input meters associated with the space
93
#   Step 2: get all input virtual meters associated with the space
94
#   Step 3: get all input offline meters associated with the space
95
#   Step 4: get all combined equipments associated with the space
96
#   Step 5: get all equipments associated with the space
97
#   Step 6: get all shopfloors associated with the space
98
#   Step 7: get all stores associated with the space
99
#   Step 8: get all tenants associated with the space
100
#   Step 9: get all child spaces associated with the space
101
#   Step 10: determine start datetime and end datetime to aggregate
102
#   Step 11: for each meter in list, get energy input data from energy database
103
#   Step 12: for each virtual meter in list, get energy input data from energy database
104
#   Step 13: for each offline meter in list, get energy input data from energy database
105
#   Step 14: for each combined equipment in list, get energy input data from energy database
106
#   Step 15: for each equipment in list, get energy input data from energy database
107
#   Step 16: for each shopfloor in list, get energy input data from energy database
108
#   Step 17: for each store in list, get energy input data from energy database
109
#   Step 18: for each tenant in list, get energy input data from energy database
110
#   Step 19: for each child space in list, get energy input data from energy database
111
#   Step 20: determine common time slot to aggregate
112
#   Step 21: aggregate energy data in the common time slot by energy categories and hourly
113
#   Step 22: save energy data to energy database
114
#
115
# NOTE: returns None or the error string because that the logger object cannot be passed in as parameter
116
########################################################################################################################
117
118 View Code Duplication
def worker(space):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
119
    ####################################################################################################################
120
    # Step 1: get all input meters associated with the space
121
    ####################################################################################################################
122
    print("Step 1: get all input meters associated with the space " + str(space['name']))
123
124
    cnx_system_db = None
125
    cursor_system_db = None
126
    try:
127
        cnx_system_db = mysql.connector.connect(**config.myems_system_db)
128
        cursor_system_db = cnx_system_db.cursor()
129
    except Exception as e:
130
        error_string = "Error in step 1.1 of space_energy_input_category.worker " + str(e)
131
        if cursor_system_db:
132
            cursor_system_db.close()
133
        if cnx_system_db:
134
            cnx_system_db.close()
135
        print(error_string)
136
        return error_string
137
138
    meter_list = list()
139
    try:
140
        cursor_system_db.execute(" SELECT m.id, m.name, m.energy_category_id "
141
                                 " FROM tbl_meters m, tbl_spaces_meters sm "
142
                                 " WHERE m.id = sm.meter_id "
143
                                 "       AND m.is_counted = true "
144
                                 "       AND sm.space_id = %s ",
145
                                 (space['id'],))
146
        rows_meters = cursor_system_db.fetchall()
147
148
        if rows_meters is not None and len(rows_meters) > 0:
149
            for row in rows_meters:
150
                meter_list.append({"id": row[0],
151
                                   "name": row[1],
152
                                   "energy_category_id": row[2]})
153
154
    except Exception as e:
155
        error_string = "Error in step 1.2 of space_energy_input_category.worker " + str(e)
156
        if cursor_system_db:
157
            cursor_system_db.close()
158
        if cnx_system_db:
159
            cnx_system_db.close()
160
        print(error_string)
161
        return error_string
162
163
    ####################################################################################################################
164
    # Step 2: get all input virtual meters associated with the space
165
    ####################################################################################################################
166
    print("Step 2: get all input virtual meters associated with the space")
167
    virtual_meter_list = list()
168
169
    try:
170
        cursor_system_db.execute(" SELECT m.id, m.name, m.energy_category_id "
171
                                 " FROM tbl_virtual_meters m, tbl_spaces_virtual_meters sm "
172
                                 " WHERE m.id = sm.virtual_meter_id "
173
                                 "       AND m.is_counted = true "
174
                                 "       AND sm.space_id = %s ",
175
                                 (space['id'],))
176
        rows_virtual_meters = cursor_system_db.fetchall()
177
178
        if rows_virtual_meters is not None and len(rows_virtual_meters) > 0:
179
            for row in rows_virtual_meters:
180
                virtual_meter_list.append({"id": row[0],
181
                                           "name": row[1],
182
                                           "energy_category_id": row[2]})
183
184
    except Exception as e:
185
        error_string = "Error in step 2 of space_energy_input_category.worker " + str(e)
186
        if cursor_system_db:
187
            cursor_system_db.close()
188
        if cnx_system_db:
189
            cnx_system_db.close()
190
        print(error_string)
191
        return error_string
192
193
    ####################################################################################################################
194
    # Step 3: get all input offline meters associated with the space
195
    ####################################################################################################################
196
    print("Step 3: get all input offline meters associated with the space")
197
198
    offline_meter_list = list()
199
200
    try:
201
        cursor_system_db.execute(" SELECT m.id, m.name, m.energy_category_id "
202
                                 " FROM tbl_offline_meters m, tbl_spaces_offline_meters sm "
203
                                 " WHERE m.id = sm.offline_meter_id "
204
                                 "       AND m.is_counted = true "
205
                                 "       AND sm.space_id = %s ",
206
                                 (space['id'],))
207
        rows_offline_meters = cursor_system_db.fetchall()
208
209
        if rows_offline_meters is not None and len(rows_offline_meters) > 0:
210
            for row in rows_offline_meters:
211
                offline_meter_list.append({"id": row[0],
212
                                           "name": row[1],
213
                                           "energy_category_id": row[2]})
214
215
    except Exception as e:
216
        error_string = "Error in step 3 of space_energy_input_category.worker " + str(e)
217
        if cursor_system_db:
218
            cursor_system_db.close()
219
        if cnx_system_db:
220
            cnx_system_db.close()
221
        print(error_string)
222
        return error_string
223
224
    ####################################################################################################################
225
    # Step 4: get all combined equipments associated with the space
226
    ####################################################################################################################
227
    print("Step 4: get all combined equipments associated with the space")
228
229
    combined_equipment_list = list()
230
231
    try:
232
        cursor_system_db.execute(" SELECT e.id, e.name "
233
                                 " FROM tbl_combined_equipments e, tbl_spaces_combined_equipments se "
234
                                 " WHERE e.id = se.combined_equipment_id "
235
                                 "       AND e.is_input_counted = true "
236
                                 "       AND se.space_id = %s ",
237
                                 (space['id'],))
238
        rows_combined_equipments = cursor_system_db.fetchall()
239
240
        if rows_combined_equipments is not None and len(rows_combined_equipments) > 0:
241
            for row in rows_combined_equipments:
242
                combined_equipment_list.append({"id": row[0],
243
                                                "name": row[1]})
244
245
    except Exception as e:
246
        error_string = "Error in step 4 of space_energy_input_category.worker " + str(e)
247
        if cursor_system_db:
248
            cursor_system_db.close()
249
        if cnx_system_db:
250
            cnx_system_db.close()
251
        print(error_string)
252
        return error_string
253
254
    ####################################################################################################################
255
    # Step 5: get all equipments associated with the space
256
    ####################################################################################################################
257
    print("Step 5: get all equipments associated with the space")
258
259
    equipment_list = list()
260
261
    try:
262
        cursor_system_db.execute(" SELECT e.id, e.name "
263
                                 " FROM tbl_equipments e, tbl_spaces_equipments se "
264
                                 " WHERE e.id = se.equipment_id "
265
                                 "       AND e.is_input_counted = true "
266
                                 "       AND se.space_id = %s ",
267
                                 (space['id'],))
268
        rows_equipments = cursor_system_db.fetchall()
269
270
        if rows_equipments is not None and len(rows_equipments) > 0:
271
            for row in rows_equipments:
272
                equipment_list.append({"id": row[0],
273
                                       "name": row[1]})
274
275
    except Exception as e:
276
        error_string = "Error in step 5 of space_energy_input_category.worker " + str(e)
277
        if cursor_system_db:
278
            cursor_system_db.close()
279
        if cnx_system_db:
280
            cnx_system_db.close()
281
        print(error_string)
282
        return error_string
283
284
    ####################################################################################################################
285
    # Step 6: get all shopfloors associated with the space
286
    ####################################################################################################################
287
    print("Step 6: get all shopfloors associated with the space")
288
289
    shopfloor_list = list()
290
291
    try:
292
        cursor_system_db.execute(" SELECT s.id, s.name "
293
                                 " FROM tbl_shopfloors s, tbl_spaces_shopfloors ss "
294
                                 " WHERE s.id = ss.shopfloor_id "
295
                                 "       AND s.is_input_counted = true "
296
                                 "       AND ss.space_id = %s ",
297
                                 (space['id'],))
298
        rows_shopfloors = cursor_system_db.fetchall()
299
300
        if rows_shopfloors is not None and len(rows_shopfloors) > 0:
301
            for row in rows_shopfloors:
302
                shopfloor_list.append({"id": row[0],
303
                                       "name": row[1]})
304
305
    except Exception as e:
306
        error_string = "Error in step 6 of space_energy_input_category.worker " + str(e)
307
        if cursor_system_db:
308
            cursor_system_db.close()
309
        if cnx_system_db:
310
            cnx_system_db.close()
311
        print(error_string)
312
        return error_string
313
314
    ####################################################################################################################
315
    # Step 7: get all stores associated with the space
316
    ####################################################################################################################
317
    print("Step 7: get all stores associated with the space")
318
319
    store_list = list()
320
321
    try:
322
        cursor_system_db.execute(" SELECT s.id, s.name "
323
                                 " FROM tbl_stores s, tbl_spaces_stores ss "
324
                                 " WHERE s.id = ss.store_id "
325
                                 "       AND s.is_input_counted = true "
326
                                 "       AND ss.space_id = %s ",
327
                                 (space['id'],))
328
        rows_stores = cursor_system_db.fetchall()
329
330
        if rows_stores is not None and len(rows_stores) > 0:
331
            for row in rows_stores:
332
                store_list.append({"id": row[0],
333
                                   "name": row[1]})
334
335
    except Exception as e:
336
        error_string = "Error in step 7 of space_energy_input_category.worker " + str(e)
337
        if cursor_system_db:
338
            cursor_system_db.close()
339
        if cnx_system_db:
340
            cnx_system_db.close()
341
        print(error_string)
342
        return error_string
343
344
    ####################################################################################################################
345
    # Step 8: get all tenants associated with the space
346
    ####################################################################################################################
347
    print("Step 8: get all tenants associated with the space")
348
349
    tenant_list = list()
350
351
    try:
352
        cursor_system_db.execute(" SELECT t.id, t.name "
353
                                 " FROM tbl_tenants t, tbl_spaces_tenants st "
354
                                 " WHERE t.id = st.tenant_id "
355
                                 "       AND t.is_input_counted = true "
356
                                 "       AND st.space_id = %s ",
357
                                 (space['id'],))
358
        rows_tenants = cursor_system_db.fetchall()
359
360
        if rows_tenants is not None and len(rows_tenants) > 0:
361
            for row in rows_tenants:
362
                tenant_list.append({"id": row[0],
363
                                    "name": row[1]})
364
365
    except Exception as e:
366
        error_string = "Error in step 8 of space_energy_input_category.worker " + str(e)
367
        if cursor_system_db:
368
            cursor_system_db.close()
369
        if cnx_system_db:
370
            cnx_system_db.close()
371
        print(error_string)
372
        return error_string
373
374
    ####################################################################################################################
375
    # Step 9: get all child spaces associated with the space
376
    ####################################################################################################################
377
    print("Step 9: get all child spaces associated with the space")
378
379
    child_space_list = list()
380
381
    try:
382
        cursor_system_db.execute(" SELECT id, name "
383
                                 " FROM tbl_spaces "
384
                                 " WHERE is_input_counted = true "
385
                                 "       AND parent_space_id = %s ",
386
                                 (space['id'],))
387
        rows_child_spaces = cursor_system_db.fetchall()
388
389
        if rows_child_spaces is not None and len(rows_child_spaces) > 0:
390
            for row in rows_child_spaces:
391
                child_space_list.append({"id": row[0],
392
                                         "name": row[1]})
393
394
    except Exception as e:
395
        error_string = "Error in step 9 of space_energy_input_category.worker " + str(e)
396
        print(error_string)
397
        return error_string
398
    finally:
399
        if cursor_system_db:
400
            cursor_system_db.close()
401
        if cnx_system_db:
402
            cnx_system_db.close()
403
404
    if (meter_list is None or len(meter_list) == 0) and \
405
            (virtual_meter_list is None or len(virtual_meter_list) == 0) and \
406
            (offline_meter_list is None or len(offline_meter_list) == 0) and \
407
            (combined_equipment_list is None or len(combined_equipment_list) == 0) and \
408
            (equipment_list is None or len(equipment_list) == 0) and \
409
            (shopfloor_list is None or len(shopfloor_list) == 0) and \
410
            (store_list is None or len(store_list) == 0) and \
411
            (tenant_list is None or len(tenant_list) == 0) and \
412
            (child_space_list is None or len(child_space_list) == 0):
413
        print("This is an empty space ")
414
        return None
415
416
    ####################################################################################################################
417
    # Step 10: determine start datetime and end datetime to aggregate
418
    ####################################################################################################################
419
    print("Step 10: determine start datetime and end datetime to aggregate")
420
    cnx_energy_db = None
421
    cursor_energy_db = None
422
    try:
423
        cnx_energy_db = mysql.connector.connect(**config.myems_energy_db)
424
        cursor_energy_db = cnx_energy_db.cursor()
425
    except Exception as e:
426
        error_string = "Error in step 10.1 of space_energy_input_category.worker " + str(e)
427
        if cursor_energy_db:
428
            cursor_energy_db.close()
429
        if cnx_energy_db:
430
            cnx_energy_db.close()
431
        print(error_string)
432
        return error_string
433
434
    try:
435
        query = (" SELECT MAX(start_datetime_utc) "
436
                 " FROM tbl_space_input_category_hourly "
437
                 " WHERE space_id = %s ")
438
        cursor_energy_db.execute(query, (space['id'],))
439
        row_datetime = cursor_energy_db.fetchone()
440
        start_datetime_utc = datetime.strptime(config.start_datetime_utc, '%Y-%m-%d %H:%M:%S')
441
        start_datetime_utc = start_datetime_utc.replace(minute=0, second=0, microsecond=0, tzinfo=None)
442
443
        if row_datetime is not None and len(row_datetime) > 0 and isinstance(row_datetime[0], datetime):
444
            # replace second and microsecond with 0
445
            # note: do not replace minute in case of calculating in half hourly
446
            start_datetime_utc = row_datetime[0].replace(second=0, microsecond=0, tzinfo=None)
447
            # start from the next time slot
448
            start_datetime_utc += timedelta(minutes=config.minutes_to_count)
449
450
        end_datetime_utc = datetime.utcnow().replace(second=0, microsecond=0, tzinfo=None)
451
452
        print("start_datetime_utc: " + start_datetime_utc.isoformat()[0:19]
453
              + "end_datetime_utc: " + end_datetime_utc.isoformat()[0:19])
454
455
    except Exception as e:
456
        error_string = "Error in step 10.2 of space_energy_input_category.worker " + str(e)
457
        if cursor_energy_db:
458
            cursor_energy_db.close()
459
        if cnx_energy_db:
460
            cnx_energy_db.close()
461
        print(error_string)
462
        return error_string
463
464
    ####################################################################################################################
465
    # Step 11: for each meter in list, get energy input data from energy database
466
    ####################################################################################################################
467
    energy_meter_hourly = dict()
468
    try:
469
        if meter_list is not None and len(meter_list) > 0:
470
            for meter in meter_list:
471
                meter_id = str(meter['id'])
472
473
                query = (" SELECT start_datetime_utc, actual_value "
474
                         " FROM tbl_meter_hourly "
475
                         " WHERE meter_id = %s "
476
                         "       AND start_datetime_utc >= %s "
477
                         "       AND start_datetime_utc < %s "
478
                         " ORDER BY start_datetime_utc ")
479
                cursor_energy_db.execute(query, (meter_id, start_datetime_utc, end_datetime_utc,))
480
                rows_energy_values = cursor_energy_db.fetchall()
481
                if rows_energy_values is None or len(rows_energy_values) == 0:
482
                    energy_meter_hourly[meter_id] = None
483
                else:
484
                    energy_meter_hourly[meter_id] = dict()
485
                    for row_energy_value in rows_energy_values:
486
                        energy_meter_hourly[meter_id][row_energy_value[0]] = row_energy_value[1]
487
    except Exception as e:
488
        error_string = "Error in step 11 of space_energy_input_category.worker " + str(e)
489
        if cursor_energy_db:
490
            cursor_energy_db.close()
491
        if cnx_energy_db:
492
            cnx_energy_db.close()
493
        print(error_string)
494
        return error_string
495
496
    ####################################################################################################################
497
    # Step 12: for each virtual meter in list, get energy input data from energy database
498
    ####################################################################################################################
499
    energy_virtual_meter_hourly = dict()
500
    if virtual_meter_list is not None and len(virtual_meter_list) > 0:
501
        try:
502
            for virtual_meter in virtual_meter_list:
503
                virtual_meter_id = str(virtual_meter['id'])
504
505
                query = (" SELECT start_datetime_utc, actual_value "
506
                         " FROM tbl_virtual_meter_hourly "
507
                         " WHERE virtual_meter_id = %s "
508
                         "       AND start_datetime_utc >= %s "
509
                         "       AND start_datetime_utc < %s "
510
                         " ORDER BY start_datetime_utc ")
511
                cursor_energy_db.execute(query, (virtual_meter_id, start_datetime_utc, end_datetime_utc,))
512
                rows_energy_values = cursor_energy_db.fetchall()
513
                if rows_energy_values is None or len(rows_energy_values) == 0:
514
                    energy_virtual_meter_hourly[virtual_meter_id] = None
515
                else:
516
                    energy_virtual_meter_hourly[virtual_meter_id] = dict()
517
                    for row_energy_value in rows_energy_values:
518
                        energy_virtual_meter_hourly[virtual_meter_id][row_energy_value[0]] = row_energy_value[1]
519
        except Exception as e:
520
            error_string = "Error in step 12 of space_energy_input_category.worker " + str(e)
521
            if cursor_energy_db:
522
                cursor_energy_db.close()
523
            if cnx_energy_db:
524
                cnx_energy_db.close()
525
            print(error_string)
526
            return error_string
527
528
    ####################################################################################################################
529
    # Step 13: for each offline meter in list, get energy input data from energy database
530
    ####################################################################################################################
531
    energy_offline_meter_hourly = dict()
532
    if offline_meter_list is not None and len(offline_meter_list) > 0:
533
        try:
534
            for offline_meter in offline_meter_list:
535
                offline_meter_id = str(offline_meter['id'])
536
537
                query = (" SELECT start_datetime_utc, actual_value "
538
                         " FROM tbl_offline_meter_hourly "
539
                         " WHERE offline_meter_id = %s "
540
                         "       AND start_datetime_utc >= %s "
541
                         "       AND start_datetime_utc < %s "
542
                         " ORDER BY start_datetime_utc ")
543
                cursor_energy_db.execute(query, (offline_meter_id, start_datetime_utc, end_datetime_utc,))
544
                rows_energy_values = cursor_energy_db.fetchall()
545
                if rows_energy_values is None or len(rows_energy_values) == 0:
546
                    energy_offline_meter_hourly[offline_meter_id] = None
547
                else:
548
                    energy_offline_meter_hourly[offline_meter_id] = dict()
549
                    for row_energy_value in rows_energy_values:
550
                        energy_offline_meter_hourly[offline_meter_id][row_energy_value[0]] = row_energy_value[1]
551
552
        except Exception as e:
553
            error_string = "Error in step 13 of space_energy_input_category.worker " + str(e)
554
            if cursor_energy_db:
555
                cursor_energy_db.close()
556
            if cnx_energy_db:
557
                cnx_energy_db.close()
558
            print(error_string)
559
            return error_string
560
561
    ####################################################################################################################
562
    # Step 14: for each combined equipment in list, get energy input data from energy database
563
    ####################################################################################################################
564
    energy_combined_equipment_hourly = dict()
565
    if combined_equipment_list is not None and len(combined_equipment_list) > 0:
566
        try:
567
            for combined_equipment in combined_equipment_list:
568
                combined_equipment_id = str(combined_equipment['id'])
569
                query = (" SELECT start_datetime_utc, energy_category_id, actual_value "
570
                         " FROM tbl_combined_equipment_input_category_hourly "
571
                         " WHERE combined_equipment_id = %s "
572
                         "       AND start_datetime_utc >= %s "
573
                         "       AND start_datetime_utc < %s "
574
                         " ORDER BY start_datetime_utc ")
575
                cursor_energy_db.execute(query, (combined_equipment_id, start_datetime_utc, end_datetime_utc,))
576
                rows_energy_values = cursor_energy_db.fetchall()
577
                if rows_energy_values is None or len(rows_energy_values) == 0:
578
                    energy_combined_equipment_hourly[combined_equipment_id] = None
579
                else:
580
                    energy_combined_equipment_hourly[combined_equipment_id] = dict()
581
                    for row_value in rows_energy_values:
582
                        current_datetime_utc = row_value[0]
583
                        if current_datetime_utc not in energy_combined_equipment_hourly[combined_equipment_id]:
584
                            energy_combined_equipment_hourly[combined_equipment_id][current_datetime_utc] = dict()
585
                        energy_category_id = row_value[1]
586
                        actual_value = row_value[2]
587
                        energy_combined_equipment_hourly[combined_equipment_id][current_datetime_utc][energy_category_id] = actual_value
588
        except Exception as e:
589
            error_string = "Error in step 14 of space_energy_input_category.worker " + str(e)
590
            if cursor_energy_db:
591
                cursor_energy_db.close()
592
            if cnx_energy_db:
593
                cnx_energy_db.close()
594
            print(error_string)
595
            return error_string
596
597
    ####################################################################################################################
598
    # Step 15: for each equipment in list, get energy input data from energy database
599
    ####################################################################################################################
600
    energy_equipment_hourly = dict()
601
    if equipment_list is not None and len(equipment_list) > 0:
602
        try:
603
            for equipment in equipment_list:
604
                equipment_id = str(equipment['id'])
605
                query = (" SELECT start_datetime_utc, energy_category_id, actual_value "
606
                         " FROM tbl_equipment_input_category_hourly "
607
                         " WHERE equipment_id = %s "
608
                         "       AND start_datetime_utc >= %s "
609
                         "       AND start_datetime_utc < %s "
610
                         " ORDER BY start_datetime_utc ")
611
                cursor_energy_db.execute(query, (equipment_id, start_datetime_utc, end_datetime_utc,))
612
                rows_energy_values = cursor_energy_db.fetchall()
613
                if rows_energy_values is None or len(rows_energy_values) == 0:
614
                    energy_equipment_hourly[equipment_id] = None
615
                else:
616
                    energy_equipment_hourly[equipment_id] = dict()
617
                    for row_value in rows_energy_values:
618
                        current_datetime_utc = row_value[0]
619
                        if current_datetime_utc not in energy_equipment_hourly[equipment_id]:
620
                            energy_equipment_hourly[equipment_id][current_datetime_utc] = dict()
621
                        energy_category_id = row_value[1]
622
                        actual_value = row_value[2]
623
                        energy_equipment_hourly[equipment_id][current_datetime_utc][energy_category_id] = \
624
                            actual_value
625
        except Exception as e:
626
            error_string = "Error in step 15 of space_energy_input_category.worker " + str(e)
627
            if cursor_energy_db:
628
                cursor_energy_db.close()
629
            if cnx_energy_db:
630
                cnx_energy_db.close()
631
            print(error_string)
632
            return error_string
633
634
    ####################################################################################################################
635
    # Step 16: for each shopfloor in list, get energy input data from energy database
636
    ####################################################################################################################
637
    energy_shopfloor_hourly = dict()
638
    if shopfloor_list is not None and len(shopfloor_list) > 0:
639
        try:
640
            for shopfloor in shopfloor_list:
641
                shopfloor_id = str(shopfloor['id'])
642
643
                query = (" SELECT start_datetime_utc, energy_category_id, actual_value "
644
                         " FROM tbl_shopfloor_input_category_hourly "
645
                         " WHERE shopfloor_id = %s "
646
                         "       AND start_datetime_utc >= %s "
647
                         "       AND start_datetime_utc < %s "
648
                         " ORDER BY start_datetime_utc ")
649
                cursor_energy_db.execute(query, (shopfloor_id, start_datetime_utc, end_datetime_utc,))
650
                rows_energy_values = cursor_energy_db.fetchall()
651
                if rows_energy_values is None or len(rows_energy_values) == 0:
652
                    energy_shopfloor_hourly[shopfloor_id] = None
653
                else:
654
                    energy_shopfloor_hourly[shopfloor_id] = dict()
655
                    for row_energy_value in rows_energy_values:
656
                        current_datetime_utc = row_energy_value[0]
657
                        if current_datetime_utc not in energy_shopfloor_hourly[shopfloor_id]:
658
                            energy_shopfloor_hourly[shopfloor_id][current_datetime_utc] = dict()
659
                        energy_category_id = row_energy_value[1]
660
                        actual_value = row_energy_value[2]
661
                        energy_shopfloor_hourly[shopfloor_id][current_datetime_utc][energy_category_id] = actual_value
662
        except Exception as e:
663
            error_string = "Error in step 16 of space_energy_input_category.worker " + str(e)
664
            if cursor_energy_db:
665
                cursor_energy_db.close()
666
            if cnx_energy_db:
667
                cnx_energy_db.close()
668
            print(error_string)
669
            return error_string
670
671
    ####################################################################################################################
672
    # Step 17: for each store in list, get energy input data from energy database
673
    ####################################################################################################################
674
    energy_store_hourly = dict()
675
    if store_list is not None and len(store_list) > 0:
676
        try:
677
            for store in store_list:
678
                store_id = str(store['id'])
679
680
                query = (" SELECT start_datetime_utc, energy_category_id, actual_value "
681
                         " FROM tbl_store_input_category_hourly "
682
                         " WHERE store_id = %s "
683
                         "       AND start_datetime_utc >= %s "
684
                         "       AND start_datetime_utc < %s "
685
                         " ORDER BY start_datetime_utc ")
686
                cursor_energy_db.execute(query, (store_id, start_datetime_utc, end_datetime_utc,))
687
                rows_energy_values = cursor_energy_db.fetchall()
688
                if rows_energy_values is None or len(rows_energy_values) == 0:
689
                    energy_store_hourly[store_id] = None
690
                else:
691
                    energy_store_hourly[store_id] = dict()
692
                    for row_energy_value in rows_energy_values:
693
                        current_datetime_utc = row_energy_value[0]
694
                        if current_datetime_utc not in energy_store_hourly[store_id]:
695
                            energy_store_hourly[store_id][current_datetime_utc] = dict()
696
                        energy_category_id = row_energy_value[1]
697
                        actual_value = row_energy_value[2]
698
                        energy_store_hourly[store_id][current_datetime_utc][energy_category_id] = actual_value
699
        except Exception as e:
700
            error_string = "Error in step 17 of space_energy_input_category.worker " + str(e)
701
            if cursor_energy_db:
702
                cursor_energy_db.close()
703
            if cnx_energy_db:
704
                cnx_energy_db.close()
705
            print(error_string)
706
            return error_string
707
708
    ####################################################################################################################
709
    # Step 18: for each tenant in list, get energy input data from energy database
710
    ####################################################################################################################
711
    energy_tenant_hourly = dict()
712
    if tenant_list is not None and len(tenant_list) > 0:
713
        try:
714
            for tenant in tenant_list:
715
                tenant_id = str(tenant['id'])
716
717
                query = (" SELECT start_datetime_utc, energy_category_id, actual_value "
718
                         " FROM tbl_tenant_input_category_hourly "
719
                         " WHERE tenant_id = %s "
720
                         "       AND start_datetime_utc >= %s "
721
                         "       AND start_datetime_utc < %s "
722
                         " ORDER BY start_datetime_utc ")
723
                cursor_energy_db.execute(query, (tenant_id, start_datetime_utc, end_datetime_utc,))
724
                rows_energy_values = cursor_energy_db.fetchall()
725
                if rows_energy_values is None or len(rows_energy_values) == 0:
726
                    energy_tenant_hourly[tenant_id] = None
727
                else:
728
                    energy_tenant_hourly[tenant_id] = dict()
729
                    for row_energy_value in rows_energy_values:
730
                        current_datetime_utc = row_energy_value[0]
731
                        if current_datetime_utc not in energy_tenant_hourly[tenant_id]:
732
                            energy_tenant_hourly[tenant_id][current_datetime_utc] = dict()
733
                        energy_category_id = row_energy_value[1]
734
                        actual_value = row_energy_value[2]
735
                        energy_tenant_hourly[tenant_id][current_datetime_utc][energy_category_id] = actual_value
736
        except Exception as e:
737
            error_string = "Error in step 18 of space_energy_input_category.worker " + str(e)
738
            if cursor_energy_db:
739
                cursor_energy_db.close()
740
            if cnx_energy_db:
741
                cnx_energy_db.close()
742
            print(error_string)
743
            return error_string
744
745
    ####################################################################################################################
746
    # Step 19: for each child space in list, get energy input data from energy database
747
    ####################################################################################################################
748
    energy_child_space_hourly = dict()
749
    if child_space_list is not None and len(child_space_list) > 0:
750
        try:
751
            for child_space in child_space_list:
752
                child_space_id = str(child_space['id'])
753
754
                query = (" SELECT start_datetime_utc, energy_category_id, actual_value "
755
                         " FROM tbl_space_input_category_hourly "
756
                         " WHERE space_id = %s "
757
                         "       AND start_datetime_utc >= %s "
758
                         "       AND start_datetime_utc < %s "
759
                         " ORDER BY start_datetime_utc ")
760
                cursor_energy_db.execute(query, (child_space_id, start_datetime_utc, end_datetime_utc,))
761
                rows_energy_values = cursor_energy_db.fetchall()
762
                if rows_energy_values is None or len(rows_energy_values) == 0:
763
                    energy_child_space_hourly[child_space_id] = None
764
                else:
765
                    energy_child_space_hourly[child_space_id] = dict()
766
                    for row_energy_value in rows_energy_values:
767
                        current_datetime_utc = row_energy_value[0]
768
                        if current_datetime_utc not in energy_child_space_hourly[child_space_id]:
769
                            energy_child_space_hourly[child_space_id][current_datetime_utc] = dict()
770
                        energy_category_id = row_energy_value[1]
771
                        actual_value = row_energy_value[2]
772
                        energy_child_space_hourly[child_space_id][current_datetime_utc][energy_category_id] = actual_value
773
        except Exception as e:
774
            error_string = "Error in step 19 of space_energy_input_category.worker " + str(e)
775
            if cursor_energy_db:
776
                cursor_energy_db.close()
777
            if cnx_energy_db:
778
                cnx_energy_db.close()
779
            print(error_string)
780
            return error_string
781
782
    ####################################################################################################################
783
    # Step 20: determine common time slot to aggregate
784
    ####################################################################################################################
785
786
    common_start_datetime_utc = start_datetime_utc
787
    common_end_datetime_utc = end_datetime_utc
788
789
    print("Getting common time slot of energy values for all meters")
790
    if energy_meter_hourly is not None and len(energy_meter_hourly) > 0:
791
        for meter_id, energy_hourly in energy_meter_hourly.items():
792
            if energy_hourly is None or len(energy_hourly) == 0:
793
                common_start_datetime_utc = None
794
                common_end_datetime_utc = None
795
                break
796
            else:
797
                if common_start_datetime_utc < min(energy_hourly.keys()):
798
                    common_start_datetime_utc = min(energy_hourly.keys())
799
                if common_end_datetime_utc > max(energy_hourly.keys()):
800
                    common_end_datetime_utc = max(energy_hourly.keys())
801
802
    print("Getting common time slot of energy values for all virtual meters")
803
    if common_start_datetime_utc is not None and common_start_datetime_utc is not None:
804
        if energy_virtual_meter_hourly is not None and len(energy_virtual_meter_hourly) > 0:
805
            for meter_id, energy_hourly in energy_virtual_meter_hourly.items():
806
                if energy_hourly is None or len(energy_hourly) == 0:
807
                    common_start_datetime_utc = None
808
                    common_end_datetime_utc = None
809
                    break
810
                else:
811
                    if common_start_datetime_utc < min(energy_hourly.keys()):
812
                        common_start_datetime_utc = min(energy_hourly.keys())
813
                    if common_end_datetime_utc > max(energy_hourly.keys()):
814
                        common_end_datetime_utc = max(energy_hourly.keys())
815
816
    print("Getting common time slot of energy values for all offline meters")
817
    if common_start_datetime_utc is not None and common_start_datetime_utc is not None:
818
        if energy_offline_meter_hourly is not None and len(energy_offline_meter_hourly) > 0:
819
            for meter_id, energy_hourly in energy_offline_meter_hourly.items():
820
                if energy_hourly is None or len(energy_hourly) == 0:
821
                    common_start_datetime_utc = None
822
                    common_end_datetime_utc = None
823
                    break
824
                else:
825
                    if common_start_datetime_utc < min(energy_hourly.keys()):
826
                        common_start_datetime_utc = min(energy_hourly.keys())
827
                    if common_end_datetime_utc > max(energy_hourly.keys()):
828
                        common_end_datetime_utc = max(energy_hourly.keys())
829
830
    print("Getting common time slot of energy values for all combined equipments")
831
    if common_start_datetime_utc is not None and common_start_datetime_utc is not None:
832
        if energy_combined_equipment_hourly is not None and len(energy_combined_equipment_hourly) > 0:
833
            for combined_equipment_id, energy_hourly in energy_combined_equipment_hourly.items():
834
                if energy_hourly is None or len(energy_hourly) == 0:
835
                    common_start_datetime_utc = None
836
                    common_end_datetime_utc = None
837
                    break
838
                else:
839
                    if common_start_datetime_utc < min(energy_hourly.keys()):
840
                        common_start_datetime_utc = min(energy_hourly.keys())
841
                    if common_end_datetime_utc > max(energy_hourly.keys()):
842
                        common_end_datetime_utc = max(energy_hourly.keys())
843
844
    print("Getting common time slot of energy values for all equipments")
845
    if common_start_datetime_utc is not None and common_start_datetime_utc is not None:
846
        if energy_equipment_hourly is not None and len(energy_equipment_hourly) > 0:
847
            for equipment_id, energy_hourly in energy_equipment_hourly.items():
848
                if energy_hourly is None or len(energy_hourly) == 0:
849
                    common_start_datetime_utc = None
850
                    common_end_datetime_utc = None
851
                    break
852
                else:
853
                    if common_start_datetime_utc < min(energy_hourly.keys()):
854
                        common_start_datetime_utc = min(energy_hourly.keys())
855
                    if common_end_datetime_utc > max(energy_hourly.keys()):
856
                        common_end_datetime_utc = max(energy_hourly.keys())
857
858
    print("Getting common time slot of energy values for all shopfloors")
859
    if common_start_datetime_utc is not None and common_start_datetime_utc is not None:
860
        if energy_shopfloor_hourly is not None and len(energy_shopfloor_hourly) > 0:
861
            for shopfloor_id, energy_hourly in energy_shopfloor_hourly.items():
862
                if energy_hourly is None or len(energy_hourly) == 0:
863
                    common_start_datetime_utc = None
864
                    common_end_datetime_utc = None
865
                    break
866
                else:
867
                    if common_start_datetime_utc < min(energy_hourly.keys()):
868
                        common_start_datetime_utc = min(energy_hourly.keys())
869
                    if common_end_datetime_utc > max(energy_hourly.keys()):
870
                        common_end_datetime_utc = max(energy_hourly.keys())
871
872
    print("Getting common time slot of energy values for all stores")
873
    if common_start_datetime_utc is not None and common_start_datetime_utc is not None:
874
        if energy_store_hourly is not None and len(energy_store_hourly) > 0:
875
            for store_id, energy_hourly in energy_store_hourly.items():
876
                if energy_hourly is None or len(energy_hourly) == 0:
877
                    common_start_datetime_utc = None
878
                    common_end_datetime_utc = None
879
                    break
880
                else:
881
                    if common_start_datetime_utc < min(energy_hourly.keys()):
882
                        common_start_datetime_utc = min(energy_hourly.keys())
883
                    if common_end_datetime_utc > max(energy_hourly.keys()):
884
                        common_end_datetime_utc = max(energy_hourly.keys())
885
886
    print("Getting common time slot of energy values for all tenants")
887
    if common_start_datetime_utc is not None and common_start_datetime_utc is not None:
888
        if energy_tenant_hourly is not None and len(energy_tenant_hourly) > 0:
889
            for tenant_id, energy_hourly in energy_tenant_hourly.items():
890
                if energy_hourly is None or len(energy_hourly) == 0:
891
                    common_start_datetime_utc = None
892
                    common_end_datetime_utc = None
893
                    break
894
                else:
895
                    if common_start_datetime_utc < min(energy_hourly.keys()):
896
                        common_start_datetime_utc = min(energy_hourly.keys())
897
                    if common_end_datetime_utc > max(energy_hourly.keys()):
898
                        common_end_datetime_utc = max(energy_hourly.keys())
899
900
    print("Getting common time slot of energy values for all child spaces")
901
    if common_start_datetime_utc is not None and common_start_datetime_utc is not None:
902
        if energy_child_space_hourly is not None and len(energy_child_space_hourly) > 0:
903
            for child_space_id, energy_hourly in energy_child_space_hourly.items():
904
                if energy_hourly is None or len(energy_hourly) == 0:
905
                    common_start_datetime_utc = None
906
                    common_end_datetime_utc = None
907
                    break
908
                else:
909
                    if common_start_datetime_utc < min(energy_hourly.keys()):
910
                        common_start_datetime_utc = min(energy_hourly.keys())
911
                    if common_end_datetime_utc > max(energy_hourly.keys()):
912
                        common_end_datetime_utc = max(energy_hourly.keys())
913
914
    if (energy_meter_hourly is None or len(energy_meter_hourly) == 0) and \
915
            (energy_virtual_meter_hourly is None or len(energy_virtual_meter_hourly) == 0) and \
916
            (energy_offline_meter_hourly is None or len(energy_offline_meter_hourly) == 0) and \
917
            (energy_combined_equipment_hourly is None or len(energy_combined_equipment_hourly) == 0) and \
918
            (energy_equipment_hourly is None or len(energy_equipment_hourly) == 0) and \
919
            (energy_shopfloor_hourly is None or len(energy_shopfloor_hourly) == 0) and \
920
            (energy_store_hourly is None or len(energy_store_hourly) == 0) and \
921
            (energy_tenant_hourly is None or len(energy_tenant_hourly) == 0) and \
922
            (energy_child_space_hourly is None or len(energy_child_space_hourly) == 0):
923
        # There isn't any energy data
924
        print("There isn't any energy data")
925
        # continue the for space loop to the next space
926
        print("continue the for space loop to the next space")
927
        if cursor_energy_db:
928
            cursor_energy_db.close()
929
        if cnx_energy_db:
930
            cnx_energy_db.close()
931
        return None
932
933
    print("common_start_datetime_utc: " + str(common_start_datetime_utc))
934
    print("common_end_datetime_utc: " + str(common_end_datetime_utc))
935
936
    ####################################################################################################################
937
    # Step 21: aggregate energy data in the common time slot by energy categories and hourly
938
    ####################################################################################################################
939
940
    print("Step 21: aggregate energy data in the common time slot by energy categories and hourly")
941
    aggregated_values = list()
942
    try:
943
        current_datetime_utc = common_start_datetime_utc
944
        while common_start_datetime_utc is not None \
945
                and common_end_datetime_utc is not None \
946
                and current_datetime_utc <= common_end_datetime_utc:
947
            aggregated_value = dict()
948
            aggregated_value['start_datetime_utc'] = current_datetime_utc
949
            aggregated_value['meta_data'] = dict()
950
951
            if meter_list is not None and len(meter_list) > 0:
952
                for meter in meter_list:
953
                    meter_id = str(meter['id'])
954
                    energy_category_id = meter['energy_category_id']
955
                    actual_value = energy_meter_hourly[meter_id].get(current_datetime_utc, Decimal(0.0))
956
                    aggregated_value['meta_data'][energy_category_id] = \
957
                        aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
958
959
            if virtual_meter_list is not None and len(virtual_meter_list) > 0:
960
                for virtual_meter in virtual_meter_list:
961
                    virtual_meter_id = str(virtual_meter['id'])
962
                    energy_category_id = virtual_meter['energy_category_id']
963
                    actual_value = energy_virtual_meter_hourly[virtual_meter_id].get(current_datetime_utc, Decimal(0.0))
964
                    aggregated_value['meta_data'][energy_category_id] = \
965
                        aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
966
967
            if offline_meter_list is not None and len(offline_meter_list) > 0:
968
                for offline_meter in offline_meter_list:
969
                    offline_meter_id = str(offline_meter['id'])
970
                    energy_category_id = offline_meter['energy_category_id']
971
                    actual_value = energy_offline_meter_hourly[offline_meter_id].get(current_datetime_utc, Decimal(0.0))
972
                    aggregated_value['meta_data'][energy_category_id] = \
973
                        aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
974
975
            if combined_equipment_list is not None and len(combined_equipment_list) > 0:
976
                for combined_equipment in combined_equipment_list:
977
                    combined_equipment_id = str(combined_equipment['id'])
978
                    meta_data_dict = \
979
                        energy_combined_equipment_hourly[combined_equipment_id].get(current_datetime_utc, None)
980
                    if meta_data_dict is not None and len(meta_data_dict) > 0:
981
                        for energy_category_id, actual_value in meta_data_dict.items():
982
                            aggregated_value['meta_data'][energy_category_id] = \
983
                                aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
984
985
            if equipment_list is not None and len(equipment_list) > 0:
986
                for equipment in equipment_list:
987
                    equipment_id = str(equipment['id'])
988
                    meta_data_dict = energy_equipment_hourly[equipment_id].get(current_datetime_utc, None)
989
                    if meta_data_dict is not None and len(meta_data_dict) > 0:
990
                        for energy_category_id, actual_value in meta_data_dict.items():
991
                            aggregated_value['meta_data'][energy_category_id] = \
992
                                aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
993
994
            if shopfloor_list is not None and len(shopfloor_list) > 0:
995
                for shopfloor in shopfloor_list:
996
                    shopfloor_id = str(shopfloor['id'])
997
                    meta_data_dict = energy_shopfloor_hourly[shopfloor_id].get(current_datetime_utc, None)
998
                    if meta_data_dict is not None and len(meta_data_dict) > 0:
999
                        for energy_category_id, actual_value in meta_data_dict.items():
1000
                            aggregated_value['meta_data'][energy_category_id] = \
1001
                                aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
1002
1003
            if store_list is not None and len(store_list) > 0:
1004
                for store in store_list:
1005
                    store_id = str(store['id'])
1006
                    meta_data_dict = energy_store_hourly[store_id].get(current_datetime_utc, None)
1007
                    if meta_data_dict is not None and len(meta_data_dict) > 0:
1008
                        for energy_category_id, actual_value in meta_data_dict.items():
1009
                            aggregated_value['meta_data'][energy_category_id] = \
1010
                                aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
1011
1012
            if tenant_list is not None and len(tenant_list) > 0:
1013
                for tenant in tenant_list:
1014
                    tenant_id = str(tenant['id'])
1015
                    meta_data_dict = energy_tenant_hourly[tenant_id].get(current_datetime_utc, None)
1016
                    if meta_data_dict is not None and len(meta_data_dict) > 0:
1017
                        for energy_category_id, actual_value in meta_data_dict.items():
1018
                            aggregated_value['meta_data'][energy_category_id] = \
1019
                                aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
1020
1021
            if child_space_list is not None and len(child_space_list) > 0:
1022
                for child_space in child_space_list:
1023
                    child_space_id = str(child_space['id'])
1024
                    meta_data_dict = energy_child_space_hourly[child_space_id].get(current_datetime_utc, None)
1025
                    if meta_data_dict is not None and len(meta_data_dict) > 0:
1026
                        for energy_category_id, actual_value in meta_data_dict.items():
1027
                            aggregated_value['meta_data'][energy_category_id] = \
1028
                                aggregated_value['meta_data'].get(energy_category_id, Decimal(0.0)) + actual_value
1029
1030
            aggregated_values.append(aggregated_value)
1031
1032
            current_datetime_utc += timedelta(minutes=config.minutes_to_count)
1033
1034
    except Exception as e:
1035
        error_string = "Error in step 21 of space_energy_input_category.worker " + str(e)
1036
        if cursor_energy_db:
1037
            cursor_energy_db.close()
1038
        if cnx_energy_db:
1039
            cnx_energy_db.close()
1040
        print(error_string)
1041
        return error_string
1042
1043
    ####################################################################################################################
1044
    # Step 22: save energy data to energy database
1045
    ####################################################################################################################
1046
    print("Step 22: save energy data to energy database")
1047
1048
    if len(aggregated_values) > 0:
1049
        try:
1050
            add_values = (" INSERT INTO tbl_space_input_category_hourly "
1051
                          "             (space_id, "
1052
                          "              energy_category_id, "
1053
                          "              start_datetime_utc, "
1054
                          "              actual_value) "
1055
                          " VALUES  ")
1056
1057
            for aggregated_value in aggregated_values:
1058
                for energy_category_id, actual_value in aggregated_value['meta_data'].items():
1059
                    add_values += " (" + str(space['id']) + ","
1060
                    add_values += " " + str(energy_category_id) + ","
1061
                    add_values += "'" + aggregated_value['start_datetime_utc'].isoformat()[0:19] + "',"
1062
                    add_values += str(actual_value) + "), "
1063
            print("add_values:" + add_values)
1064
            # trim ", " at the end of string and then execute
1065
            cursor_energy_db.execute(add_values[:-2])
1066
            cnx_energy_db.commit()
1067
1068
        except Exception as e:
1069
            error_string = "Error in step 22 of space_energy_input_category.worker " + str(e)
1070
            print(error_string)
1071
            return error_string
1072
        finally:
1073
            if cursor_energy_db:
1074
                cursor_energy_db.close()
1075
            if cnx_energy_db:
1076
                cnx_energy_db.close()
1077
    else:
1078
        if cursor_energy_db:
1079
            cursor_energy_db.close()
1080
        if cnx_energy_db:
1081
            cnx_energy_db.close()
1082