Code Duplication    Length = 119-120 lines in 9 locations

myems-api/core/energystoragecontainer.py 8 locations

@@ 5653-5772 (lines=120) @@
5650
        resp.status = falcon.HTTP_200
5651
5652
5653
class EnergyStorageContainerSTSPointCollection:
5654
    def __init__(self):
5655
        """Initializes EnergyStorageContainerSTSPointCollection"""
5656
        pass
5657
5658
    @staticmethod
5659
    def on_options(req, resp, id_, fid):
5660
        _ = req
5661
        resp.status = falcon.HTTP_200
5662
        _ = id_
5663
5664
    @staticmethod
5665
    def on_get(req, resp, id_, fid):
5666
        if 'API-KEY' not in req.headers or \
5667
                not isinstance(req.headers['API-KEY'], str) or \
5668
                len(str.strip(req.headers['API-KEY'])) == 0:
5669
            access_control(req)
5670
        else:
5671
            api_key_control(req)
5672
        if not id_.isdigit() or int(id_) <= 0:
5673
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5674
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
5675
        if not fid.isdigit() or int(fid) <= 0:
5676
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5677
                                   description='API.INVALID_STS_ID')
5678
5679
        cnx = mysql.connector.connect(**config.myems_system_db)
5680
        cursor = cnx.cursor()
5681
5682
        cursor.execute(" SELECT name "
5683
                       " FROM tbl_energy_storage_containers_stses "
5684
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, fid, ))
5685
        if cursor.fetchone() is None:
5686
            cursor.close()
5687
            cnx.close()
5688
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5689
                                   description='API.ENERGY_STORAGE_CONTAINER_STS_NOT_FOUND')
5690
5691
        query = (" SELECT p.id, p.name, "
5692
                 "        ds.id, ds.name, ds.uuid, "
5693
                 "        p.address "
5694
                 " FROM tbl_points p, tbl_energy_storage_containers_stses_points mp, tbl_data_sources ds "
5695
                 " WHERE mp.sts_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
5696
                 " ORDER BY p.name ")
5697
        cursor.execute(query, (fid,))
5698
        rows = cursor.fetchall()
5699
5700
        result = list()
5701
        if rows is not None and len(rows) > 0:
5702
            for row in rows:
5703
                meta_result = {"id": row[0], "name": row[1],
5704
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
5705
                               "address": row[5]}
5706
                result.append(meta_result)
5707
5708
        resp.text = json.dumps(result)
5709
5710
    @staticmethod
5711
    @user_logger
5712
    def on_post(req, resp, id_, fid):
5713
        """Handles POST requests"""
5714
        admin_control(req)
5715
        try:
5716
            raw_json = req.stream.read().decode('utf-8')
5717
        except Exception as ex:
5718
            print(str(ex))
5719
            raise falcon.HTTPError(status=falcon.HTTP_400,
5720
                                   title='API.BAD_REQUEST',
5721
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5722
5723
        if not id_.isdigit() or int(id_) <= 0:
5724
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5725
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
5726
        if not fid.isdigit() or int(fid) <= 0:
5727
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5728
                                   description='API.INVALID_STS_ID')
5729
5730
        new_values = json.loads(raw_json)
5731
        cnx = mysql.connector.connect(**config.myems_system_db)
5732
        cursor = cnx.cursor()
5733
5734
        cursor.execute(" SELECT name "
5735
                       " FROM tbl_energy_storage_containers_stses "
5736
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, fid,))
5737
        if cursor.fetchone() is None:
5738
            cursor.close()
5739
            cnx.close()
5740
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5741
                                   description='API.ENERGY_STORAGE_CONTAINER_STS_NOT_FOUND')
5742
5743
        cursor.execute(" SELECT name, object_type "
5744
                       " FROM tbl_points "
5745
                       " WHERE id = %s ", (new_values['data']['point_id'],))
5746
        row = cursor.fetchone()
5747
        if row is None:
5748
            cursor.close()
5749
            cnx.close()
5750
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5751
                                   description='API.POINT_NOT_FOUND')
5752
5753
        query = (" SELECT id " 
5754
                 " FROM tbl_energy_storage_containers_stses_points "
5755
                 " WHERE sts_id = %s AND point_id = %s")
5756
        cursor.execute(query, (fid, new_values['data']['point_id'],))
5757
        if cursor.fetchone() is not None:
5758
            cursor.close()
5759
            cnx.close()
5760
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5761
                                   description='API.STS_POINT_RELATION_EXISTS')
5762
5763
        add_row = (" INSERT INTO tbl_energy_storage_containers_stses_points (sts_id, point_id) "
5764
                   " VALUES (%s, %s) ")
5765
        cursor.execute(add_row, (fid, new_values['data']['point_id'],))
5766
        cnx.commit()
5767
        cursor.close()
5768
        cnx.close()
5769
5770
        resp.status = falcon.HTTP_201
5771
        resp.location = '/energystoragecontainers/' + str(id_) + '/stses/' + str(fid) + '/points/' + \
5772
                        str(new_values['data']['point_id'])
5773
5774
5775
class EnergyStorageContainerSTSPointItem:
@@ 4862-4981 (lines=120) @@
4859
        resp.status = falcon.HTTP_200
4860
4861
4862
class EnergyStorageContainerPCSPointCollection:
4863
    def __init__(self):
4864
        """Initializes EnergyStorageContainerPCSPointCollection"""
4865
        pass
4866
4867
    @staticmethod
4868
    def on_options(req, resp, id_, pcsid):
4869
        _ = req
4870
        resp.status = falcon.HTTP_200
4871
        _ = id_
4872
4873
    @staticmethod
4874
    def on_get(req, resp, id_, pcsid):
4875
        if 'API-KEY' not in req.headers or \
4876
                not isinstance(req.headers['API-KEY'], str) or \
4877
                len(str.strip(req.headers['API-KEY'])) == 0:
4878
            access_control(req)
4879
        else:
4880
            api_key_control(req)
4881
        if not id_.isdigit() or int(id_) <= 0:
4882
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4883
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4884
        if not pcsid.isdigit() or int(pcsid) <= 0:
4885
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4886
                                   description='API.INVALID_PCS_ID')
4887
4888
        cnx = mysql.connector.connect(**config.myems_system_db)
4889
        cursor = cnx.cursor()
4890
4891
        cursor.execute(" SELECT name "
4892
                       " FROM tbl_energy_storage_containers_power_conversion_systems "
4893
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, pcsid, ))
4894
        if cursor.fetchone() is None:
4895
            cursor.close()
4896
            cnx.close()
4897
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4898
                                   description='API.ENERGY_STORAGE_CONTAINER_PCS_NOT_FOUND')
4899
4900
        query = (" SELECT p.id, p.name, "
4901
                 "        ds.id, ds.name, ds.uuid, "
4902
                 "        p.address "
4903
                 " FROM tbl_points p, tbl_energy_storage_containers_pcses_points mp, tbl_data_sources ds "
4904
                 " WHERE mp.pcs_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
4905
                 " ORDER BY p.name ")
4906
        cursor.execute(query, (pcsid,))
4907
        rows = cursor.fetchall()
4908
4909
        result = list()
4910
        if rows is not None and len(rows) > 0:
4911
            for row in rows:
4912
                meta_result = {"id": row[0], "name": row[1],
4913
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
4914
                               "address": row[5]}
4915
                result.append(meta_result)
4916
4917
        resp.text = json.dumps(result)
4918
4919
    @staticmethod
4920
    @user_logger
4921
    def on_post(req, resp, id_, pcsid):
4922
        """Handles POST requests"""
4923
        admin_control(req)
4924
        try:
4925
            raw_json = req.stream.read().decode('utf-8')
4926
        except Exception as ex:
4927
            print(str(ex))
4928
            raise falcon.HTTPError(status=falcon.HTTP_400,
4929
                                   title='API.BAD_REQUEST',
4930
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4931
4932
        if not id_.isdigit() or int(id_) <= 0:
4933
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4934
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4935
        if not pcsid.isdigit() or int(pcsid) <= 0:
4936
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4937
                                   description='API.INVALID_PCS_ID')
4938
4939
        new_values = json.loads(raw_json)
4940
        cnx = mysql.connector.connect(**config.myems_system_db)
4941
        cursor = cnx.cursor()
4942
4943
        cursor.execute(" SELECT name "
4944
                       " FROM tbl_energy_storage_containers_power_conversion_systems "
4945
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, pcsid,))
4946
        if cursor.fetchone() is None:
4947
            cursor.close()
4948
            cnx.close()
4949
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4950
                                   description='API.ENERGY_STORAGE_CONTAINER_PCS_NOT_FOUND')
4951
4952
        cursor.execute(" SELECT name, object_type "
4953
                       " FROM tbl_points "
4954
                       " WHERE id = %s ", (new_values['data']['point_id'],))
4955
        row = cursor.fetchone()
4956
        if row is None:
4957
            cursor.close()
4958
            cnx.close()
4959
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4960
                                   description='API.POINT_NOT_FOUND')
4961
4962
        query = (" SELECT id " 
4963
                 " FROM tbl_energy_storage_containers_pcses_points "
4964
                 " WHERE pcs_id = %s AND point_id = %s")
4965
        cursor.execute(query, (pcsid, new_values['data']['point_id'],))
4966
        if cursor.fetchone() is not None:
4967
            cursor.close()
4968
            cnx.close()
4969
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4970
                                   description='API.PCS_POINT_RELATION_EXISTS')
4971
4972
        add_row = (" INSERT INTO tbl_energy_storage_containers_pcses_points (pcs_id, point_id) "
4973
                   " VALUES (%s, %s) ")
4974
        cursor.execute(add_row, (pcsid, new_values['data']['point_id'],))
4975
        cnx.commit()
4976
        cursor.close()
4977
        cnx.close()
4978
4979
        resp.status = falcon.HTTP_201
4980
        resp.location = '/energystoragecontainers/' + str(id_) + '/pcses/' + str(pcsid) + '/points/' + \
4981
                        str(new_values['data']['point_id'])
4982
4983
4984
class EnergyStorageContainerPCSPointItem:
@@ 4277-4396 (lines=120) @@
4274
        resp.status = falcon.HTTP_200
4275
4276
4277
class EnergyStorageContainerLoadPointCollection:
4278
    def __init__(self):
4279
        """Initializes EnergyStorageContainerLoadPointCollection"""
4280
        pass
4281
4282
    @staticmethod
4283
    def on_options(req, resp, id_, lid):
4284
        _ = req
4285
        resp.status = falcon.HTTP_200
4286
        _ = id_
4287
4288
    @staticmethod
4289
    def on_get(req, resp, id_, lid):
4290
        if 'API-KEY' not in req.headers or \
4291
                not isinstance(req.headers['API-KEY'], str) or \
4292
                len(str.strip(req.headers['API-KEY'])) == 0:
4293
            access_control(req)
4294
        else:
4295
            api_key_control(req)
4296
        if not id_.isdigit() or int(id_) <= 0:
4297
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4298
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4299
        if not lid.isdigit() or int(lid) <= 0:
4300
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4301
                                   description='API.INVALID_LOAD_ID')
4302
4303
        cnx = mysql.connector.connect(**config.myems_system_db)
4304
        cursor = cnx.cursor()
4305
4306
        cursor.execute(" SELECT name "
4307
                       " FROM tbl_energy_storage_containers_loads "
4308
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, lid, ))
4309
        if cursor.fetchone() is None:
4310
            cursor.close()
4311
            cnx.close()
4312
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4313
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NOT_FOUND')
4314
4315
        query = (" SELECT p.id, p.name, "
4316
                 "        ds.id, ds.name, ds.uuid, "
4317
                 "        p.address "
4318
                 " FROM tbl_points p, tbl_energy_storage_containers_loads_points mp, tbl_data_sources ds "
4319
                 " WHERE mp.load_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
4320
                 " ORDER BY p.name ")
4321
        cursor.execute(query, (lid,))
4322
        rows = cursor.fetchall()
4323
4324
        result = list()
4325
        if rows is not None and len(rows) > 0:
4326
            for row in rows:
4327
                meta_result = {"id": row[0], "name": row[1],
4328
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
4329
                               "address": row[5]}
4330
                result.append(meta_result)
4331
4332
        resp.text = json.dumps(result)
4333
4334
    @staticmethod
4335
    @user_logger
4336
    def on_post(req, resp, id_, lid):
4337
        """Handles POST requests"""
4338
        admin_control(req)
4339
        try:
4340
            raw_json = req.stream.read().decode('utf-8')
4341
        except Exception as ex:
4342
            print(str(ex))
4343
            raise falcon.HTTPError(status=falcon.HTTP_400,
4344
                                   title='API.BAD_REQUEST',
4345
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4346
4347
        if not id_.isdigit() or int(id_) <= 0:
4348
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4349
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
4350
        if not lid.isdigit() or int(lid) <= 0:
4351
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4352
                                   description='API.INVALID_LOAD_ID')
4353
4354
        new_values = json.loads(raw_json)
4355
        cnx = mysql.connector.connect(**config.myems_system_db)
4356
        cursor = cnx.cursor()
4357
4358
        cursor.execute(" SELECT name "
4359
                       " FROM tbl_energy_storage_containers_loads "
4360
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, lid,))
4361
        if cursor.fetchone() is None:
4362
            cursor.close()
4363
            cnx.close()
4364
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4365
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NOT_FOUND')
4366
4367
        cursor.execute(" SELECT name, object_type "
4368
                       " FROM tbl_points "
4369
                       " WHERE id = %s ", (new_values['data']['point_id'],))
4370
        row = cursor.fetchone()
4371
        if row is None:
4372
            cursor.close()
4373
            cnx.close()
4374
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4375
                                   description='API.POINT_NOT_FOUND')
4376
4377
        query = (" SELECT id " 
4378
                 " FROM tbl_energy_storage_containers_loads_points "
4379
                 " WHERE load_id = %s AND point_id = %s")
4380
        cursor.execute(query, (lid, new_values['data']['point_id'],))
4381
        if cursor.fetchone() is not None:
4382
            cursor.close()
4383
            cnx.close()
4384
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
4385
                                   description='API.LOAD_POINT_RELATION_EXISTS')
4386
4387
        add_row = (" INSERT INTO tbl_energy_storage_containers_loads_points (load_id, point_id) "
4388
                   " VALUES (%s, %s) ")
4389
        cursor.execute(add_row, (lid, new_values['data']['point_id'],))
4390
        cnx.commit()
4391
        cursor.close()
4392
        cnx.close()
4393
4394
        resp.status = falcon.HTTP_201
4395
        resp.location = '/energystoragecontainers/' + str(id_) + '/loads/' + str(lid) + '/points/' + \
4396
                        str(new_values['data']['point_id'])
4397
4398
4399
class EnergyStorageContainerLoadPointItem:
@@ 3642-3761 (lines=120) @@
3639
        resp.status = falcon.HTTP_200
3640
3641
3642
class EnergyStorageContainerHVACPointCollection:
3643
    def __init__(self):
3644
        """Initializes EnergyStorageContainerHVACPointCollection"""
3645
        pass
3646
3647
    @staticmethod
3648
    def on_options(req, resp, id_, hid):
3649
        _ = req
3650
        resp.status = falcon.HTTP_200
3651
        _ = id_
3652
3653
    @staticmethod
3654
    def on_get(req, resp, id_, hid):
3655
        if 'API-KEY' not in req.headers or \
3656
                not isinstance(req.headers['API-KEY'], str) or \
3657
                len(str.strip(req.headers['API-KEY'])) == 0:
3658
            access_control(req)
3659
        else:
3660
            api_key_control(req)
3661
        if not id_.isdigit() or int(id_) <= 0:
3662
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3663
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3664
        if not hid.isdigit() or int(hid) <= 0:
3665
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3666
                                   description='API.INVALID_HVAC_ID')
3667
3668
        cnx = mysql.connector.connect(**config.myems_system_db)
3669
        cursor = cnx.cursor()
3670
3671
        cursor.execute(" SELECT name "
3672
                       " FROM tbl_energy_storage_containers_hvacs "
3673
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, hid, ))
3674
        if cursor.fetchone() is None:
3675
            cursor.close()
3676
            cnx.close()
3677
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3678
                                   description='API.ENERGY_STORAGE_CONTAINER_HVAC_NOT_FOUND')
3679
3680
        query = (" SELECT p.id, p.name, "
3681
                 "        ds.id, ds.name, ds.uuid, "
3682
                 "        p.address "
3683
                 " FROM tbl_points p, tbl_energy_storage_containers_hvacs_points mp, tbl_data_sources ds "
3684
                 " WHERE mp.hvac_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
3685
                 " ORDER BY p.name ")
3686
        cursor.execute(query, (hid,))
3687
        rows = cursor.fetchall()
3688
3689
        result = list()
3690
        if rows is not None and len(rows) > 0:
3691
            for row in rows:
3692
                meta_result = {"id": row[0], "name": row[1],
3693
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
3694
                               "address": row[5]}
3695
                result.append(meta_result)
3696
3697
        resp.text = json.dumps(result)
3698
3699
    @staticmethod
3700
    @user_logger
3701
    def on_post(req, resp, id_, hid):
3702
        """Handles POST requests"""
3703
        admin_control(req)
3704
        try:
3705
            raw_json = req.stream.read().decode('utf-8')
3706
        except Exception as ex:
3707
            print(str(ex))
3708
            raise falcon.HTTPError(status=falcon.HTTP_400,
3709
                                   title='API.BAD_REQUEST',
3710
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3711
3712
        if not id_.isdigit() or int(id_) <= 0:
3713
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3714
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3715
        if not hid.isdigit() or int(hid) <= 0:
3716
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3717
                                   description='API.INVALID_HVAC_ID')
3718
3719
        new_values = json.loads(raw_json)
3720
        cnx = mysql.connector.connect(**config.myems_system_db)
3721
        cursor = cnx.cursor()
3722
3723
        cursor.execute(" SELECT name "
3724
                       " FROM tbl_energy_storage_containers_hvacs "
3725
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, hid,))
3726
        if cursor.fetchone() is None:
3727
            cursor.close()
3728
            cnx.close()
3729
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3730
                                   description='API.ENERGY_STORAGE_CONTAINER_HVAC_NOT_FOUND')
3731
3732
        cursor.execute(" SELECT name, object_type "
3733
                       " FROM tbl_points "
3734
                       " WHERE id = %s ", (new_values['data']['point_id'],))
3735
        row = cursor.fetchone()
3736
        if row is None:
3737
            cursor.close()
3738
            cnx.close()
3739
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3740
                                   description='API.POINT_NOT_FOUND')
3741
3742
        query = (" SELECT id " 
3743
                 " FROM tbl_energy_storage_containers_hvacs_points "
3744
                 " WHERE hvac_id = %s AND point_id = %s")
3745
        cursor.execute(query, (hid, new_values['data']['point_id'],))
3746
        if cursor.fetchone() is not None:
3747
            cursor.close()
3748
            cnx.close()
3749
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
3750
                                   description='API.HVAC_POINT_RELATION_EXISTS')
3751
3752
        add_row = (" INSERT INTO tbl_energy_storage_containers_hvacs_points (hvac_id, point_id) "
3753
                   " VALUES (%s, %s) ")
3754
        cursor.execute(add_row, (hid, new_values['data']['point_id'],))
3755
        cnx.commit()
3756
        cursor.close()
3757
        cnx.close()
3758
3759
        resp.status = falcon.HTTP_201
3760
        resp.location = '/energystoragecontainers/' + str(id_) + '/hvacs/' + str(hid) + '/points/' + \
3761
                        str(new_values['data']['point_id'])
3762
3763
3764
class EnergyStorageContainerHVACPointItem:
@@ 3152-3271 (lines=120) @@
3149
        resp.status = falcon.HTTP_200
3150
3151
3152
class EnergyStorageContainerGridPointCollection:
3153
    def __init__(self):
3154
        """Initializes EnergyStorageContainerGridPointCollection"""
3155
        pass
3156
3157
    @staticmethod
3158
    def on_options(req, resp, id_, gid):
3159
        _ = req
3160
        resp.status = falcon.HTTP_200
3161
        _ = id_
3162
3163
    @staticmethod
3164
    def on_get(req, resp, id_, gid):
3165
        if 'API-KEY' not in req.headers or \
3166
                not isinstance(req.headers['API-KEY'], str) or \
3167
                len(str.strip(req.headers['API-KEY'])) == 0:
3168
            access_control(req)
3169
        else:
3170
            api_key_control(req)
3171
        if not id_.isdigit() or int(id_) <= 0:
3172
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3173
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3174
        if not gid.isdigit() or int(gid) <= 0:
3175
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3176
                                   description='API.INVALID_GRID_ID')
3177
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
        query = (" SELECT p.id, p.name, "
3191
                 "        ds.id, ds.name, ds.uuid, "
3192
                 "        p.address "
3193
                 " FROM tbl_points p, tbl_energy_storage_containers_grids_points mp, tbl_data_sources ds "
3194
                 " WHERE mp.grid_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
3195
                 " ORDER BY p.name ")
3196
        cursor.execute(query, (gid,))
3197
        rows = cursor.fetchall()
3198
3199
        result = list()
3200
        if rows is not None and len(rows) > 0:
3201
            for row in rows:
3202
                meta_result = {"id": row[0], "name": row[1],
3203
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
3204
                               "address": row[5]}
3205
                result.append(meta_result)
3206
3207
        resp.text = json.dumps(result)
3208
3209
    @staticmethod
3210
    @user_logger
3211
    def on_post(req, resp, id_, gid):
3212
        """Handles POST requests"""
3213
        admin_control(req)
3214
        try:
3215
            raw_json = req.stream.read().decode('utf-8')
3216
        except Exception as ex:
3217
            print(str(ex))
3218
            raise falcon.HTTPError(status=falcon.HTTP_400,
3219
                                   title='API.BAD_REQUEST',
3220
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3221
3222
        if not id_.isdigit() or int(id_) <= 0:
3223
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3224
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3225
        if not gid.isdigit() or int(gid) <= 0:
3226
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3227
                                   description='API.INVALID_GRID_ID')
3228
3229
        new_values = json.loads(raw_json)
3230
        cnx = mysql.connector.connect(**config.myems_system_db)
3231
        cursor = cnx.cursor()
3232
3233
        cursor.execute(" SELECT name "
3234
                       " FROM tbl_energy_storage_containers_grids "
3235
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, gid,))
3236
        if cursor.fetchone() is None:
3237
            cursor.close()
3238
            cnx.close()
3239
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3240
                                   description='API.ENERGY_STORAGE_CONTAINER_GRID_NOT_FOUND')
3241
3242
        cursor.execute(" SELECT name, object_type "
3243
                       " FROM tbl_points "
3244
                       " WHERE id = %s ", (new_values['data']['point_id'],))
3245
        row = cursor.fetchone()
3246
        if row is None:
3247
            cursor.close()
3248
            cnx.close()
3249
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3250
                                   description='API.POINT_NOT_FOUND')
3251
3252
        query = (" SELECT id " 
3253
                 " FROM tbl_energy_storage_containers_grids_points "
3254
                 " WHERE grid_id = %s AND point_id = %s")
3255
        cursor.execute(query, (gid, new_values['data']['point_id'],))
3256
        if cursor.fetchone() is not None:
3257
            cursor.close()
3258
            cnx.close()
3259
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
3260
                                   description='API.GRID_POINT_RELATION_EXISTS')
3261
3262
        add_row = (" INSERT INTO tbl_energy_storage_containers_grids_points (grid_id, point_id) "
3263
                   " VALUES (%s, %s) ")
3264
        cursor.execute(add_row, (gid, new_values['data']['point_id'],))
3265
        cnx.commit()
3266
        cursor.close()
3267
        cnx.close()
3268
3269
        resp.status = falcon.HTTP_201
3270
        resp.location = '/energystoragecontainers/' + str(id_) + '/grids/' + str(gid) + '/points/' + \
3271
                        str(new_values['data']['point_id'])
3272
3273
3274
class EnergyStorageContainerGridPointItem:
@@ 2477-2596 (lines=120) @@
2474
        resp.status = falcon.HTTP_200
2475
2476
2477
class EnergyStorageContainerFirecontrolPointCollection:
2478
    def __init__(self):
2479
        """Initializes EnergyStorageContainerFirecontrolPointCollection"""
2480
        pass
2481
2482
    @staticmethod
2483
    def on_options(req, resp, id_, fid):
2484
        _ = req
2485
        resp.status = falcon.HTTP_200
2486
        _ = id_
2487
2488
    @staticmethod
2489
    def on_get(req, resp, id_, fid):
2490
        if 'API-KEY' not in req.headers or \
2491
                not isinstance(req.headers['API-KEY'], str) or \
2492
                len(str.strip(req.headers['API-KEY'])) == 0:
2493
            access_control(req)
2494
        else:
2495
            api_key_control(req)
2496
        if not id_.isdigit() or int(id_) <= 0:
2497
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2498
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2499
        if not fid.isdigit() or int(fid) <= 0:
2500
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2501
                                   description='API.INVALID_FIRECONTROL_ID')
2502
2503
        cnx = mysql.connector.connect(**config.myems_system_db)
2504
        cursor = cnx.cursor()
2505
2506
        cursor.execute(" SELECT name "
2507
                       " FROM tbl_energy_storage_containers_firecontrols "
2508
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, fid, ))
2509
        if cursor.fetchone() is None:
2510
            cursor.close()
2511
            cnx.close()
2512
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2513
                                   description='API.ENERGY_STORAGE_CONTAINER_FIRECONTROL_NOT_FOUND')
2514
2515
        query = (" SELECT p.id, p.name, "
2516
                 "        ds.id, ds.name, ds.uuid, "
2517
                 "        p.address "
2518
                 " FROM tbl_points p, tbl_energy_storage_containers_firecontrols_points mp, tbl_data_sources ds "
2519
                 " WHERE mp.firecontrol_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
2520
                 " ORDER BY p.name ")
2521
        cursor.execute(query, (fid,))
2522
        rows = cursor.fetchall()
2523
2524
        result = list()
2525
        if rows is not None and len(rows) > 0:
2526
            for row in rows:
2527
                meta_result = {"id": row[0], "name": row[1],
2528
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
2529
                               "address": row[5]}
2530
                result.append(meta_result)
2531
2532
        resp.text = json.dumps(result)
2533
2534
    @staticmethod
2535
    @user_logger
2536
    def on_post(req, resp, id_, fid):
2537
        """Handles POST requests"""
2538
        admin_control(req)
2539
        try:
2540
            raw_json = req.stream.read().decode('utf-8')
2541
        except Exception as ex:
2542
            print(str(ex))
2543
            raise falcon.HTTPError(status=falcon.HTTP_400,
2544
                                   title='API.BAD_REQUEST',
2545
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2546
2547
        if not id_.isdigit() or int(id_) <= 0:
2548
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2549
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2550
        if not fid.isdigit() or int(fid) <= 0:
2551
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2552
                                   description='API.INVALID_FIRECONTROL_ID')
2553
2554
        new_values = json.loads(raw_json)
2555
        cnx = mysql.connector.connect(**config.myems_system_db)
2556
        cursor = cnx.cursor()
2557
2558
        cursor.execute(" SELECT name "
2559
                       " FROM tbl_energy_storage_containers_firecontrols "
2560
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, fid,))
2561
        if cursor.fetchone() is None:
2562
            cursor.close()
2563
            cnx.close()
2564
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2565
                                   description='API.ENERGY_STORAGE_CONTAINER_FIRECONTROL_NOT_FOUND')
2566
2567
        cursor.execute(" SELECT name, object_type "
2568
                       " FROM tbl_points "
2569
                       " WHERE id = %s ", (new_values['data']['point_id'],))
2570
        row = cursor.fetchone()
2571
        if row is None:
2572
            cursor.close()
2573
            cnx.close()
2574
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2575
                                   description='API.POINT_NOT_FOUND')
2576
2577
        query = (" SELECT id " 
2578
                 " FROM tbl_energy_storage_containers_firecontrols_points "
2579
                 " WHERE firecontrol_id = %s AND point_id = %s")
2580
        cursor.execute(query, (fid, new_values['data']['point_id'],))
2581
        if cursor.fetchone() is not None:
2582
            cursor.close()
2583
            cnx.close()
2584
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2585
                                   description='API.FIRECONTROL_POINT_RELATION_EXISTS')
2586
2587
        add_row = (" INSERT INTO tbl_energy_storage_containers_firecontrols_points (firecontrol_id, point_id) "
2588
                   " VALUES (%s, %s) ")
2589
        cursor.execute(add_row, (fid, new_values['data']['point_id'],))
2590
        cnx.commit()
2591
        cursor.close()
2592
        cnx.close()
2593
2594
        resp.status = falcon.HTTP_201
2595
        resp.location = '/energystoragecontainers/' + str(id_) + '/firecontrols/' + str(fid) + '/points/' + \
2596
                        str(new_values['data']['point_id'])
2597
2598
2599
class EnergyStorageContainerFirecontrolPointItem:
@@ 1987-2106 (lines=120) @@
1984
        resp.status = falcon.HTTP_200
1985
1986
1987
class EnergyStorageContainerDCDCPointCollection:
1988
    def __init__(self):
1989
        """Initializes EnergyStorageContainerDCDCPointCollection"""
1990
        pass
1991
1992
    @staticmethod
1993
    def on_options(req, resp, id_, did):
1994
        _ = req
1995
        resp.status = falcon.HTTP_200
1996
        _ = id_
1997
1998
    @staticmethod
1999
    def on_get(req, resp, id_, did):
2000
        if 'API-KEY' not in req.headers or \
2001
                not isinstance(req.headers['API-KEY'], str) or \
2002
                len(str.strip(req.headers['API-KEY'])) == 0:
2003
            access_control(req)
2004
        else:
2005
            api_key_control(req)
2006
        if not id_.isdigit() or int(id_) <= 0:
2007
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2008
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2009
        if not did.isdigit() or int(did) <= 0:
2010
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2011
                                   description='API.INVALID_DCDC_ID')
2012
2013
        cnx = mysql.connector.connect(**config.myems_system_db)
2014
        cursor = cnx.cursor()
2015
2016
        cursor.execute(" SELECT name "
2017
                       " FROM tbl_energy_storage_containers_dcdcs "
2018
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, did, ))
2019
        if cursor.fetchone() is None:
2020
            cursor.close()
2021
            cnx.close()
2022
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2023
                                   description='API.ENERGY_STORAGE_CONTAINER_DCDC_NOT_FOUND')
2024
2025
        query = (" SELECT p.id, p.name, "
2026
                 "        ds.id, ds.name, ds.uuid, "
2027
                 "        p.address "
2028
                 " FROM tbl_points p, tbl_energy_storage_containers_dcdcs_points mp, tbl_data_sources ds "
2029
                 " WHERE mp.dcdc_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
2030
                 " ORDER BY p.name ")
2031
        cursor.execute(query, (did,))
2032
        rows = cursor.fetchall()
2033
2034
        result = list()
2035
        if rows is not None and len(rows) > 0:
2036
            for row in rows:
2037
                meta_result = {"id": row[0], "name": row[1],
2038
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
2039
                               "address": row[5]}
2040
                result.append(meta_result)
2041
2042
        resp.text = json.dumps(result)
2043
2044
    @staticmethod
2045
    @user_logger
2046
    def on_post(req, resp, id_, did):
2047
        """Handles POST requests"""
2048
        admin_control(req)
2049
        try:
2050
            raw_json = req.stream.read().decode('utf-8')
2051
        except Exception as ex:
2052
            print(str(ex))
2053
            raise falcon.HTTPError(status=falcon.HTTP_400,
2054
                                   title='API.BAD_REQUEST',
2055
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2056
2057
        if not id_.isdigit() or int(id_) <= 0:
2058
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2059
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2060
        if not did.isdigit() or int(did) <= 0:
2061
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2062
                                   description='API.INVALID_DCDC_ID')
2063
2064
        new_values = json.loads(raw_json)
2065
        cnx = mysql.connector.connect(**config.myems_system_db)
2066
        cursor = cnx.cursor()
2067
2068
        cursor.execute(" SELECT name "
2069
                       " FROM tbl_energy_storage_containers_dcdcs "
2070
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, did,))
2071
        if cursor.fetchone() is None:
2072
            cursor.close()
2073
            cnx.close()
2074
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2075
                                   description='API.ENERGY_STORAGE_CONTAINER_DCDC_NOT_FOUND')
2076
2077
        cursor.execute(" SELECT name, object_type "
2078
                       " FROM tbl_points "
2079
                       " WHERE id = %s ", (new_values['data']['point_id'],))
2080
        row = cursor.fetchone()
2081
        if row is None:
2082
            cursor.close()
2083
            cnx.close()
2084
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2085
                                   description='API.POINT_NOT_FOUND')
2086
2087
        query = (" SELECT id " 
2088
                 " FROM tbl_energy_storage_containers_dcdcs_points "
2089
                 " WHERE dcdc_id = %s AND point_id = %s")
2090
        cursor.execute(query, (did, new_values['data']['point_id'],))
2091
        if cursor.fetchone() is not None:
2092
            cursor.close()
2093
            cnx.close()
2094
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
2095
                                   description='API.DCDC_POINT_RELATION_EXISTS')
2096
2097
        add_row = (" INSERT INTO tbl_energy_storage_containers_dcdcs_points (dcdc_id, point_id) "
2098
                   " VALUES (%s, %s) ")
2099
        cursor.execute(add_row, (did, new_values['data']['point_id'],))
2100
        cnx.commit()
2101
        cursor.close()
2102
        cnx.close()
2103
2104
        resp.status = falcon.HTTP_201
2105
        resp.location = '/energystoragecontainers/' + str(id_) + '/dcdcs/' + str(did) + '/points/' + \
2106
                        str(new_values['data']['point_id'])
2107
2108
2109
class EnergyStorageContainerDCDCPointItem:
@@ 1089-1208 (lines=120) @@
1086
        resp.status = falcon.HTTP_200
1087
1088
1089
class EnergyStorageContainerBatteryPointCollection:
1090
    def __init__(self):
1091
        """Initializes EnergyStorageContainerBatteryPointCollection"""
1092
        pass
1093
1094
    @staticmethod
1095
    def on_options(req, resp, id_, bid):
1096
        _ = req
1097
        resp.status = falcon.HTTP_200
1098
        _ = id_
1099
1100
    @staticmethod
1101
    def on_get(req, resp, id_, bid):
1102
        if 'API-KEY' not in req.headers or \
1103
                not isinstance(req.headers['API-KEY'], str) or \
1104
                len(str.strip(req.headers['API-KEY'])) == 0:
1105
            access_control(req)
1106
        else:
1107
            api_key_control(req)
1108
        if not id_.isdigit() or int(id_) <= 0:
1109
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1110
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
1111
        if not bid.isdigit() or int(bid) <= 0:
1112
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1113
                                   description='API.INVALID_BMS_ID')
1114
1115
        cnx = mysql.connector.connect(**config.myems_system_db)
1116
        cursor = cnx.cursor()
1117
1118
        cursor.execute(" SELECT name "
1119
                       " FROM tbl_energy_storage_containers_batteries "
1120
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, bid, ))
1121
        if cursor.fetchone() is None:
1122
            cursor.close()
1123
            cnx.close()
1124
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1125
                                   description='API.ENERGY_STORAGE_CONTAINER_BMS_NOT_FOUND')
1126
1127
        query = (" SELECT p.id, p.name, "
1128
                 "        ds.id, ds.name, ds.uuid, "
1129
                 "        p.address "
1130
                 " FROM tbl_points p, tbl_energy_storage_containers_bmses_points mp, tbl_data_sources ds "
1131
                 " WHERE mp.bms_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
1132
                 " ORDER BY p.name ")
1133
        cursor.execute(query, (bid,))
1134
        rows = cursor.fetchall()
1135
1136
        result = list()
1137
        if rows is not None and len(rows) > 0:
1138
            for row in rows:
1139
                meta_result = {"id": row[0], "name": row[1],
1140
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
1141
                               "address": row[5]}
1142
                result.append(meta_result)
1143
1144
        resp.text = json.dumps(result)
1145
1146
    @staticmethod
1147
    @user_logger
1148
    def on_post(req, resp, id_, bid):
1149
        """Handles POST requests"""
1150
        admin_control(req)
1151
        try:
1152
            raw_json = req.stream.read().decode('utf-8')
1153
        except Exception as ex:
1154
            print(str(ex))
1155
            raise falcon.HTTPError(status=falcon.HTTP_400,
1156
                                   title='API.BAD_REQUEST',
1157
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1158
1159
        if not id_.isdigit() or int(id_) <= 0:
1160
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1161
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
1162
        if not bid.isdigit() or int(bid) <= 0:
1163
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1164
                                   description='API.INVALID_BMS_ID')
1165
1166
        new_values = json.loads(raw_json)
1167
        cnx = mysql.connector.connect(**config.myems_system_db)
1168
        cursor = cnx.cursor()
1169
1170
        cursor.execute(" SELECT name "
1171
                       " FROM tbl_energy_storage_containers_batteries "
1172
                       " WHERE energy_storage_container_id = %s AND id = %s ", (id_, bid,))
1173
        if cursor.fetchone() is None:
1174
            cursor.close()
1175
            cnx.close()
1176
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1177
                                   description='API.ENERGY_STORAGE_CONTAINER_BMS_NOT_FOUND')
1178
1179
        cursor.execute(" SELECT name, object_type "
1180
                       " FROM tbl_points "
1181
                       " WHERE id = %s ", (new_values['data']['point_id'],))
1182
        row = cursor.fetchone()
1183
        if row is None:
1184
            cursor.close()
1185
            cnx.close()
1186
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1187
                                   description='API.POINT_NOT_FOUND')
1188
1189
        query = (" SELECT id " 
1190
                 " FROM tbl_energy_storage_containers_bmses_points "
1191
                 " WHERE bms_id = %s AND point_id = %s")
1192
        cursor.execute(query, (bid, new_values['data']['point_id'],))
1193
        if cursor.fetchone() is not None:
1194
            cursor.close()
1195
            cnx.close()
1196
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
1197
                                   description='API.BMS_POINT_RELATION_EXISTS')
1198
1199
        add_row = (" INSERT INTO tbl_energy_storage_containers_bmses_points (bms_id, point_id) "
1200
                   " VALUES (%s, %s) ")
1201
        cursor.execute(add_row, (bid, new_values['data']['point_id'],))
1202
        cnx.commit()
1203
        cursor.close()
1204
        cnx.close()
1205
1206
        resp.status = falcon.HTTP_201
1207
        resp.location = '/energystoragecontainers/' + str(id_) + '/batteries/' + str(bid) + '/points/' + \
1208
                        str(new_values['data']['point_id'])
1209
1210
1211
class EnergyStorageContainerBatteryPointItem:

myems-api/core/photovoltaicpowerstation.py 1 location

@@ 5217-5335 (lines=119) @@
5214
5215
        resp.status = falcon.HTTP_204
5216
5217
class PhotovoltaicPowerStationInvertorPointCollection:
5218
    def __init__(self):
5219
        pass
5220
5221
    @staticmethod
5222
    def on_options(req, resp, id_, iid):
5223
        _ = req
5224
        resp.status = falcon.HTTP_200
5225
        _ = id_
5226
        _ = iid
5227
5228
    @staticmethod
5229
    def on_get(req, resp, id_, iid):
5230
        if 'API-KEY' not in req.headers or \
5231
                not isinstance(req.headers['API-KEY'], str) or \
5232
                len(str.strip(req.headers['API-KEY'])) == 0:
5233
            access_control(req)
5234
        else:
5235
            api_key_control(req)
5236
        if not id_.isdigit() or int(id_) <= 0:
5237
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5238
                                   description='API.INVALID_PHOTOVOLTAIC_POWER_STATION_ID')
5239
        if not iid.isdigit() or int(iid) <= 0:
5240
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5241
                                   description='API.INVALID_INVERTOR_ID')
5242
5243
        cnx = mysql.connector.connect(**config.myems_system_db)
5244
        cursor = cnx.cursor()
5245
5246
        cursor.execute(" SELECT name "
5247
                       " FROM tbl_photovoltaic_power_stations_invertors "
5248
                       " WHERE photovoltaic_power_station_id = %s AND id = %s ", (id_, iid,))
5249
        if cursor.fetchone() is None:
5250
            cursor.close()
5251
            cnx.close()
5252
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5253
                                   description='API.PHOTOVOLTAIC_INVERTOR_NOT_FOUND')
5254
5255
        query = (" SELECT p.id, p.name, "
5256
                 "        ds.id, ds.name, ds.uuid, "
5257
                 "        p.address "
5258
                 " FROM tbl_points p, tbl_photovoltaic_power_stations_invertors_points mp, tbl_data_sources ds "
5259
                 " WHERE mp.invertor_id = %s AND p.id = mp.point_id AND p.data_source_id = ds.id "
5260
                 " ORDER BY p.name ")
5261
        cursor.execute(query, (iid,))
5262
        rows = cursor.fetchall()
5263
5264
        result = list()
5265
        if rows is not None and len(rows) > 0:
5266
            for row in rows:
5267
                meta_result = {"id": row[0], "name": row[1],
5268
                               "data_source": {"id": row[2], "name": row[3], "uuid": row[4]},
5269
                               "address": row[5]}
5270
                result.append(meta_result)
5271
5272
        resp.text = json.dumps(result)
5273
5274
    @staticmethod
5275
    @user_logger
5276
    def on_post(req, resp, id_, iid):
5277
        admin_control(req)
5278
        try:
5279
            raw_json = req.stream.read().decode('utf-8')
5280
        except Exception as ex:
5281
            print(str(ex))
5282
            raise falcon.HTTPError(status=falcon.HTTP_400,
5283
                                   title='API.BAD_REQUEST',
5284
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
5285
5286
        if not id_.isdigit() or int(id_) <= 0:
5287
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5288
                                   description='API.INVALID_PHOTOVOLTAIC_POWER_STATION_ID')
5289
        if not iid.isdigit() or int(iid) <= 0:
5290
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
5291
                                   description='API.INVALID_INVERTOR_ID')
5292
5293
        new_values = json.loads(raw_json)
5294
        cnx = mysql.connector.connect(**config.myems_system_db)
5295
        cursor = cnx.cursor()
5296
5297
        cursor.execute(" SELECT name "
5298
                       " FROM tbl_photovoltaic_power_stations_invertors "
5299
                       " WHERE photovoltaic_power_station_id = %s AND id = %s ", (id_, iid,))
5300
        if cursor.fetchone() is None:
5301
            cursor.close()
5302
            cnx.close()
5303
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5304
                                   description='API.PHOTOVOLTAIC_INVERTOR_NOT_FOUND')
5305
5306
        cursor.execute(" SELECT name, object_type "
5307
                       " FROM tbl_points "
5308
                       " WHERE id = %s ", (new_values['data']['point_id'],))
5309
        row = cursor.fetchone()
5310
        if row is None:
5311
            cursor.close()
5312
            cnx.close()
5313
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
5314
                                   description='API.POINT_NOT_FOUND')
5315
5316
        query = (" SELECT id "
5317
                 " FROM tbl_photovoltaic_power_stations_invertors_points "
5318
                 " WHERE invertor_id = %s AND point_id = %s")
5319
        cursor.execute(query, (iid, new_values['data']['point_id'],))
5320
        if cursor.fetchone() is not None:
5321
            cursor.close()
5322
            cnx.close()
5323
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
5324
                                   description='API.INVERTOR_POINT_RELATION_EXISTS')
5325
5326
        add_row = (" INSERT INTO tbl_photovoltaic_power_stations_invertors_points (invertor_id, point_id) "
5327
                   " VALUES (%s, %s) ")
5328
        cursor.execute(add_row, (iid, new_values['data']['point_id'],))
5329
        cnx.commit()
5330
        cursor.close()
5331
        cnx.close()
5332
5333
        resp.status = falcon.HTTP_201
5334
        resp.location = '/photovoltaicpowerstations/' + str(id_) + '/invertors/' + str(iid) + '/points/' + \
5335
                        str(new_values['data']['point_id'])
5336
5337
5338
class PhotovoltaicPowerStationInvertorPointItem: