Code Duplication    Length = 117-119 lines in 8 locations

myems-api/core/energystoragecontainer.py 8 locations

@@ 3335-3453 (lines=119) @@
3332
        resp.status = falcon.HTTP_200
3333
3334
3335
class EnergyStorageContainerHVACPointCollection:
3336
    def __init__(self):
3337
        """Initializes EnergyStorageContainerHVACPointCollection"""
3338
        pass
3339
3340
    @staticmethod
3341
    def on_options(req, resp, id_, hid):
3342
        _=req
3343
        resp.status = falcon.HTTP_200
3344
        _=id_
3345
    @staticmethod
3346
    def on_get(req, resp, id_, hid):
3347
        if 'API-KEY' not in req.headers or \
3348
                not isinstance(req.headers['API-KEY'], str) or \
3349
                len(str.strip(req.headers['API-KEY'])) == 0:
3350
            access_control(req)
3351
        else:
3352
            api_key_control(req)
3353
        if not id_.isdigit() or int(id_) <= 0:
3354
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3355
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3356
        if not hid.isdigit() or int(hid) <= 0:
3357
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3358
                                   description='API.INVALID_HVAC_ID')
3359
3360
        cnx = mysql.connector.connect(**config.myems_system_db)
3361
        cursor = cnx.cursor()
3362
3363
        cursor.execute(" SELECT name "
3364
                       " FROM tbl_energy_storage_containers_hvacs "
3365
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, hid, ))
3366
        if cursor.fetchone() is None:
3367
            cursor.close()
3368
            cnx.close()
3369
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3370
                                   description='API.ENERGY_STORAGE_CONTAINER_HVAC_NOT_FOUND')
3371
3372
        query = (" SELECT p.id, p.name, "
3373
                 "        ds.id, ds.name, ds.uuid, "
3374
                 "        p.address "
3375
                 " FROM tbl_points p, tbl_energy_storage_containers_hvacs_points mp, tbl_data_sources ds "
3376
                 " WHERE mp.hvac_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
3377
                 " ORDER BY p.name ")
3378
        cursor.execute(query, (hid,))
3379
        rows = cursor.fetchall()
3380
3381
        result = list()
3382
        if rows is not None and len(rows) > 0:
3383
            for row in rows:
3384
                meta_result = {"id": row[0], "name": row[1],
3385
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
3386
                               "address": row[5]}
3387
                result.append(meta_result)
3388
3389
        resp.text = json.dumps(result)
3390
3391
    @staticmethod
3392
    @user_logger
3393
    def on_post(req, resp, id_, hid):
3394
        """Handles POST requests"""
3395
        admin_control(req)
3396
        try:
3397
            raw_json = req.stream.read().decode('utf-8')
3398
        except Exception as ex:
3399
            print(str(ex))
3400
            raise falcon.HTTPError(status=falcon.HTTP_400,
3401
                                   title='API.BAD_REQUEST',
3402
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3403
3404
        if not id_.isdigit() or int(id_) <= 0:
3405
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3406
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3407
        if not hid.isdigit() or int(hid) <= 0:
3408
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3409
                                   description='API.INVALID_HVAC_ID')
3410
3411
        new_values = json.loads(raw_json)
3412
        cnx = mysql.connector.connect(**config.myems_system_db)
3413
        cursor = cnx.cursor()
3414
3415
        cursor.execute(" SELECT name "
3416
                       " FROM tbl_energy_storage_containers_hvacs "
3417
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, hid,))
3418
        if cursor.fetchone() is None:
3419
            cursor.close()
3420
            cnx.close()
3421
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3422
                                   description='API.ENERGY_STORAGE_CONTAINER_HVAC_NOT_FOUND')
3423
3424
        cursor.execute(" SELECT name, object_type "
3425
                       " FROM tbl_points "
3426
                       " WHERE id = %s ", (new_values['data']['point_id'],))
3427
        row = cursor.fetchone()
3428
        if row is None:
3429
            cursor.close()
3430
            cnx.close()
3431
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3432
                                   description='API.POINT_NOT_FOUND')
3433
3434
        query = (" SELECT id " 
3435
                 " FROM tbl_energy_storage_containers_hvacs_points "
3436
                 " WHERE hvac_id = %s AND point_id = %s")
3437
        cursor.execute(query, (hid, new_values['data']['point_id'],))
3438
        if cursor.fetchone() is not None:
3439
            cursor.close()
3440
            cnx.close()
3441
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
3442
                                   description='API.HVAC_POINT_RELATION_EXISTS')
3443
3444
        add_row = (" INSERT INTO tbl_energy_storage_containers_hvacs_points (hvac_id, point_id) "
3445
                   " VALUES (%s, %s) ")
3446
        cursor.execute(add_row, (hid, new_values['data']['point_id'],))
3447
        cnx.commit()
3448
        cursor.close()
3449
        cnx.close()
3450
3451
        resp.status = falcon.HTTP_201
3452
        resp.location = '/energystoragecontainers/' + str(id_) + '/hvacs/' + str(hid) + '/points/' + \
3453
                        str(new_values['data']['point_id'])
3454
3455
3456
class EnergyStorageContainerHVACPointItem:
@@ 2849-2967 (lines=119) @@
2846
        resp.status = falcon.HTTP_200
2847
2848
2849
class EnergyStorageContainerGridPointCollection:
2850
    def __init__(self):
2851
        """Initializes EnergyStorageContainerGridPointCollection"""
2852
        pass
2853
2854
    @staticmethod
2855
    def on_options(req, resp, id_, gid):
2856
        _=req
2857
        resp.status = falcon.HTTP_200
2858
        _=id_
2859
    @staticmethod
2860
    def on_get(req, resp, id_, gid):
2861
        if 'API-KEY' not in req.headers or \
2862
                not isinstance(req.headers['API-KEY'], str) or \
2863
                len(str.strip(req.headers['API-KEY'])) == 0:
2864
            access_control(req)
2865
        else:
2866
            api_key_control(req)
2867
        if not id_.isdigit() or int(id_) <= 0:
2868
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2869
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2870
        if not gid.isdigit() or int(gid) <= 0:
2871
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2872
                                   description='API.INVALID_GRID_ID')
2873
2874
        cnx = mysql.connector.connect(**config.myems_system_db)
2875
        cursor = cnx.cursor()
2876
2877
        cursor.execute(" SELECT name "
2878
                       " FROM tbl_energy_storage_containers_grids "
2879
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, gid, ))
2880
        if cursor.fetchone() is None:
2881
            cursor.close()
2882
            cnx.close()
2883
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2884
                                   description='API.ENERGY_STORAGE_CONTAINER_GRID_NOT_FOUND')
2885
2886
        query = (" SELECT p.id, p.name, "
2887
                 "        ds.id, ds.name, ds.uuid, "
2888
                 "        p.address "
2889
                 " FROM tbl_points p, tbl_energy_storage_containers_grids_points mp, tbl_data_sources ds "
2890
                 " WHERE mp.grid_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
2891
                 " ORDER BY p.name ")
2892
        cursor.execute(query, (gid,))
2893
        rows = cursor.fetchall()
2894
2895
        result = list()
2896
        if rows is not None and len(rows) > 0:
2897
            for row in rows:
2898
                meta_result = {"id": row[0], "name": row[1],
2899
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
2900
                               "address": row[5]}
2901
                result.append(meta_result)
2902
2903
        resp.text = json.dumps(result)
2904
2905
    @staticmethod
2906
    @user_logger
2907
    def on_post(req, resp, id_, gid):
2908
        """Handles POST requests"""
2909
        admin_control(req)
2910
        try:
2911
            raw_json = req.stream.read().decode('utf-8')
2912
        except Exception as ex:
2913
            print(str(ex))
2914
            raise falcon.HTTPError(status=falcon.HTTP_400,
2915
                                   title='API.BAD_REQUEST',
2916
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2917
2918
        if not id_.isdigit() or int(id_) <= 0:
2919
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2920
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2921
        if not gid.isdigit() or int(gid) <= 0:
2922
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2923
                                   description='API.INVALID_GRID_ID')
2924
2925
        new_values = json.loads(raw_json)
2926
        cnx = mysql.connector.connect(**config.myems_system_db)
2927
        cursor = cnx.cursor()
2928
2929
        cursor.execute(" SELECT name "
2930
                       " FROM tbl_energy_storage_containers_grids "
2931
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, gid,))
2932
        if cursor.fetchone() is None:
2933
            cursor.close()
2934
            cnx.close()
2935
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2936
                                   description='API.ENERGY_STORAGE_CONTAINER_GRID_NOT_FOUND')
2937
2938
        cursor.execute(" SELECT name, object_type "
2939
                       " FROM tbl_points "
2940
                       " WHERE id = %s ", (new_values['data']['point_id'],))
2941
        row = cursor.fetchone()
2942
        if row is None:
2943
            cursor.close()
2944
            cnx.close()
2945
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2946
                                   description='API.POINT_NOT_FOUND')
2947
2948
        query = (" SELECT id " 
2949
                 " FROM tbl_energy_storage_containers_grids_points "
2950
                 " WHERE grid_id = %s AND point_id = %s")
2951
        cursor.execute(query, (gid, new_values['data']['point_id'],))
2952
        if cursor.fetchone() is not None:
2953
            cursor.close()
2954
            cnx.close()
2955
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2956
                                   description='API.GRID_POINT_RELATION_EXISTS')
2957
2958
        add_row = (" INSERT INTO tbl_energy_storage_containers_grids_points (grid_id, point_id) "
2959
                   " VALUES (%s, %s) ")
2960
        cursor.execute(add_row, (gid, new_values['data']['point_id'],))
2961
        cnx.commit()
2962
        cursor.close()
2963
        cnx.close()
2964
2965
        resp.status = falcon.HTTP_201
2966
        resp.location = '/energystoragecontainers/' + str(id_) + '/grids/' + str(gid) + '/points/' + \
2967
                        str(new_values['data']['point_id'])
2968
2969
2970
class EnergyStorageContainerGridPointItem:
@@ 2178-2296 (lines=119) @@
2175
        resp.status = falcon.HTTP_200
2176
2177
2178
class EnergyStorageContainerFirecontrolPointCollection:
2179
    def __init__(self):
2180
        """Initializes EnergyStorageContainerFirecontrolPointCollection"""
2181
        pass
2182
2183
    @staticmethod
2184
    def on_options(req, resp, id_, fid):
2185
        _=req
2186
        resp.status = falcon.HTTP_200
2187
        _=id_
2188
    @staticmethod
2189
    def on_get(req, resp, id_, fid):
2190
        if 'API-KEY' not in req.headers or \
2191
                not isinstance(req.headers['API-KEY'], str) or \
2192
                len(str.strip(req.headers['API-KEY'])) == 0:
2193
            access_control(req)
2194
        else:
2195
            api_key_control(req)
2196
        if not id_.isdigit() or int(id_) <= 0:
2197
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2198
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2199
        if not fid.isdigit() or int(fid) <= 0:
2200
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2201
                                   description='API.INVALID_FIRECONTROL_ID')
2202
2203
        cnx = mysql.connector.connect(**config.myems_system_db)
2204
        cursor = cnx.cursor()
2205
2206
        cursor.execute(" SELECT name "
2207
                       " FROM tbl_energy_storage_containers_firecontrols "
2208
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, fid, ))
2209
        if cursor.fetchone() is None:
2210
            cursor.close()
2211
            cnx.close()
2212
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2213
                                   description='API.ENERGY_STORAGE_CONTAINER_FIRECONTROL_NOT_FOUND')
2214
2215
        query = (" SELECT p.id, p.name, "
2216
                 "        ds.id, ds.name, ds.uuid, "
2217
                 "        p.address "
2218
                 " FROM tbl_points p, tbl_energy_storage_containers_firecontrols_points mp, tbl_data_sources ds "
2219
                 " WHERE mp.firecontrol_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
2220
                 " ORDER BY p.name ")
2221
        cursor.execute(query, (fid,))
2222
        rows = cursor.fetchall()
2223
2224
        result = list()
2225
        if rows is not None and len(rows) > 0:
2226
            for row in rows:
2227
                meta_result = {"id": row[0], "name": row[1],
2228
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
2229
                               "address": row[5]}
2230
                result.append(meta_result)
2231
2232
        resp.text = json.dumps(result)
2233
2234
    @staticmethod
2235
    @user_logger
2236
    def on_post(req, resp, id_, fid):
2237
        """Handles POST requests"""
2238
        admin_control(req)
2239
        try:
2240
            raw_json = req.stream.read().decode('utf-8')
2241
        except Exception as ex:
2242
            print(str(ex))
2243
            raise falcon.HTTPError(status=falcon.HTTP_400,
2244
                                   title='API.BAD_REQUEST',
2245
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2246
2247
        if not id_.isdigit() or int(id_) <= 0:
2248
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2249
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2250
        if not fid.isdigit() or int(fid) <= 0:
2251
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2252
                                   description='API.INVALID_FIRECONTROL_ID')
2253
2254
        new_values = json.loads(raw_json)
2255
        cnx = mysql.connector.connect(**config.myems_system_db)
2256
        cursor = cnx.cursor()
2257
2258
        cursor.execute(" SELECT name "
2259
                       " FROM tbl_energy_storage_containers_firecontrols "
2260
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, fid,))
2261
        if cursor.fetchone() is None:
2262
            cursor.close()
2263
            cnx.close()
2264
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2265
                                   description='API.ENERGY_STORAGE_CONTAINER_FIRECONTROL_NOT_FOUND')
2266
2267
        cursor.execute(" SELECT name, object_type "
2268
                       " FROM tbl_points "
2269
                       " WHERE id = %s ", (new_values['data']['point_id'],))
2270
        row = cursor.fetchone()
2271
        if row is None:
2272
            cursor.close()
2273
            cnx.close()
2274
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2275
                                   description='API.POINT_NOT_FOUND')
2276
2277
        query = (" SELECT id " 
2278
                 " FROM tbl_energy_storage_containers_firecontrols_points "
2279
                 " WHERE firecontrol_id = %s AND point_id = %s")
2280
        cursor.execute(query, (fid, new_values['data']['point_id'],))
2281
        if cursor.fetchone() is not None:
2282
            cursor.close()
2283
            cnx.close()
2284
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2285
                                   description='API.FIRECONTROL_POINT_RELATION_EXISTS')
2286
2287
        add_row = (" INSERT INTO tbl_energy_storage_containers_firecontrols_points (firecontrol_id, point_id) "
2288
                   " VALUES (%s, %s) ")
2289
        cursor.execute(add_row, (fid, new_values['data']['point_id'],))
2290
        cnx.commit()
2291
        cursor.close()
2292
        cnx.close()
2293
2294
        resp.status = falcon.HTTP_201
2295
        resp.location = '/energystoragecontainers/' + str(id_) + '/firecontrols/' + str(fid) + '/points/' + \
2296
                        str(new_values['data']['point_id'])
2297
2298
2299
class EnergyStorageContainerFirecontrolPointItem:
@@ 1036-1154 (lines=119) @@
1033
        resp.status = falcon.HTTP_200
1034
1035
1036
class EnergyStorageContainerBatteryPointCollection:
1037
    def __init__(self):
1038
        """Initializes EnergyStorageContainerBatteryPointCollection"""
1039
        pass
1040
1041
    @staticmethod
1042
    def on_options(req, resp, id_, bid):
1043
        _=req
1044
        resp.status = falcon.HTTP_200
1045
        _=id_
1046
    @staticmethod
1047
    def on_get(req, resp, id_, bid):
1048
        if 'API-KEY' not in req.headers or \
1049
                not isinstance(req.headers['API-KEY'], str) or \
1050
                len(str.strip(req.headers['API-KEY'])) == 0:
1051
            access_control(req)
1052
        else:
1053
            api_key_control(req)
1054
        if not id_.isdigit() or int(id_) <= 0:
1055
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1056
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
1057
        if not bid.isdigit() or int(bid) <= 0:
1058
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1059
                                   description='API.INVALID_BMS_ID')
1060
1061
        cnx = mysql.connector.connect(**config.myems_system_db)
1062
        cursor = cnx.cursor()
1063
1064
        cursor.execute(" SELECT name "
1065
                       " FROM tbl_energy_storage_containers_batteries "
1066
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, bid, ))
1067
        if cursor.fetchone() is None:
1068
            cursor.close()
1069
            cnx.close()
1070
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1071
                                   description='API.ENERGY_STORAGE_CONTAINER_BMS_NOT_FOUND')
1072
1073
        query = (" SELECT p.id, p.name, "
1074
                 "        ds.id, ds.name, ds.uuid, "
1075
                 "        p.address "
1076
                 " FROM tbl_points p, tbl_energy_storage_containers_bmses_points mp, tbl_data_sources ds "
1077
                 " WHERE mp.bms_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
1078
                 " ORDER BY p.name ")
1079
        cursor.execute(query, (bid,))
1080
        rows = cursor.fetchall()
1081
1082
        result = list()
1083
        if rows is not None and len(rows) > 0:
1084
            for row in rows:
1085
                meta_result = {"id": row[0], "name": row[1],
1086
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
1087
                               "address": row[5]}
1088
                result.append(meta_result)
1089
1090
        resp.text = json.dumps(result)
1091
1092
    @staticmethod
1093
    @user_logger
1094
    def on_post(req, resp, id_, bid):
1095
        """Handles POST requests"""
1096
        admin_control(req)
1097
        try:
1098
            raw_json = req.stream.read().decode('utf-8')
1099
        except Exception as ex:
1100
            print(str(ex))
1101
            raise falcon.HTTPError(status=falcon.HTTP_400,
1102
                                   title='API.BAD_REQUEST',
1103
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1104
1105
        if not id_.isdigit() or int(id_) <= 0:
1106
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1107
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
1108
        if not bid.isdigit() or int(bid) <= 0:
1109
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1110
                                   description='API.INVALID_BMS_ID')
1111
1112
        new_values = json.loads(raw_json)
1113
        cnx = mysql.connector.connect(**config.myems_system_db)
1114
        cursor = cnx.cursor()
1115
1116
        cursor.execute(" SELECT name "
1117
                       " FROM tbl_energy_storage_containers_batteries "
1118
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, bid,))
1119
        if cursor.fetchone() is None:
1120
            cursor.close()
1121
            cnx.close()
1122
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1123
                                   description='API.ENERGY_STORAGE_CONTAINER_BMS_NOT_FOUND')
1124
1125
        cursor.execute(" SELECT name, object_type "
1126
                       " FROM tbl_points "
1127
                       " WHERE id = %s ", (new_values['data']['point_id'],))
1128
        row = cursor.fetchone()
1129
        if row is None:
1130
            cursor.close()
1131
            cnx.close()
1132
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1133
                                   description='API.POINT_NOT_FOUND')
1134
1135
        query = (" SELECT id " 
1136
                 " FROM tbl_energy_storage_containers_bmses_points "
1137
                 " WHERE bms_id = %s AND point_id = %s")
1138
        cursor.execute(query, (bid, new_values['data']['point_id'],))
1139
        if cursor.fetchone() is not None:
1140
            cursor.close()
1141
            cnx.close()
1142
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1143
                                   description='API.BMS_POINT_RELATION_EXISTS')
1144
1145
        add_row = (" INSERT INTO tbl_energy_storage_containers_bmses_points (bms_id, point_id) "
1146
                   " VALUES (%s, %s) ")
1147
        cursor.execute(add_row, (bid, new_values['data']['point_id'],))
1148
        cnx.commit()
1149
        cursor.close()
1150
        cnx.close()
1151
1152
        resp.status = falcon.HTTP_201
1153
        resp.location = '/energystoragecontainers/' + str(id_) + '/batteries/' + str(bid) + '/points/' + \
1154
                        str(new_values['data']['point_id'])
1155
1156
1157
class EnergyStorageContainerBatteryPointItem:
@@ 1693-1810 (lines=118) @@
1690
        resp.status = falcon.HTTP_200
1691
1692
1693
class EnergyStorageContainerDCDCPointCollection:
1694
    def __init__(self):
1695
        """Initializes EnergyStorageContainerDCDCPointCollection"""
1696
        pass
1697
1698
    @staticmethod
1699
    def on_options(req, resp, id_, did):
1700
        resp.status = falcon.HTTP_200
1701
1702
    @staticmethod
1703
    def on_get(req, resp, id_, did):
1704
        if 'API-KEY' not in req.headers or \
1705
                not isinstance(req.headers['API-KEY'], str) or \
1706
                len(str.strip(req.headers['API-KEY'])) == 0:
1707
            access_control(req)
1708
        else:
1709
            api_key_control(req)
1710
        if not id_.isdigit() or int(id_) <= 0:
1711
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1712
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
1713
        if not did.isdigit() or int(did) <= 0:
1714
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1715
                                   description='API.INVALID_DCDC_ID')
1716
1717
        cnx = mysql.connector.connect(**config.myems_system_db)
1718
        cursor = cnx.cursor()
1719
1720
        cursor.execute(" SELECT name "
1721
                       " FROM tbl_energy_storage_containers_dcdcs "
1722
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, did, ))
1723
        if cursor.fetchone() is None:
1724
            cursor.close()
1725
            cnx.close()
1726
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1727
                                   description='API.ENERGY_STORAGE_CONTAINER_DCDC_NOT_FOUND')
1728
1729
        query = (" SELECT p.id, p.name, "
1730
                 "        ds.id, ds.name, ds.uuid, "
1731
                 "        p.address "
1732
                 " FROM tbl_points p, tbl_energy_storage_containers_dcdcs_points mp, tbl_data_sources ds "
1733
                 " WHERE mp.dcdc_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
1734
                 " ORDER BY p.name ")
1735
        cursor.execute(query, (did,))
1736
        rows = cursor.fetchall()
1737
1738
        result = list()
1739
        if rows is not None and len(rows) > 0:
1740
            for row in rows:
1741
                meta_result = {"id": row[0], "name": row[1],
1742
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
1743
                               "address": row[5]}
1744
                result.append(meta_result)
1745
1746
        resp.text = json.dumps(result)
1747
1748
    @staticmethod
1749
    @user_logger
1750
    def on_post(req, resp, id_, did):
1751
        """Handles POST requests"""
1752
        admin_control(req)
1753
        try:
1754
            raw_json = req.stream.read().decode('utf-8')
1755
        except Exception as ex:
1756
            print(str(ex))
1757
            raise falcon.HTTPError(status=falcon.HTTP_400,
1758
                                   title='API.BAD_REQUEST',
1759
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1760
1761
        if not id_.isdigit() or int(id_) <= 0:
1762
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1763
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
1764
        if not did.isdigit() or int(did) <= 0:
1765
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1766
                                   description='API.INVALID_DCDC_ID')
1767
1768
        new_values = json.loads(raw_json)
1769
        cnx = mysql.connector.connect(**config.myems_system_db)
1770
        cursor = cnx.cursor()
1771
1772
        cursor.execute(" SELECT name "
1773
                       " FROM tbl_energy_storage_containers_dcdcs "
1774
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, did,))
1775
        if cursor.fetchone() is None:
1776
            cursor.close()
1777
            cnx.close()
1778
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1779
                                   description='API.ENERGY_STORAGE_CONTAINER_DCDC_NOT_FOUND')
1780
1781
        cursor.execute(" SELECT name, object_type "
1782
                       " FROM tbl_points "
1783
                       " WHERE id = %s ", (new_values['data']['point_id'],))
1784
        row = cursor.fetchone()
1785
        if row is None:
1786
            cursor.close()
1787
            cnx.close()
1788
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1789
                                   description='API.POINT_NOT_FOUND')
1790
1791
        query = (" SELECT id " 
1792
                 " FROM tbl_energy_storage_containers_dcdcs_points "
1793
                 " WHERE dcdc_id = %s AND point_id = %s")
1794
        cursor.execute(query, (did, new_values['data']['point_id'],))
1795
        if cursor.fetchone() is not None:
1796
            cursor.close()
1797
            cnx.close()
1798
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1799
                                   description='API.DCDC_POINT_RELATION_EXISTS')
1800
1801
        add_row = (" INSERT INTO tbl_energy_storage_containers_dcdcs_points (dcdc_id, point_id) "
1802
                   " VALUES (%s, %s) ")
1803
        cursor.execute(add_row, (did, new_values['data']['point_id'],))
1804
        cnx.commit()
1805
        cursor.close()
1806
        cnx.close()
1807
1808
        resp.status = falcon.HTTP_201
1809
        resp.location = '/energystoragecontainers/' + str(id_) + '/dcdcs/' + str(did) + '/points/' + \
1810
                        str(new_values['data']['point_id'])
1811
1812
1813
class EnergyStorageContainerDCDCPointItem:
@@ 5309-5425 (lines=117) @@
5306
        resp.status = falcon.HTTP_200
5307
5308
5309
class EnergyStorageContainerSTSPointCollection:
5310
    def __init__(self):
5311
        """Initializes EnergyStorageContainerSTSPointCollection"""
5312
        pass
5313
5314
    @staticmethod
5315
    def on_options(req, resp, id_, fid):
5316
        resp.status = falcon.HTTP_200
5317
5318
    @staticmethod
5319
    def on_get(req, resp, id_, fid):
5320
        if 'API-KEY' not in req.headers or \
5321
                not isinstance(req.headers['API-KEY'], str) or \
5322
                len(str.strip(req.headers['API-KEY'])) == 0:
5323
            access_control(req)
5324
        else:
5325
            api_key_control(req)
5326
        if not id_.isdigit() or int(id_) <= 0:
5327
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5328
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
5329
        if not fid.isdigit() or int(fid) <= 0:
5330
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5331
                                   description='API.INVALID_STS_ID')
5332
5333
        cnx = mysql.connector.connect(**config.myems_system_db)
5334
        cursor = cnx.cursor()
5335
5336
        cursor.execute(" SELECT name "
5337
                       " FROM tbl_energy_storage_containers_stses "
5338
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, fid, ))
5339
        if cursor.fetchone() is None:
5340
            cursor.close()
5341
            cnx.close()
5342
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5343
                                   description='API.ENERGY_STORAGE_CONTAINER_STS_NOT_FOUND')
5344
5345
        query = (" SELECT p.id, p.name, "
5346
                 "        ds.id, ds.name, ds.uuid, "
5347
                 "        p.address "
5348
                 " FROM tbl_points p, tbl_energy_storage_containers_stses_points mp, tbl_data_sources ds "
5349
                 " WHERE mp.sts_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
5350
                 " ORDER BY p.name ")
5351
        cursor.execute(query, (fid,))
5352
        rows = cursor.fetchall()
5353
5354
        result = list()
5355
        if rows is not None and len(rows) > 0:
5356
            for row in rows:
5357
                meta_result = {"id": row[0], "name": row[1],
5358
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
5359
                               "address": row[5]}
5360
                result.append(meta_result)
5361
5362
        resp.text = json.dumps(result)
5363
5364
    @staticmethod
5365
    @user_logger
5366
    def on_post(req, resp, id_, fid):
5367
        """Handles POST requests"""
5368
        admin_control(req)
5369
        try:
5370
            raw_json = req.stream.read().decode('utf-8')
5371
        except Exception as ex:
5372
            raise falcon.HTTPError(status=falcon.HTTP_400,
5373
                                   title='API.BAD_REQUEST',
5374
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5375
5376
        if not id_.isdigit() or int(id_) <= 0:
5377
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5378
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
5379
        if not fid.isdigit() or int(fid) <= 0:
5380
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5381
                                   description='API.INVALID_STS_ID')
5382
5383
        new_values = json.loads(raw_json)
5384
        cnx = mysql.connector.connect(**config.myems_system_db)
5385
        cursor = cnx.cursor()
5386
5387
        cursor.execute(" SELECT name "
5388
                       " FROM tbl_energy_storage_containers_stses "
5389
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, fid,))
5390
        if cursor.fetchone() is None:
5391
            cursor.close()
5392
            cnx.close()
5393
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5394
                                   description='API.ENERGY_STORAGE_CONTAINER_STS_NOT_FOUND')
5395
5396
        cursor.execute(" SELECT name, object_type "
5397
                       " FROM tbl_points "
5398
                       " WHERE id = %s ", (new_values['data']['point_id'],))
5399
        row = cursor.fetchone()
5400
        if row is None:
5401
            cursor.close()
5402
            cnx.close()
5403
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5404
                                   description='API.POINT_NOT_FOUND')
5405
5406
        query = (" SELECT id " 
5407
                 " FROM tbl_energy_storage_containers_stses_points "
5408
                 " WHERE sts_id = %s AND point_id = %s")
5409
        cursor.execute(query, (fid, new_values['data']['point_id'],))
5410
        if cursor.fetchone() is not None:
5411
            cursor.close()
5412
            cnx.close()
5413
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5414
                                   description='API.STS_POINT_RELATION_EXISTS')
5415
5416
        add_row = (" INSERT INTO tbl_energy_storage_containers_stses_points (sts_id, point_id) "
5417
                   " VALUES (%s, %s) ")
5418
        cursor.execute(add_row, (fid, new_values['data']['point_id'],))
5419
        cnx.commit()
5420
        cursor.close()
5421
        cnx.close()
5422
5423
        resp.status = falcon.HTTP_201
5424
        resp.location = '/energystoragecontainers/' + str(id_) + '/stses/' + str(fid) + '/points/' + \
5425
                        str(new_values['data']['point_id'])
5426
5427
5428
class EnergyStorageContainerSTSPointItem:
@@ 4535-4651 (lines=117) @@
4532
        resp.status = falcon.HTTP_200
4533
4534
4535
class EnergyStorageContainerPCSPointCollection:
4536
    def __init__(self):
4537
        """Initializes EnergyStorageContainerPCSPointCollection"""
4538
        pass
4539
4540
    @staticmethod
4541
    def on_options(req, resp, id_, pcsid):
4542
        resp.status = falcon.HTTP_200
4543
4544
    @staticmethod
4545
    def on_get(req, resp, id_, pcsid):
4546
        if 'API-KEY' not in req.headers or \
4547
                not isinstance(req.headers['API-KEY'], str) or \
4548
                len(str.strip(req.headers['API-KEY'])) == 0:
4549
            access_control(req)
4550
        else:
4551
            api_key_control(req)
4552
        if not id_.isdigit() or int(id_) <= 0:
4553
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4554
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4555
        if not pcsid.isdigit() or int(pcsid) <= 0:
4556
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4557
                                   description='API.INVALID_PCS_ID')
4558
4559
        cnx = mysql.connector.connect(**config.myems_system_db)
4560
        cursor = cnx.cursor()
4561
4562
        cursor.execute(" SELECT name "
4563
                       " FROM tbl_energy_storage_containers_power_conversion_systems "
4564
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, pcsid, ))
4565
        if cursor.fetchone() is None:
4566
            cursor.close()
4567
            cnx.close()
4568
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4569
                                   description='API.ENERGY_STORAGE_CONTAINER_PCS_NOT_FOUND')
4570
4571
        query = (" SELECT p.id, p.name, "
4572
                 "        ds.id, ds.name, ds.uuid, "
4573
                 "        p.address "
4574
                 " FROM tbl_points p, tbl_energy_storage_containers_pcses_points mp, tbl_data_sources ds "
4575
                 " WHERE mp.pcs_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
4576
                 " ORDER BY p.name ")
4577
        cursor.execute(query, (pcsid,))
4578
        rows = cursor.fetchall()
4579
4580
        result = list()
4581
        if rows is not None and len(rows) > 0:
4582
            for row in rows:
4583
                meta_result = {"id": row[0], "name": row[1],
4584
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
4585
                               "address": row[5]}
4586
                result.append(meta_result)
4587
4588
        resp.text = json.dumps(result)
4589
4590
    @staticmethod
4591
    @user_logger
4592
    def on_post(req, resp, id_, pcsid):
4593
        """Handles POST requests"""
4594
        admin_control(req)
4595
        try:
4596
            raw_json = req.stream.read().decode('utf-8')
4597
        except Exception as ex:
4598
            raise falcon.HTTPError(status=falcon.HTTP_400,
4599
                                   title='API.BAD_REQUEST',
4600
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4601
4602
        if not id_.isdigit() or int(id_) <= 0:
4603
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4604
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4605
        if not pcsid.isdigit() or int(pcsid) <= 0:
4606
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4607
                                   description='API.INVALID_PCS_ID')
4608
4609
        new_values = json.loads(raw_json)
4610
        cnx = mysql.connector.connect(**config.myems_system_db)
4611
        cursor = cnx.cursor()
4612
4613
        cursor.execute(" SELECT name "
4614
                       " FROM tbl_energy_storage_containers_power_conversion_systems "
4615
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, pcsid,))
4616
        if cursor.fetchone() is None:
4617
            cursor.close()
4618
            cnx.close()
4619
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4620
                                   description='API.ENERGY_STORAGE_CONTAINER_PCS_NOT_FOUND')
4621
4622
        cursor.execute(" SELECT name, object_type "
4623
                       " FROM tbl_points "
4624
                       " WHERE id = %s ", (new_values['data']['point_id'],))
4625
        row = cursor.fetchone()
4626
        if row is None:
4627
            cursor.close()
4628
            cnx.close()
4629
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4630
                                   description='API.POINT_NOT_FOUND')
4631
4632
        query = (" SELECT id " 
4633
                 " FROM tbl_energy_storage_containers_pcses_points "
4634
                 " WHERE pcs_id = %s AND point_id = %s")
4635
        cursor.execute(query, (pcsid, new_values['data']['point_id'],))
4636
        if cursor.fetchone() is not None:
4637
            cursor.close()
4638
            cnx.close()
4639
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4640
                                   description='API.PCS_POINT_RELATION_EXISTS')
4641
4642
        add_row = (" INSERT INTO tbl_energy_storage_containers_pcses_points (pcs_id, point_id) "
4643
                   " VALUES (%s, %s) ")
4644
        cursor.execute(add_row, (pcsid, new_values['data']['point_id'],))
4645
        cnx.commit()
4646
        cursor.close()
4647
        cnx.close()
4648
4649
        resp.status = falcon.HTTP_201
4650
        resp.location = '/energystoragecontainers/' + str(id_) + '/pcses/' + str(pcsid) + '/points/' + \
4651
                        str(new_values['data']['point_id'])
4652
4653
4654
class EnergyStorageContainerPCSPointItem:
@@ 3961-4077 (lines=117) @@
3958
        resp.status = falcon.HTTP_200
3959
3960
3961
class EnergyStorageContainerLoadPointCollection:
3962
    def __init__(self):
3963
        """Initializes EnergyStorageContainerLoadPointCollection"""
3964
        pass
3965
3966
    @staticmethod
3967
    def on_options(req, resp, id_, lid):
3968
        resp.status = falcon.HTTP_200
3969
3970
    @staticmethod
3971
    def on_get(req, resp, id_, lid):
3972
        if 'API-KEY' not in req.headers or \
3973
                not isinstance(req.headers['API-KEY'], str) or \
3974
                len(str.strip(req.headers['API-KEY'])) == 0:
3975
            access_control(req)
3976
        else:
3977
            api_key_control(req)
3978
        if not id_.isdigit() or int(id_) <= 0:
3979
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3980
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3981
        if not lid.isdigit() or int(lid) <= 0:
3982
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3983
                                   description='API.INVALID_LOAD_ID')
3984
3985
        cnx = mysql.connector.connect(**config.myems_system_db)
3986
        cursor = cnx.cursor()
3987
3988
        cursor.execute(" SELECT name "
3989
                       " FROM tbl_energy_storage_containers_loads "
3990
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, lid, ))
3991
        if cursor.fetchone() is None:
3992
            cursor.close()
3993
            cnx.close()
3994
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3995
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NOT_FOUND')
3996
3997
        query = (" SELECT p.id, p.name, "
3998
                 "        ds.id, ds.name, ds.uuid, "
3999
                 "        p.address "
4000
                 " FROM tbl_points p, tbl_energy_storage_containers_loads_points mp, tbl_data_sources ds "
4001
                 " WHERE mp.load_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
4002
                 " ORDER BY p.name ")
4003
        cursor.execute(query, (lid,))
4004
        rows = cursor.fetchall()
4005
4006
        result = list()
4007
        if rows is not None and len(rows) > 0:
4008
            for row in rows:
4009
                meta_result = {"id": row[0], "name": row[1],
4010
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
4011
                               "address": row[5]}
4012
                result.append(meta_result)
4013
4014
        resp.text = json.dumps(result)
4015
4016
    @staticmethod
4017
    @user_logger
4018
    def on_post(req, resp, id_, lid):
4019
        """Handles POST requests"""
4020
        admin_control(req)
4021
        try:
4022
            raw_json = req.stream.read().decode('utf-8')
4023
        except Exception as ex:
4024
            raise falcon.HTTPError(status=falcon.HTTP_400,
4025
                                   title='API.BAD_REQUEST',
4026
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4027
4028
        if not id_.isdigit() or int(id_) <= 0:
4029
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4030
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4031
        if not lid.isdigit() or int(lid) <= 0:
4032
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4033
                                   description='API.INVALID_LOAD_ID')
4034
4035
        new_values = json.loads(raw_json)
4036
        cnx = mysql.connector.connect(**config.myems_system_db)
4037
        cursor = cnx.cursor()
4038
4039
        cursor.execute(" SELECT name "
4040
                       " FROM tbl_energy_storage_containers_loads "
4041
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, lid,))
4042
        if cursor.fetchone() is None:
4043
            cursor.close()
4044
            cnx.close()
4045
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4046
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NOT_FOUND')
4047
4048
        cursor.execute(" SELECT name, object_type "
4049
                       " FROM tbl_points "
4050
                       " WHERE id = %s ", (new_values['data']['point_id'],))
4051
        row = cursor.fetchone()
4052
        if row is None:
4053
            cursor.close()
4054
            cnx.close()
4055
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4056
                                   description='API.POINT_NOT_FOUND')
4057
4058
        query = (" SELECT id " 
4059
                 " FROM tbl_energy_storage_containers_loads_points "
4060
                 " WHERE load_id = %s AND point_id = %s")
4061
        cursor.execute(query, (lid, new_values['data']['point_id'],))
4062
        if cursor.fetchone() is not None:
4063
            cursor.close()
4064
            cnx.close()
4065
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4066
                                   description='API.LOAD_POINT_RELATION_EXISTS')
4067
4068
        add_row = (" INSERT INTO tbl_energy_storage_containers_loads_points (load_id, point_id) "
4069
                   " VALUES (%s, %s) ")
4070
        cursor.execute(add_row, (lid, new_values['data']['point_id'],))
4071
        cnx.commit()
4072
        cursor.close()
4073
        cnx.close()
4074
4075
        resp.status = falcon.HTTP_201
4076
        resp.location = '/energystoragecontainers/' + str(id_) + '/loads/' + str(lid) + '/points/' + \
4077
                        str(new_values['data']['point_id'])
4078
4079
4080
class EnergyStorageContainerLoadPointItem: