Code Duplication    Length = 117-117 lines in 7 locations

myems-api/core/energystoragecontainer.py 7 locations

@@ 4780-4896 (lines=117) @@
4777
        resp.status = falcon.HTTP_200
4778
4779
4780
class EnergyStorageContainerPCSPointCollection:
4781
    def __init__(self):
4782
        """Initializes EnergyStorageContainerPCSPointCollection"""
4783
        pass
4784
4785
    @staticmethod
4786
    def on_options(req, resp, id_, pid):
4787
        resp.status = falcon.HTTP_200
4788
4789
    @staticmethod
4790
    def on_get(req, resp, id_, pid):
4791
        if 'API-KEY' not in req.headers or \
4792
                not isinstance(req.headers['API-KEY'], str) or \
4793
                len(str.strip(req.headers['API-KEY'])) == 0:
4794
            access_control(req)
4795
        else:
4796
            api_key_control(req)
4797
        if not id_.isdigit() or int(id_) <= 0:
4798
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4799
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4800
        if not pid.isdigit() or int(pid) <= 0:
4801
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4802
                                   description='API.INVALID_PCS_ID')
4803
4804
        cnx = mysql.connector.connect(**config.myems_system_db)
4805
        cursor = cnx.cursor()
4806
4807
        cursor.execute(" SELECT name "
4808
                       " FROM tbl_energy_storage_containers_pcses "
4809
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, pid, ))
4810
        if cursor.fetchone() is None:
4811
            cursor.close()
4812
            cnx.close()
4813
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4814
                                   description='API.ENERGY_STORAGE_CONTAINER_PCS_NOT_FOUND')
4815
4816
        query = (" SELECT p.id, p.name, "
4817
                 "        ds.id, ds.name, ds.uuid, "
4818
                 "        p.address "
4819
                 " FROM tbl_points p, tbl_energy_storage_containers_pcses_points mp, tbl_data_sources ds "
4820
                 " WHERE mp.pcs_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
4821
                 " ORDER BY p.name ")
4822
        cursor.execute(query, (pid,))
4823
        rows = cursor.fetchall()
4824
4825
        result = list()
4826
        if rows is not None and len(rows) > 0:
4827
            for row in rows:
4828
                meta_result = {"id": row[0], "name": row[1],
4829
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
4830
                               "address": row[5]}
4831
                result.append(meta_result)
4832
4833
        resp.text = json.dumps(result)
4834
4835
    @staticmethod
4836
    @user_logger
4837
    def on_post(req, resp, id_, pid):
4838
        """Handles POST requests"""
4839
        admin_control(req)
4840
        try:
4841
            raw_json = req.stream.read().decode('utf-8')
4842
        except Exception as ex:
4843
            raise falcon.HTTPError(status=falcon.HTTP_400,
4844
                                   title='API.BAD_REQUEST',
4845
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4846
4847
        if not id_.isdigit() or int(id_) <= 0:
4848
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4849
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4850
        if not pid.isdigit() or int(pid) <= 0:
4851
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4852
                                   description='API.INVALID_PCS_ID')
4853
4854
        new_values = json.loads(raw_json)
4855
        cnx = mysql.connector.connect(**config.myems_system_db)
4856
        cursor = cnx.cursor()
4857
4858
        cursor.execute(" SELECT name "
4859
                       " FROM tbl_energy_storage_containers_pcses "
4860
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, pid,))
4861
        if cursor.fetchone() is None:
4862
            cursor.close()
4863
            cnx.close()
4864
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4865
                                   description='API.ENERGY_STORAGE_CONTAINER_PCS_NOT_FOUND')
4866
4867
        cursor.execute(" SELECT name, object_type "
4868
                       " FROM tbl_points "
4869
                       " WHERE id = %s ", (new_values['data']['point_id'],))
4870
        row = cursor.fetchone()
4871
        if row is None:
4872
            cursor.close()
4873
            cnx.close()
4874
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4875
                                   description='API.POINT_NOT_FOUND')
4876
4877
        query = (" SELECT id " 
4878
                 " FROM tbl_energy_storage_containers_pcses_points "
4879
                 " WHERE pcs_id = %s AND point_id = %s")
4880
        cursor.execute(query, (pid, new_values['data']['point_id'],))
4881
        if cursor.fetchone() is not None:
4882
            cursor.close()
4883
            cnx.close()
4884
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4885
                                   description='API.PCS_POINT_RELATION_EXISTS')
4886
4887
        add_row = (" INSERT INTO tbl_energy_storage_containers_pcses_points (pcs_id, point_id) "
4888
                   " VALUES (%s, %s) ")
4889
        cursor.execute(add_row, (hid, new_values['data']['point_id'],))
4890
        cnx.commit()
4891
        cursor.close()
4892
        cnx.close()
4893
4894
        resp.status = falcon.HTTP_201
4895
        resp.location = '/energystoragecontainers/' + str(id_) + '/pcses/' + str(pid) + '/points/' + \
4896
                        str(new_values['data']['point_id'])
4897
4898
4899
class EnergyStorageContainerPCSPointItem:
@@ 4206-4322 (lines=117) @@
4203
        resp.status = falcon.HTTP_200
4204
4205
4206
class EnergyStorageContainerLoadPointCollection:
4207
    def __init__(self):
4208
        """Initializes EnergyStorageContainerLoadPointCollection"""
4209
        pass
4210
4211
    @staticmethod
4212
    def on_options(req, resp, id_, lid):
4213
        resp.status = falcon.HTTP_200
4214
4215
    @staticmethod
4216
    def on_get(req, resp, id_, lid):
4217
        if 'API-KEY' not in req.headers or \
4218
                not isinstance(req.headers['API-KEY'], str) or \
4219
                len(str.strip(req.headers['API-KEY'])) == 0:
4220
            access_control(req)
4221
        else:
4222
            api_key_control(req)
4223
        if not id_.isdigit() or int(id_) <= 0:
4224
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4225
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4226
        if not lid.isdigit() or int(lid) <= 0:
4227
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4228
                                   description='API.INVALID_LOAD_ID')
4229
4230
        cnx = mysql.connector.connect(**config.myems_system_db)
4231
        cursor = cnx.cursor()
4232
4233
        cursor.execute(" SELECT name "
4234
                       " FROM tbl_energy_storage_containers_loads "
4235
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, lid, ))
4236
        if cursor.fetchone() is None:
4237
            cursor.close()
4238
            cnx.close()
4239
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4240
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NOT_FOUND')
4241
4242
        query = (" SELECT p.id, p.name, "
4243
                 "        ds.id, ds.name, ds.uuid, "
4244
                 "        p.address "
4245
                 " FROM tbl_points p, tbl_energy_storage_containers_loads_points mp, tbl_data_sources ds "
4246
                 " WHERE mp.load_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
4247
                 " ORDER BY p.name ")
4248
        cursor.execute(query, (lid,))
4249
        rows = cursor.fetchall()
4250
4251
        result = list()
4252
        if rows is not None and len(rows) > 0:
4253
            for row in rows:
4254
                meta_result = {"id": row[0], "name": row[1],
4255
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
4256
                               "address": row[5]}
4257
                result.append(meta_result)
4258
4259
        resp.text = json.dumps(result)
4260
4261
    @staticmethod
4262
    @user_logger
4263
    def on_post(req, resp, id_, hid):
4264
        """Handles POST requests"""
4265
        admin_control(req)
4266
        try:
4267
            raw_json = req.stream.read().decode('utf-8')
4268
        except Exception as ex:
4269
            raise falcon.HTTPError(status=falcon.HTTP_400,
4270
                                   title='API.BAD_REQUEST',
4271
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4272
4273
        if not id_.isdigit() or int(id_) <= 0:
4274
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4275
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4276
        if not hid.isdigit() or int(hid) <= 0:
4277
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4278
                                   description='API.INVALID_LOAD_ID')
4279
4280
        new_values = json.loads(raw_json)
4281
        cnx = mysql.connector.connect(**config.myems_system_db)
4282
        cursor = cnx.cursor()
4283
4284
        cursor.execute(" SELECT name "
4285
                       " FROM tbl_energy_storage_containers_loads "
4286
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, hid,))
4287
        if cursor.fetchone() is None:
4288
            cursor.close()
4289
            cnx.close()
4290
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4291
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NOT_FOUND')
4292
4293
        cursor.execute(" SELECT name, object_type "
4294
                       " FROM tbl_points "
4295
                       " WHERE id = %s ", (new_values['data']['point_id'],))
4296
        row = cursor.fetchone()
4297
        if row is None:
4298
            cursor.close()
4299
            cnx.close()
4300
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4301
                                   description='API.POINT_NOT_FOUND')
4302
4303
        query = (" SELECT id " 
4304
                 " FROM tbl_energy_storage_containers_loads_points "
4305
                 " WHERE load_id = %s AND point_id = %s")
4306
        cursor.execute(query, (hid, new_values['data']['point_id'],))
4307
        if cursor.fetchone() is not None:
4308
            cursor.close()
4309
            cnx.close()
4310
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4311
                                   description='API.LOAD_POINT_RELATION_EXISTS')
4312
4313
        add_row = (" INSERT INTO tbl_energy_storage_containers_loads_points (load_id, point_id) "
4314
                   " VALUES (%s, %s) ")
4315
        cursor.execute(add_row, (hid, new_values['data']['point_id'],))
4316
        cnx.commit()
4317
        cursor.close()
4318
        cnx.close()
4319
4320
        resp.status = falcon.HTTP_201
4321
        resp.location = '/energystoragecontainers/' + str(id_) + '/loads/' + str(hid) + '/points/' + \
4322
                        str(new_values['data']['point_id'])
4323
4324
4325
class EnergyStorageContainerLoadPointItem:
@@ 3582-3698 (lines=117) @@
3579
        resp.status = falcon.HTTP_200
3580
3581
3582
class EnergyStorageContainerHVACPointCollection:
3583
    def __init__(self):
3584
        """Initializes EnergyStorageContainerHVACPointCollection"""
3585
        pass
3586
3587
    @staticmethod
3588
    def on_options(req, resp, id_, hid):
3589
        resp.status = falcon.HTTP_200
3590
3591
    @staticmethod
3592
    def on_get(req, resp, id_, hid):
3593
        if 'API-KEY' not in req.headers or \
3594
                not isinstance(req.headers['API-KEY'], str) or \
3595
                len(str.strip(req.headers['API-KEY'])) == 0:
3596
            access_control(req)
3597
        else:
3598
            api_key_control(req)
3599
        if not id_.isdigit() or int(id_) <= 0:
3600
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3601
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3602
        if not hid.isdigit() or int(hid) <= 0:
3603
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3604
                                   description='API.INVALID_HVAC_ID')
3605
3606
        cnx = mysql.connector.connect(**config.myems_system_db)
3607
        cursor = cnx.cursor()
3608
3609
        cursor.execute(" SELECT name "
3610
                       " FROM tbl_energy_storage_containers_hvacs "
3611
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, hid, ))
3612
        if cursor.fetchone() is None:
3613
            cursor.close()
3614
            cnx.close()
3615
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3616
                                   description='API.ENERGY_STORAGE_CONTAINER_HVAC_NOT_FOUND')
3617
3618
        query = (" SELECT p.id, p.name, "
3619
                 "        ds.id, ds.name, ds.uuid, "
3620
                 "        p.address "
3621
                 " FROM tbl_points p, tbl_energy_storage_containers_hvacs_points mp, tbl_data_sources ds "
3622
                 " WHERE mp.hvac_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
3623
                 " ORDER BY p.name ")
3624
        cursor.execute(query, (hid,))
3625
        rows = cursor.fetchall()
3626
3627
        result = list()
3628
        if rows is not None and len(rows) > 0:
3629
            for row in rows:
3630
                meta_result = {"id": row[0], "name": row[1],
3631
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
3632
                               "address": row[5]}
3633
                result.append(meta_result)
3634
3635
        resp.text = json.dumps(result)
3636
3637
    @staticmethod
3638
    @user_logger
3639
    def on_post(req, resp, id_, hid):
3640
        """Handles POST requests"""
3641
        admin_control(req)
3642
        try:
3643
            raw_json = req.stream.read().decode('utf-8')
3644
        except Exception as ex:
3645
            raise falcon.HTTPError(status=falcon.HTTP_400,
3646
                                   title='API.BAD_REQUEST',
3647
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3648
3649
        if not id_.isdigit() or int(id_) <= 0:
3650
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3651
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3652
        if not hid.isdigit() or int(hid) <= 0:
3653
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3654
                                   description='API.INVALID_HVAC_ID')
3655
3656
        new_values = json.loads(raw_json)
3657
        cnx = mysql.connector.connect(**config.myems_system_db)
3658
        cursor = cnx.cursor()
3659
3660
        cursor.execute(" SELECT name "
3661
                       " FROM tbl_energy_storage_containers_hvacs "
3662
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, hid,))
3663
        if cursor.fetchone() is None:
3664
            cursor.close()
3665
            cnx.close()
3666
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3667
                                   description='API.ENERGY_STORAGE_CONTAINER_HVAC_NOT_FOUND')
3668
3669
        cursor.execute(" SELECT name, object_type "
3670
                       " FROM tbl_points "
3671
                       " WHERE id = %s ", (new_values['data']['point_id'],))
3672
        row = cursor.fetchone()
3673
        if row is None:
3674
            cursor.close()
3675
            cnx.close()
3676
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3677
                                   description='API.POINT_NOT_FOUND')
3678
3679
        query = (" SELECT id " 
3680
                 " FROM tbl_energy_storage_containers_hvacs_points "
3681
                 " WHERE hvac_id = %s AND point_id = %s")
3682
        cursor.execute(query, (hid, new_values['data']['point_id'],))
3683
        if cursor.fetchone() is not None:
3684
            cursor.close()
3685
            cnx.close()
3686
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
3687
                                   description='API.HVAC_POINT_RELATION_EXISTS')
3688
3689
        add_row = (" INSERT INTO tbl_energy_storage_containers_hvacs_points (hvac_id, point_id) "
3690
                   " VALUES (%s, %s) ")
3691
        cursor.execute(add_row, (hid, new_values['data']['point_id'],))
3692
        cnx.commit()
3693
        cursor.close()
3694
        cnx.close()
3695
3696
        resp.status = falcon.HTTP_201
3697
        resp.location = '/energystoragecontainers/' + str(id_) + '/hvacs/' + str(hid) + '/points/' + \
3698
                        str(new_values['data']['point_id'])
3699
3700
3701
class EnergyStorageContainerHVACPointItem:
@@ 3103-3219 (lines=117) @@
3100
        resp.status = falcon.HTTP_200
3101
3102
3103
class EnergyStorageContainerGridPointCollection:
3104
    def __init__(self):
3105
        """Initializes EnergyStorageContainerGridPointCollection"""
3106
        pass
3107
3108
    @staticmethod
3109
    def on_options(req, resp, id_, gid):
3110
        resp.status = falcon.HTTP_200
3111
3112
    @staticmethod
3113
    def on_get(req, resp, id_, gid):
3114
        if 'API-KEY' not in req.headers or \
3115
                not isinstance(req.headers['API-KEY'], str) or \
3116
                len(str.strip(req.headers['API-KEY'])) == 0:
3117
            access_control(req)
3118
        else:
3119
            api_key_control(req)
3120
        if not id_.isdigit() or int(id_) <= 0:
3121
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3122
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3123
        if not gid.isdigit() or int(gid) <= 0:
3124
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3125
                                   description='API.INVALID_GRID_ID')
3126
3127
        cnx = mysql.connector.connect(**config.myems_system_db)
3128
        cursor = cnx.cursor()
3129
3130
        cursor.execute(" SELECT name "
3131
                       " FROM tbl_energy_storage_containers_grids "
3132
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, gid, ))
3133
        if cursor.fetchone() is None:
3134
            cursor.close()
3135
            cnx.close()
3136
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3137
                                   description='API.ENERGY_STORAGE_CONTAINER_GRID_NOT_FOUND')
3138
3139
        query = (" SELECT p.id, p.name, "
3140
                 "        ds.id, ds.name, ds.uuid, "
3141
                 "        p.address "
3142
                 " FROM tbl_points p, tbl_energy_storage_containers_grids_points mp, tbl_data_sources ds "
3143
                 " WHERE mp.grid_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
3144
                 " ORDER BY p.name ")
3145
        cursor.execute(query, (gid,))
3146
        rows = cursor.fetchall()
3147
3148
        result = list()
3149
        if rows is not None and len(rows) > 0:
3150
            for row in rows:
3151
                meta_result = {"id": row[0], "name": row[1],
3152
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
3153
                               "address": row[5]}
3154
                result.append(meta_result)
3155
3156
        resp.text = json.dumps(result)
3157
3158
    @staticmethod
3159
    @user_logger
3160
    def on_post(req, resp, id_, gid):
3161
        """Handles POST requests"""
3162
        admin_control(req)
3163
        try:
3164
            raw_json = req.stream.read().decode('utf-8')
3165
        except Exception as ex:
3166
            raise falcon.HTTPError(status=falcon.HTTP_400,
3167
                                   title='API.BAD_REQUEST',
3168
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3169
3170
        if not id_.isdigit() or int(id_) <= 0:
3171
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3172
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3173
        if not gid.isdigit() or int(gid) <= 0:
3174
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3175
                                   description='API.INVALID_GRID_ID')
3176
3177
        new_values = json.loads(raw_json)
3178
        cnx = mysql.connector.connect(**config.myems_system_db)
3179
        cursor = cnx.cursor()
3180
3181
        cursor.execute(" SELECT name "
3182
                       " FROM tbl_energy_storage_containers_grids "
3183
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, gid,))
3184
        if cursor.fetchone() is None:
3185
            cursor.close()
3186
            cnx.close()
3187
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3188
                                   description='API.ENERGY_STORAGE_CONTAINER_GRID_NOT_FOUND')
3189
3190
        cursor.execute(" SELECT name, object_type "
3191
                       " FROM tbl_points "
3192
                       " WHERE id = %s ", (new_values['data']['point_id'],))
3193
        row = cursor.fetchone()
3194
        if row is None:
3195
            cursor.close()
3196
            cnx.close()
3197
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3198
                                   description='API.POINT_NOT_FOUND')
3199
3200
        query = (" SELECT id " 
3201
                 " FROM tbl_energy_storage_containers_grids_points "
3202
                 " WHERE grid_id = %s AND point_id = %s")
3203
        cursor.execute(query, (gid, new_values['data']['point_id'],))
3204
        if cursor.fetchone() is not None:
3205
            cursor.close()
3206
            cnx.close()
3207
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
3208
                                   description='API.GRID_POINT_RELATION_EXISTS')
3209
3210
        add_row = (" INSERT INTO tbl_energy_storage_containers_grids_points (grid_id, point_id) "
3211
                   " VALUES (%s, %s) ")
3212
        cursor.execute(add_row, (gid, new_values['data']['point_id'],))
3213
        cnx.commit()
3214
        cursor.close()
3215
        cnx.close()
3216
3217
        resp.status = falcon.HTTP_201
3218
        resp.location = '/energystoragecontainers/' + str(id_) + '/grids/' + str(gid) + '/points/' + \
3219
                        str(new_values['data']['point_id'])
3220
3221
3222
class EnergyStorageContainerGridPointItem:
@@ 2439-2555 (lines=117) @@
2436
        resp.status = falcon.HTTP_200
2437
2438
2439
class EnergyStorageContainerFirecontrolPointCollection:
2440
    def __init__(self):
2441
        """Initializes EnergyStorageContainerFirecontrolPointCollection"""
2442
        pass
2443
2444
    @staticmethod
2445
    def on_options(req, resp, id_, fid):
2446
        resp.status = falcon.HTTP_200
2447
2448
    @staticmethod
2449
    def on_get(req, resp, id_, fid):
2450
        if 'API-KEY' not in req.headers or \
2451
                not isinstance(req.headers['API-KEY'], str) or \
2452
                len(str.strip(req.headers['API-KEY'])) == 0:
2453
            access_control(req)
2454
        else:
2455
            api_key_control(req)
2456
        if not id_.isdigit() or int(id_) <= 0:
2457
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2458
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2459
        if not fid.isdigit() or int(fid) <= 0:
2460
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2461
                                   description='API.INVALID_FIRECONTROL_ID')
2462
2463
        cnx = mysql.connector.connect(**config.myems_system_db)
2464
        cursor = cnx.cursor()
2465
2466
        cursor.execute(" SELECT name "
2467
                       " FROM tbl_energy_storage_containers_dcdcs "
2468
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, fid, ))
2469
        if cursor.fetchone() is None:
2470
            cursor.close()
2471
            cnx.close()
2472
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2473
                                   description='API.ENERGY_STORAGE_CONTAINER_DCDC_NOT_FOUND')
2474
2475
        query = (" SELECT p.id, p.name, "
2476
                 "        ds.id, ds.name, ds.uuid, "
2477
                 "        p.address "
2478
                 " FROM tbl_points p, tbl_energy_storage_containers_firecontrols_points mp, tbl_data_sources ds "
2479
                 " WHERE mp.firecontrol_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
2480
                 " ORDER BY p.name ")
2481
        cursor.execute(query, (fid,))
2482
        rows = cursor.fetchall()
2483
2484
        result = list()
2485
        if rows is not None and len(rows) > 0:
2486
            for row in rows:
2487
                meta_result = {"id": row[0], "name": row[1],
2488
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
2489
                               "address": row[5]}
2490
                result.append(meta_result)
2491
2492
        resp.text = json.dumps(result)
2493
2494
    @staticmethod
2495
    @user_logger
2496
    def on_post(req, resp, id_, fid):
2497
        """Handles POST requests"""
2498
        admin_control(req)
2499
        try:
2500
            raw_json = req.stream.read().decode('utf-8')
2501
        except Exception as ex:
2502
            raise falcon.HTTPError(status=falcon.HTTP_400,
2503
                                   title='API.BAD_REQUEST',
2504
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2505
2506
        if not id_.isdigit() or int(id_) <= 0:
2507
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2508
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2509
        if not fid.isdigit() or int(fid) <= 0:
2510
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2511
                                   description='API.INVALID_FIRECONTROL_ID')
2512
2513
        new_values = json.loads(raw_json)
2514
        cnx = mysql.connector.connect(**config.myems_system_db)
2515
        cursor = cnx.cursor()
2516
2517
        cursor.execute(" SELECT name "
2518
                       " FROM tbl_energy_storage_containers_firecontrols "
2519
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, fid,))
2520
        if cursor.fetchone() is None:
2521
            cursor.close()
2522
            cnx.close()
2523
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2524
                                   description='API.ENERGY_STORAGE_CONTAINER_FIRECONTROL_NOT_FOUND')
2525
2526
        cursor.execute(" SELECT name, object_type "
2527
                       " FROM tbl_points "
2528
                       " WHERE id = %s ", (new_values['data']['point_id'],))
2529
        row = cursor.fetchone()
2530
        if row is None:
2531
            cursor.close()
2532
            cnx.close()
2533
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2534
                                   description='API.POINT_NOT_FOUND')
2535
2536
        query = (" SELECT id " 
2537
                 " FROM tbl_energy_storage_containers_firecontrols_points "
2538
                 " WHERE firecontrol_id = %s AND point_id = %s")
2539
        cursor.execute(query, (fid, new_values['data']['point_id'],))
2540
        if cursor.fetchone() is not None:
2541
            cursor.close()
2542
            cnx.close()
2543
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2544
                                   description='API.FIRECONTROL_POINT_RELATION_EXISTS')
2545
2546
        add_row = (" INSERT INTO tbl_energy_storage_containers_firecontrols_points (firecontrol_id, point_id) "
2547
                   " VALUES (%s, %s) ")
2548
        cursor.execute(add_row, (fid, new_values['data']['point_id'],))
2549
        cnx.commit()
2550
        cursor.close()
2551
        cnx.close()
2552
2553
        resp.status = falcon.HTTP_201
2554
        resp.location = '/energystoragecontainers/' + str(id_) + '/firecontrols/' + str(fid) + '/points/' + \
2555
                        str(new_values['data']['point_id'])
2556
2557
2558
class EnergyStorageContainerFirecontrolPointItem:
@@ 1960-2076 (lines=117) @@
1957
        resp.status = falcon.HTTP_200
1958
1959
1960
class EnergyStorageContainerDCDCPointCollection:
1961
    def __init__(self):
1962
        """Initializes EnergyStorageContainerDCDCPointCollection"""
1963
        pass
1964
1965
    @staticmethod
1966
    def on_options(req, resp, id_, did):
1967
        resp.status = falcon.HTTP_200
1968
1969
    @staticmethod
1970
    def on_get(req, resp, id_, did):
1971
        if 'API-KEY' not in req.headers or \
1972
                not isinstance(req.headers['API-KEY'], str) or \
1973
                len(str.strip(req.headers['API-KEY'])) == 0:
1974
            access_control(req)
1975
        else:
1976
            api_key_control(req)
1977
        if not id_.isdigit() or int(id_) <= 0:
1978
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1979
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
1980
        if not did.isdigit() or int(did) <= 0:
1981
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1982
                                   description='API.INVALID_DCDC_ID')
1983
1984
        cnx = mysql.connector.connect(**config.myems_system_db)
1985
        cursor = cnx.cursor()
1986
1987
        cursor.execute(" SELECT name "
1988
                       " FROM tbl_energy_storage_containers_dcdcs "
1989
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, did, ))
1990
        if cursor.fetchone() is None:
1991
            cursor.close()
1992
            cnx.close()
1993
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1994
                                   description='API.ENERGY_STORAGE_CONTAINER_DCDC_NOT_FOUND')
1995
1996
        query = (" SELECT p.id, p.name, "
1997
                 "        ds.id, ds.name, ds.uuid, "
1998
                 "        p.address "
1999
                 " FROM tbl_points p, tbl_energy_storage_containers_dcdcs_points mp, tbl_data_sources ds "
2000
                 " WHERE mp.dcdc_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
2001
                 " ORDER BY p.name ")
2002
        cursor.execute(query, (did,))
2003
        rows = cursor.fetchall()
2004
2005
        result = list()
2006
        if rows is not None and len(rows) > 0:
2007
            for row in rows:
2008
                meta_result = {"id": row[0], "name": row[1],
2009
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
2010
                               "address": row[5]}
2011
                result.append(meta_result)
2012
2013
        resp.text = json.dumps(result)
2014
2015
    @staticmethod
2016
    @user_logger
2017
    def on_post(req, resp, id_, did):
2018
        """Handles POST requests"""
2019
        admin_control(req)
2020
        try:
2021
            raw_json = req.stream.read().decode('utf-8')
2022
        except Exception as ex:
2023
            raise falcon.HTTPError(status=falcon.HTTP_400,
2024
                                   title='API.BAD_REQUEST',
2025
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2026
2027
        if not id_.isdigit() or int(id_) <= 0:
2028
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2029
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2030
        if not did.isdigit() or int(did) <= 0:
2031
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2032
                                   description='API.INVALID_DCDC_ID')
2033
2034
        new_values = json.loads(raw_json)
2035
        cnx = mysql.connector.connect(**config.myems_system_db)
2036
        cursor = cnx.cursor()
2037
2038
        cursor.execute(" SELECT name "
2039
                       " FROM tbl_energy_storage_containers_dcdcs "
2040
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, did,))
2041
        if cursor.fetchone() is None:
2042
            cursor.close()
2043
            cnx.close()
2044
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2045
                                   description='API.ENERGY_STORAGE_CONTAINER_DCDC_NOT_FOUND')
2046
2047
        cursor.execute(" SELECT name, object_type "
2048
                       " FROM tbl_points "
2049
                       " WHERE id = %s ", (new_values['data']['point_id'],))
2050
        row = cursor.fetchone()
2051
        if row is None:
2052
            cursor.close()
2053
            cnx.close()
2054
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2055
                                   description='API.POINT_NOT_FOUND')
2056
2057
        query = (" SELECT id " 
2058
                 " FROM tbl_energy_storage_containers_dcdcs_points "
2059
                 " WHERE dcdc_id = %s AND point_id = %s")
2060
        cursor.execute(query, (did, new_values['data']['point_id'],))
2061
        if cursor.fetchone() is not None:
2062
            cursor.close()
2063
            cnx.close()
2064
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2065
                                   description='API.DCDC_POINT_RELATION_EXISTS')
2066
2067
        add_row = (" INSERT INTO tbl_energy_storage_containers_dcdcs_points (dcdc_id, point_id) "
2068
                   " VALUES (%s, %s) ")
2069
        cursor.execute(add_row, (did, new_values['data']['point_id'],))
2070
        cnx.commit()
2071
        cursor.close()
2072
        cnx.close()
2073
2074
        resp.status = falcon.HTTP_201
2075
        resp.location = '/energystoragecontainers/' + str(id_) + '/dcdcs/' + str(did) + '/points/' + \
2076
                        str(new_values['data']['point_id'])
2077
2078
2079
class EnergyStorageContainerDCDCPointItem:
@@ 1305-1421 (lines=117) @@
1302
        resp.status = falcon.HTTP_200
1303
1304
1305
class EnergyStorageContainerBatteryPointCollection:
1306
    def __init__(self):
1307
        """Initializes EnergyStorageContainerBatteryPointCollection"""
1308
        pass
1309
1310
    @staticmethod
1311
    def on_options(req, resp, id_, bid):
1312
        resp.status = falcon.HTTP_200
1313
1314
    @staticmethod
1315
    def on_get(req, resp, id_, bid):
1316
        if 'API-KEY' not in req.headers or \
1317
                not isinstance(req.headers['API-KEY'], str) or \
1318
                len(str.strip(req.headers['API-KEY'])) == 0:
1319
            access_control(req)
1320
        else:
1321
            api_key_control(req)
1322
        if not id_.isdigit() or int(id_) <= 0:
1323
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1324
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
1325
        if not bid.isdigit() or int(bid) <= 0:
1326
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1327
                                   description='API.INVALID_BMS_ID')
1328
1329
        cnx = mysql.connector.connect(**config.myems_system_db)
1330
        cursor = cnx.cursor()
1331
1332
        cursor.execute(" SELECT name "
1333
                       " FROM tbl_energy_storage_containers_batteries "
1334
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, bid, ))
1335
        if cursor.fetchone() is None:
1336
            cursor.close()
1337
            cnx.close()
1338
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1339
                                   description='API.ENERGY_STORAGE_CONTAINER_BMS_NOT_FOUND')
1340
1341
        query = (" SELECT p.id, p.name, "
1342
                 "        ds.id, ds.name, ds.uuid, "
1343
                 "        p.address "
1344
                 " FROM tbl_points p, tbl_energy_storage_containers_bmses_points mp, tbl_data_sources ds "
1345
                 " WHERE mp.bms_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
1346
                 " ORDER BY p.name ")
1347
        cursor.execute(query, (bid,))
1348
        rows = cursor.fetchall()
1349
1350
        result = list()
1351
        if rows is not None and len(rows) > 0:
1352
            for row in rows:
1353
                meta_result = {"id": row[0], "name": row[1],
1354
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
1355
                               "address": row[5]}
1356
                result.append(meta_result)
1357
1358
        resp.text = json.dumps(result)
1359
1360
    @staticmethod
1361
    @user_logger
1362
    def on_post(req, resp, id_, bid):
1363
        """Handles POST requests"""
1364
        admin_control(req)
1365
        try:
1366
            raw_json = req.stream.read().decode('utf-8')
1367
        except Exception as ex:
1368
            raise falcon.HTTPError(status=falcon.HTTP_400,
1369
                                   title='API.BAD_REQUEST',
1370
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1371
1372
        if not id_.isdigit() or int(id_) <= 0:
1373
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1374
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
1375
        if not bid.isdigit() or int(bid) <= 0:
1376
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1377
                                   description='API.INVALID_BMS_ID')
1378
1379
        new_values = json.loads(raw_json)
1380
        cnx = mysql.connector.connect(**config.myems_system_db)
1381
        cursor = cnx.cursor()
1382
1383
        cursor.execute(" SELECT name "
1384
                       " FROM tbl_energy_storage_containers_batteries "
1385
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, bid,))
1386
        if cursor.fetchone() is None:
1387
            cursor.close()
1388
            cnx.close()
1389
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1390
                                   description='API.ENERGY_STORAGE_CONTAINER_BMS_NOT_FOUND')
1391
1392
        cursor.execute(" SELECT name, object_type "
1393
                       " FROM tbl_points "
1394
                       " WHERE id = %s ", (new_values['data']['point_id'],))
1395
        row = cursor.fetchone()
1396
        if row is None:
1397
            cursor.close()
1398
            cnx.close()
1399
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1400
                                   description='API.POINT_NOT_FOUND')
1401
1402
        query = (" SELECT id " 
1403
                 " FROM tbl_energy_storage_containers_bmses_points "
1404
                 " WHERE bms_id = %s AND point_id = %s")
1405
        cursor.execute(query, (bid, new_values['data']['point_id'],))
1406
        if cursor.fetchone() is not None:
1407
            cursor.close()
1408
            cnx.close()
1409
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1410
                                   description='API.BMS_POINT_RELATION_EXISTS')
1411
1412
        add_row = (" INSERT INTO tbl_energy_storage_containers_bmses_points (bms_id, point_id) "
1413
                   " VALUES (%s, %s) ")
1414
        cursor.execute(add_row, (bid, new_values['data']['point_id'],))
1415
        cnx.commit()
1416
        cursor.close()
1417
        cnx.close()
1418
1419
        resp.status = falcon.HTTP_201
1420
        resp.location = '/energystoragecontainers/' + str(id_) + '/batteries/' + str(bid) + '/points/' + \
1421
                        str(new_values['data']['point_id'])
1422
1423
1424
class EnergyStorageContainerBatteryPointItem: