Code Duplication    Length = 243-246 lines in 5 locations

myems-api/core/microgrid.py 4 locations

@@ 3771-4014 (lines=244) @@
3768
        resp.location = '/microgrids' + str(id_) + '/photovoltaics/' + str(new_id)
3769
3770
3771
class MicrogridPhotovoltaicItem:
3772
    def __init__(self):
3773
        """Initializes MicrogridPhotovoltaicItem"""
3774
        pass
3775
3776
    @staticmethod
3777
    def on_options(req, resp, id_, pid):
3778
        resp.status = falcon.HTTP_200
3779
3780
    @staticmethod
3781
    def on_get(req, resp, id_, pid):
3782
        access_control(req)
3783
        if not id_.isdigit() or int(id_) <= 0:
3784
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3785
                                   description='API.INVALID_MICROGRID_ID')
3786
        if not pid.isdigit() or int(pid) <= 0:
3787
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3788
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_ID')
3789
3790
        cnx = mysql.connector.connect(**config.myems_system_db)
3791
        cursor = cnx.cursor()
3792
3793
        cursor.execute(" SELECT name "
3794
                       " FROM tbl_microgrids "
3795
                       " WHERE id = %s ", (id_,))
3796
        if cursor.fetchone() is None:
3797
            cursor.close()
3798
            cnx.close()
3799
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3800
                                   description='API.MICROGRID_NOT_FOUND')
3801
3802
        # query microgrid dict
3803
        query = (" SELECT id, name, uuid "
3804
                 " FROM tbl_microgrids ")
3805
        cursor.execute(query)
3806
        rows_microgrids = cursor.fetchall()
3807
3808
        microgrid_dict = dict()
3809
        if rows_microgrids is not None and len(rows_microgrids) > 0:
3810
            for row in rows_microgrids:
3811
                microgrid_dict[row[0]] = {"id": row[0],
3812
                                          "name": row[1],
3813
                                          "uuid": row[2]}
3814
        # query meter dict
3815
        query = (" SELECT id, name, uuid "
3816
                 " FROM tbl_meters ")
3817
        cursor.execute(query)
3818
        rows_meters = cursor.fetchall()
3819
3820
        meter_dict = dict()
3821
        if rows_meters is not None and len(rows_meters) > 0:
3822
            for row in rows_meters:
3823
                meter_dict[row[0]] = {"id": row[0],
3824
                                      "name": row[1],
3825
                                      "uuid": row[2]}
3826
        # query point dict
3827
        query = (" SELECT id, name "
3828
                 " FROM tbl_points ")
3829
        cursor.execute(query)
3830
        rows_points = cursor.fetchall()
3831
3832
        point_dict = dict()
3833
        if rows_points is not None and len(rows_points) > 0:
3834
            for row in rows_points:
3835
                point_dict[row[0]] = {"id": row[0],
3836
                                      "name": row[1]}
3837
3838
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_power "
3839
                 " FROM tbl_microgrids_photovoltaics "
3840
                 " WHERE id = %s ")
3841
        cursor.execute(query, (pid,))
3842
        row = cursor.fetchone()
3843
        cursor.close()
3844
        cnx.close()
3845
3846
        if row is None:
3847
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3848
                                   description='API.MICROGRID_PHOTOVOLTAIC_NOT_FOUND')
3849
        else:
3850
            meta_result = {"id": row[0],
3851
                           "name": row[1],
3852
                           "uuid": row[2],
3853
                           "microgrid": microgrid_dict.get(row[3], None),
3854
                           "power_point": point_dict.get(row[4], None),
3855
                           "meter": meter_dict.get(row[5], None),
3856
                           "rated_power": row[6]}
3857
3858
        resp.text = json.dumps(meta_result)
3859
3860
    @staticmethod
3861
    @user_logger
3862
    def on_delete(req, resp, id_, pid):
3863
        admin_control(req)
3864
        if not id_.isdigit() or int(id_) <= 0:
3865
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3866
                                   description='API.INVALID_MICROGRID_ID')
3867
        if not pid.isdigit() or int(pid) <= 0:
3868
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3869
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_ID')
3870
3871
        cnx = mysql.connector.connect(**config.myems_system_db)
3872
        cursor = cnx.cursor()
3873
3874
        cursor.execute(" SELECT name "
3875
                       " FROM tbl_microgrids "
3876
                       " WHERE id = %s ", (id_,))
3877
        if cursor.fetchone() is None:
3878
            cursor.close()
3879
            cnx.close()
3880
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3881
                                   description='API.MICROGRID_NOT_FOUND')
3882
3883
        cursor.execute(" SELECT name "
3884
                       " FROM tbl_microgrids_photovoltaics "
3885
                       " WHERE id = %s ", (pid,))
3886
        if cursor.fetchone() is None:
3887
            cursor.close()
3888
            cnx.close()
3889
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3890
                                   description='API.MICROGRID_PHOTOVOLTAIC_NOT_FOUND')
3891
3892
        cursor.execute(" DELETE FROM tbl_microgrids_photovoltaics "
3893
                       " WHERE id = %s ", (pid,))
3894
        cnx.commit()
3895
3896
        cursor.close()
3897
        cnx.close()
3898
3899
        resp.status = falcon.HTTP_204
3900
3901
    @staticmethod
3902
    @user_logger
3903
    def on_put(req, resp, id_, pid):
3904
        """Handles PUT requests"""
3905
        admin_control(req)
3906
        try:
3907
            raw_json = req.stream.read().decode('utf-8')
3908
        except Exception as ex:
3909
            raise falcon.HTTPError(status=falcon.HTTP_400,
3910
                                   title='API.BAD_REQUEST',
3911
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3912
        if not id_.isdigit() or int(id_) <= 0:
3913
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3914
                                   description='API.INVALID_MICROGRID_ID')
3915
        if not pid.isdigit() or int(pid) <= 0:
3916
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3917
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_ID')
3918
3919
        new_values = json.loads(raw_json)
3920
3921
        if 'name' not in new_values['data'].keys() or \
3922
                not isinstance(new_values['data']['name'], str) or \
3923
                len(str.strip(new_values['data']['name'])) == 0:
3924
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3925
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_NAME')
3926
        name = str.strip(new_values['data']['name'])
3927
3928
        if 'power_point_id' not in new_values['data'].keys() or \
3929
                not isinstance(new_values['data']['power_point_id'], int) or \
3930
                new_values['data']['power_point_id'] <= 0:
3931
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3932
                                   description='API.INVALID_POWER_POINT_ID')
3933
        power_point_id = new_values['data']['power_point_id']
3934
3935
        if 'meter_id' not in new_values['data'].keys() or \
3936
                not isinstance(new_values['data']['meter_id'], int) or \
3937
                new_values['data']['meter_id'] <= 0:
3938
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3939
                                   description='API.INVALID_METER_ID')
3940
        meter_id = new_values['data']['meter_id']
3941
3942
        if 'rated_power' not in new_values['data'].keys() or \
3943
                not (isinstance(new_values['data']['rated_power'], float) or
3944
                     isinstance(new_values['data']['rated_power'], int)):
3945
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3946
                                   description='API.INVALID_RATED_POWER')
3947
        rated_power = float(new_values['data']['rated_power'])
3948
3949
        cnx = mysql.connector.connect(**config.myems_system_db)
3950
        cursor = cnx.cursor()
3951
3952
        cursor.execute(" SELECT name "
3953
                       " FROM tbl_microgrids "
3954
                       " WHERE id = %s ", (id_,))
3955
        if cursor.fetchone() is None:
3956
            cursor.close()
3957
            cnx.close()
3958
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3959
                                   description='API.MICROGRID_NOT_FOUND')
3960
3961
        cursor.execute(" SELECT name "
3962
                       " FROM tbl_microgrids_photovoltaics "
3963
                       " WHERE id = %s ", (pid,))
3964
        if cursor.fetchone() is None:
3965
            cursor.close()
3966
            cnx.close()
3967
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3968
                                   description='API.MICROGRID_PHOTOVOLTAIC_NOT_FOUND')
3969
3970
        cursor.execute(" SELECT name "
3971
                       " FROM tbl_microgrids_photovoltaics "
3972
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
3973
                       (id_, name, pid))
3974
        if cursor.fetchone() is not None:
3975
            cursor.close()
3976
            cnx.close()
3977
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3978
                                   description='API.MICROGRID_PHOTOVOLTAIC_NAME_IS_ALREADY_IN_USE')
3979
3980
        cursor.execute(" SELECT name "
3981
                       " FROM tbl_points "
3982
                       " WHERE id = %s ",
3983
                       (power_point_id,))
3984
        if cursor.fetchone() is None:
3985
            cursor.close()
3986
            cnx.close()
3987
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3988
                                   description='API.POWER_POINT_NOT_FOUND')
3989
3990
        cursor.execute(" SELECT name "
3991
                       " FROM tbl_meters "
3992
                       " WHERE id = %s ",
3993
                       (meter_id,))
3994
        if cursor.fetchone() is None:
3995
            cursor.close()
3996
            cnx.close()
3997
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3998
                                   description='API.METER_NOT_FOUND')
3999
4000
        update_row = (" UPDATE tbl_microgrids_photovoltaics "
4001
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_power = %s "
4002
                      " WHERE id = %s ")
4003
        cursor.execute(update_row, (name,
4004
                                    id_,
4005
                                    power_point_id,
4006
                                    meter_id,
4007
                                    rated_power,
4008
                                    pid))
4009
        cnx.commit()
4010
4011
        cursor.close()
4012
        cnx.close()
4013
4014
        resp.status = falcon.HTTP_200
4015
4016
4017
class MicrogridPowerconversionsystemCollection:
@@ 3333-3576 (lines=244) @@
3330
        resp.location = '/microgrids/' + str(id_) + '/loads/' + str(new_id)
3331
3332
3333
class MicrogridLoadItem:
3334
    def __init__(self):
3335
        """Initializes MicrogridLoadItem"""
3336
        pass
3337
3338
    @staticmethod
3339
    def on_options(req, resp, id_, lid):
3340
        resp.status = falcon.HTTP_200
3341
3342
    @staticmethod
3343
    def on_get(req, resp, id_, lid):
3344
        access_control(req)
3345
        if not id_.isdigit() or int(id_) <= 0:
3346
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3347
                                   description='API.INVALID_MICROGRID_ID')
3348
        if not lid.isdigit() or int(lid) <= 0:
3349
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3350
                                   description='API.INVALID_MICROGRID_LOAD_ID')
3351
3352
        cnx = mysql.connector.connect(**config.myems_system_db)
3353
        cursor = cnx.cursor()
3354
3355
        cursor.execute(" SELECT name "
3356
                       " FROM tbl_microgrids "
3357
                       " WHERE id = %s ", (id_,))
3358
        if cursor.fetchone() is None:
3359
            cursor.close()
3360
            cnx.close()
3361
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3362
                                   description='API.MICROGRID_NOT_FOUND')
3363
3364
        # query microgrid dict
3365
        query = (" SELECT id, name, uuid "
3366
                 " FROM tbl_microgrids ")
3367
        cursor.execute(query)
3368
        rows_microgrids = cursor.fetchall()
3369
3370
        microgrid_dict = dict()
3371
        if rows_microgrids is not None and len(rows_microgrids) > 0:
3372
            for row in rows_microgrids:
3373
                microgrid_dict[row[0]] = {"id": row[0],
3374
                                          "name": row[1],
3375
                                          "uuid": row[2]}
3376
        # query meter dict
3377
        query = (" SELECT id, name, uuid "
3378
                 " FROM tbl_meters ")
3379
        cursor.execute(query)
3380
        rows_meters = cursor.fetchall()
3381
3382
        meter_dict = dict()
3383
        if rows_meters is not None and len(rows_meters) > 0:
3384
            for row in rows_meters:
3385
                meter_dict[row[0]] = {"id": row[0],
3386
                                      "name": row[1],
3387
                                      "uuid": row[2]}
3388
        # query point dict
3389
        query = (" SELECT id, name "
3390
                 " FROM tbl_points ")
3391
        cursor.execute(query)
3392
        rows_points = cursor.fetchall()
3393
3394
        point_dict = dict()
3395
        if rows_points is not None and len(rows_points) > 0:
3396
            for row in rows_points:
3397
                point_dict[row[0]] = {"id": row[0],
3398
                                      "name": row[1]}
3399
3400
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_input_power "
3401
                 " FROM tbl_microgrids_loads "
3402
                 " WHERE id = %s ")
3403
        cursor.execute(query, (lid,))
3404
        row = cursor.fetchone()
3405
        cursor.close()
3406
        cnx.close()
3407
3408
        if row is None:
3409
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3410
                                   description='API.MICROGRID_LOAD_NOT_FOUND')
3411
        else:
3412
            meta_result = {"id": row[0],
3413
                           "name": row[1],
3414
                           "uuid": row[2],
3415
                           "microgrid": microgrid_dict.get(row[3], None),
3416
                           "power_point": point_dict.get(row[4], None),
3417
                           "meter": meter_dict.get(row[5], None),
3418
                           "rated_input_power": row[6]}
3419
3420
        resp.text = json.dumps(meta_result)
3421
3422
    @staticmethod
3423
    @user_logger
3424
    def on_delete(req, resp, id_, lid):
3425
        admin_control(req)
3426
        if not id_.isdigit() or int(id_) <= 0:
3427
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3428
                                   description='API.INVALID_MICROGRID_ID')
3429
        if not lid.isdigit() or int(lid) <= 0:
3430
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3431
                                   description='API.INVALID_MICROGRID_LOAD_ID')
3432
3433
        cnx = mysql.connector.connect(**config.myems_system_db)
3434
        cursor = cnx.cursor()
3435
3436
        cursor.execute(" SELECT name "
3437
                       " FROM tbl_microgrids "
3438
                       " WHERE id = %s ", (id_,))
3439
        if cursor.fetchone() is None:
3440
            cursor.close()
3441
            cnx.close()
3442
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3443
                                   description='API.MICROGRID_NOT_FOUND')
3444
3445
        cursor.execute(" SELECT name "
3446
                       " FROM tbl_microgrids_loads "
3447
                       " WHERE id = %s ", (lid,))
3448
        if cursor.fetchone() is None:
3449
            cursor.close()
3450
            cnx.close()
3451
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3452
                                   description='API.MICROGRID_LOAD_NOT_FOUND')
3453
3454
        cursor.execute(" DELETE FROM tbl_microgrids_loads "
3455
                       " WHERE id = %s ", (lid,))
3456
        cnx.commit()
3457
3458
        cursor.close()
3459
        cnx.close()
3460
3461
        resp.status = falcon.HTTP_204
3462
3463
    @staticmethod
3464
    @user_logger
3465
    def on_put(req, resp, id_, lid):
3466
        """Handles PUT requests"""
3467
        admin_control(req)
3468
        try:
3469
            raw_json = req.stream.read().decode('utf-8')
3470
        except Exception as ex:
3471
            raise falcon.HTTPError(status=falcon.HTTP_400,
3472
                                   title='API.BAD_REQUEST',
3473
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3474
        if not id_.isdigit() or int(id_) <= 0:
3475
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3476
                                   description='API.INVALID_MICROGRID_ID')
3477
        if not lid.isdigit() or int(lid) <= 0:
3478
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3479
                                   description='API.INVALID_MICROGRID_LOAD_ID')
3480
3481
        new_values = json.loads(raw_json)
3482
3483
        if 'name' not in new_values['data'].keys() or \
3484
                not isinstance(new_values['data']['name'], str) or \
3485
                len(str.strip(new_values['data']['name'])) == 0:
3486
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3487
                                   description='API.INVALID_MICROGRID_LOAD_NAME')
3488
        name = str.strip(new_values['data']['name'])
3489
3490
        if 'power_point_id' not in new_values['data'].keys() or \
3491
                not isinstance(new_values['data']['power_point_id'], int) or \
3492
                new_values['data']['power_point_id'] <= 0:
3493
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3494
                                   description='API.INVALID_POWER_POINT_ID')
3495
        power_point_id = new_values['data']['power_point_id']
3496
3497
        if 'meter_id' not in new_values['data'].keys() or \
3498
                not isinstance(new_values['data']['meter_id'], int) or \
3499
                new_values['data']['meter_id'] <= 0:
3500
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3501
                                   description='API.INVALID_METER_ID')
3502
        meter_id = new_values['data']['meter_id']
3503
3504
        if 'rated_input_power' not in new_values['data'].keys() or \
3505
                not (isinstance(new_values['data']['rated_input_power'], float) or
3506
                     isinstance(new_values['data']['rated_input_power'], int)):
3507
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3508
                                   description='API.INVALID_RATED_INPUT_POWER')
3509
        rated_input_power = float(new_values['data']['rated_input_power'])
3510
3511
        cnx = mysql.connector.connect(**config.myems_system_db)
3512
        cursor = cnx.cursor()
3513
3514
        cursor.execute(" SELECT name "
3515
                       " FROM tbl_microgrids "
3516
                       " WHERE id = %s ", (id_,))
3517
        if cursor.fetchone() is None:
3518
            cursor.close()
3519
            cnx.close()
3520
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3521
                                   description='API.MICROGRID_NOT_FOUND')
3522
3523
        cursor.execute(" SELECT name "
3524
                       " FROM tbl_microgrids_loads "
3525
                       " WHERE id = %s ", (lid,))
3526
        if cursor.fetchone() is None:
3527
            cursor.close()
3528
            cnx.close()
3529
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3530
                                   description='API.MICROGRID_LOAD_NOT_FOUND')
3531
3532
        cursor.execute(" SELECT name "
3533
                       " FROM tbl_microgrids_loads "
3534
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
3535
                       (id_, name, lid))
3536
        if cursor.fetchone() is not None:
3537
            cursor.close()
3538
            cnx.close()
3539
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3540
                                   description='API.MICROGRID_LOAD_NAME_IS_ALREADY_IN_USE')
3541
3542
        cursor.execute(" SELECT name "
3543
                       " FROM tbl_points "
3544
                       " WHERE id = %s ",
3545
                       (power_point_id,))
3546
        if cursor.fetchone() is None:
3547
            cursor.close()
3548
            cnx.close()
3549
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3550
                                   description='API.POWER_POINT_NOT_FOUND')
3551
3552
        cursor.execute(" SELECT name "
3553
                       " FROM tbl_meters "
3554
                       " WHERE id = %s ",
3555
                       (meter_id,))
3556
        if cursor.fetchone() is None:
3557
            cursor.close()
3558
            cnx.close()
3559
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3560
                                   description='API.METER_NOT_FOUND')
3561
3562
        update_row = (" UPDATE tbl_microgrids_loads "
3563
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_input_power = %s "
3564
                      " WHERE id = %s ")
3565
        cursor.execute(update_row, (name,
3566
                                    id_,
3567
                                    power_point_id,
3568
                                    meter_id,
3569
                                    rated_input_power,
3570
                                    lid))
3571
        cnx.commit()
3572
3573
        cursor.close()
3574
        cnx.close()
3575
3576
        resp.status = falcon.HTTP_200
3577
3578
3579
class MicrogridPhotovoltaicCollection:
@@ 1902-2145 (lines=244) @@
1899
        resp.location = '/microgrids/' + str(id_) + '/generators/' + str(new_id)
1900
1901
1902
class MicrogridGeneratorItem:
1903
    def __init__(self):
1904
        """Initializes MicrogridGeneratorItem"""
1905
        pass
1906
1907
    @staticmethod
1908
    def on_options(req, resp, id_, gid):
1909
        resp.status = falcon.HTTP_200
1910
1911
    @staticmethod
1912
    def on_get(req, resp, id_, gid):
1913
        access_control(req)
1914
        if not id_.isdigit() or int(id_) <= 0:
1915
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1916
                                   description='API.INVALID_MICROGRID_ID')
1917
        if not gid.isdigit() or int(gid) <= 0:
1918
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1919
                                   description='API.INVALID_MICROGRID_GENERATOR_ID')
1920
1921
        cnx = mysql.connector.connect(**config.myems_system_db)
1922
        cursor = cnx.cursor()
1923
1924
        cursor.execute(" SELECT name "
1925
                       " FROM tbl_microgrids "
1926
                       " WHERE id = %s ", (id_,))
1927
        if cursor.fetchone() is None:
1928
            cursor.close()
1929
            cnx.close()
1930
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1931
                                   description='API.MICROGRID_NOT_FOUND')
1932
1933
        # query microgrid dict
1934
        query = (" SELECT id, name, uuid "
1935
                 " FROM tbl_microgrids ")
1936
        cursor.execute(query)
1937
        rows_microgrids = cursor.fetchall()
1938
1939
        microgrid_dict = dict()
1940
        if rows_microgrids is not None and len(rows_microgrids) > 0:
1941
            for row in rows_microgrids:
1942
                microgrid_dict[row[0]] = {"id": row[0],
1943
                                          "name": row[1],
1944
                                          "uuid": row[2]}
1945
        # query meter dict
1946
        query = (" SELECT id, name, uuid "
1947
                 " FROM tbl_meters ")
1948
        cursor.execute(query)
1949
        rows_meters = cursor.fetchall()
1950
1951
        meter_dict = dict()
1952
        if rows_meters is not None and len(rows_meters) > 0:
1953
            for row in rows_meters:
1954
                meter_dict[row[0]] = {"id": row[0],
1955
                                      "name": row[1],
1956
                                      "uuid": row[2]}
1957
        # query point dict
1958
        query = (" SELECT id, name "
1959
                 " FROM tbl_points ")
1960
        cursor.execute(query)
1961
        rows_points = cursor.fetchall()
1962
1963
        point_dict = dict()
1964
        if rows_points is not None and len(rows_points) > 0:
1965
            for row in rows_points:
1966
                point_dict[row[0]] = {"id": row[0],
1967
                                      "name": row[1]}
1968
1969
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power "
1970
                 " FROM tbl_microgrids_generators "
1971
                 " WHERE id = %s ")
1972
        cursor.execute(query, (gid,))
1973
        row = cursor.fetchone()
1974
        cursor.close()
1975
        cnx.close()
1976
1977
        if row is None:
1978
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1979
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
1980
        else:
1981
            meta_result = {"id": row[0],
1982
                           "name": row[1],
1983
                           "uuid": row[2],
1984
                           "microgrid": microgrid_dict.get(row[3]),
1985
                           "power_point": point_dict.get(row[4]),
1986
                           "meter": meter_dict.get(row[5]),
1987
                           "rated_output_power": row[6]}
1988
1989
        resp.text = json.dumps(meta_result)
1990
1991
    @staticmethod
1992
    @user_logger
1993
    def on_delete(req, resp, id_, gid):
1994
        admin_control(req)
1995
        if not id_.isdigit() or int(id_) <= 0:
1996
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1997
                                   description='API.INVALID_MICROGRID_ID')
1998
        if not gid.isdigit() or int(gid) <= 0:
1999
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2000
                                   description='API.INVALID_MICROGRID_GENERATOR_ID')
2001
2002
        cnx = mysql.connector.connect(**config.myems_system_db)
2003
        cursor = cnx.cursor()
2004
2005
        cursor.execute(" SELECT name "
2006
                       " FROM tbl_microgrids "
2007
                       " WHERE id = %s ", (id_,))
2008
        if cursor.fetchone() is None:
2009
            cursor.close()
2010
            cnx.close()
2011
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2012
                                   description='API.MICROGRID_NOT_FOUND')
2013
2014
        cursor.execute(" SELECT name "
2015
                       " FROM tbl_microgrids_generators "
2016
                       " WHERE id = %s ", (gid,))
2017
        if cursor.fetchone() is None:
2018
            cursor.close()
2019
            cnx.close()
2020
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2021
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
2022
2023
        cursor.execute(" DELETE FROM tbl_microgrids_generators "
2024
                       " WHERE id = %s ", (gid,))
2025
        cnx.commit()
2026
2027
        cursor.close()
2028
        cnx.close()
2029
2030
        resp.status = falcon.HTTP_204
2031
2032
    @staticmethod
2033
    @user_logger
2034
    def on_put(req, resp, id_, gid):
2035
        """Handles PUT requests"""
2036
        admin_control(req)
2037
        try:
2038
            raw_json = req.stream.read().decode('utf-8')
2039
        except Exception as ex:
2040
            raise falcon.HTTPError(status=falcon.HTTP_400,
2041
                                   title='API.BAD_REQUEST',
2042
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2043
        if not id_.isdigit() or int(id_) <= 0:
2044
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2045
                                   description='API.INVALID_MICROGRID_ID')
2046
        if not gid.isdigit() or int(gid) <= 0:
2047
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2048
                                   description='API.INVALID_MICROGRID_GENERATOR_ID')
2049
2050
        new_values = json.loads(raw_json)
2051
2052
        if 'name' not in new_values['data'].keys() or \
2053
                not isinstance(new_values['data']['name'], str) or \
2054
                len(str.strip(new_values['data']['name'])) == 0:
2055
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2056
                                   description='API.INVALID_MICROGRID_GENERATOR_NAME')
2057
        name = str.strip(new_values['data']['name'])
2058
2059
        if 'power_point_id' not in new_values['data'].keys() or \
2060
                not isinstance(new_values['data']['power_point_id'], int) or \
2061
                new_values['data']['power_point_id'] <= 0:
2062
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2063
                                   description='API.INVALID_POWER_POINT_ID')
2064
        power_point_id = new_values['data']['power_point_id']
2065
2066
        if 'meter_id' not in new_values['data'].keys() or \
2067
                not isinstance(new_values['data']['meter_id'], int) or \
2068
                new_values['data']['meter_id'] <= 0:
2069
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2070
                                   description='API.INVALID_METER_ID')
2071
        meter_id = new_values['data']['meter_id']
2072
2073
        if 'rated_output_power' not in new_values['data'].keys() or \
2074
                not (isinstance(new_values['data']['rated_output_power'], float) or
2075
                     isinstance(new_values['data']['rated_output_power'], int)):
2076
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2077
                                   description='API.INVALID_RATED_OUTPUT_POWER')
2078
        rated_output_power = float(new_values['data']['rated_output_power'])
2079
2080
        cnx = mysql.connector.connect(**config.myems_system_db)
2081
        cursor = cnx.cursor()
2082
2083
        cursor.execute(" SELECT name "
2084
                       " FROM tbl_microgrids "
2085
                       " WHERE id = %s ", (id_,))
2086
        if cursor.fetchone() is None:
2087
            cursor.close()
2088
            cnx.close()
2089
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2090
                                   description='API.MICROGRID_NOT_FOUND')
2091
2092
        cursor.execute(" SELECT name "
2093
                       " FROM tbl_microgrids_generators "
2094
                       " WHERE id = %s ", (gid,))
2095
        if cursor.fetchone() is None:
2096
            cursor.close()
2097
            cnx.close()
2098
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2099
                                   description='API.MICROGRID_GENERATOR_NOT_FOUND')
2100
2101
        cursor.execute(" SELECT name "
2102
                       " FROM tbl_microgrids_generators "
2103
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
2104
                       (id_, name, gid))
2105
        if cursor.fetchone() is not None:
2106
            cursor.close()
2107
            cnx.close()
2108
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2109
                                   description='API.MICROGRID_GENERATOR_NAME_IS_ALREADY_IN_USE')
2110
2111
        cursor.execute(" SELECT name "
2112
                       " FROM tbl_points "
2113
                       " WHERE id = %s ",
2114
                       (power_point_id,))
2115
        if cursor.fetchone() is None:
2116
            cursor.close()
2117
            cnx.close()
2118
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2119
                                   description='API.POWER_POINT_NOT_FOUND')
2120
2121
        cursor.execute(" SELECT name "
2122
                       " FROM tbl_meters "
2123
                       " WHERE id = %s ",
2124
                       (meter_id,))
2125
        if cursor.fetchone() is None:
2126
            cursor.close()
2127
            cnx.close()
2128
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2129
                                   description='API.METER_NOT_FOUND')
2130
2131
        update_row = (" UPDATE tbl_microgrids_generators "
2132
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_output_power = %s "
2133
                      " WHERE id = %s ")
2134
        cursor.execute(update_row, (name,
2135
                                    id_,
2136
                                    power_point_id,
2137
                                    meter_id,
2138
                                    rated_output_power,
2139
                                    gid))
2140
        cnx.commit()
2141
2142
        cursor.close()
2143
        cnx.close()
2144
2145
        resp.status = falcon.HTTP_200
2146
2147
2148
class MicrogridGridCollection:
@@ 1466-1708 (lines=243) @@
1463
        resp.location = '/microgrids/' + id_ + '/evchargers/' + str(new_id)
1464
1465
1466
class MicrogridEVChargerItem:
1467
    def __init__(self):
1468
        """Initializes MicrogridEVChargerItem"""
1469
        pass
1470
1471
    @staticmethod
1472
    def on_options(req, resp, id_, eid):
1473
        resp.status = falcon.HTTP_200
1474
1475
    @staticmethod
1476
    def on_get(req, resp, id_, eid):
1477
        access_control(req)
1478
        if not id_.isdigit() or int(id_) <= 0:
1479
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1480
                                   description='API.INVALID_MICROGRID_ID')
1481
        if not eid.isdigit() or int(eid) <= 0:
1482
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1483
                                   description='API.INVALID_MICROGRID_EVCHARGER_ID')
1484
1485
        cnx = mysql.connector.connect(**config.myems_system_db)
1486
        cursor = cnx.cursor()
1487
1488
        cursor.execute(" SELECT name "
1489
                       " FROM tbl_microgrids "
1490
                       " WHERE id = %s ", (id_,))
1491
        if cursor.fetchone() is None:
1492
            cursor.close()
1493
            cnx.close()
1494
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1495
                                   description='API.MICROGRID_NOT_FOUND')
1496
1497
        # query microgrid dict
1498
        query = (" SELECT id, name, uuid "
1499
                 " FROM tbl_microgrids ")
1500
        cursor.execute(query)
1501
        rows_microgrids = cursor.fetchall()
1502
1503
        microgrid_dict = dict()
1504
        if rows_microgrids is not None and len(rows_microgrids) > 0:
1505
            for row in rows_microgrids:
1506
                microgrid_dict[row[0]] = {"id": row[0],
1507
                                          "name": row[1],
1508
                                          "uuid": row[2]}
1509
        # query meter dict
1510
        query = (" SELECT id, name, uuid "
1511
                 " FROM tbl_meters ")
1512
        cursor.execute(query)
1513
        rows_meters = cursor.fetchall()
1514
1515
        meter_dict = dict()
1516
        if rows_meters is not None and len(rows_meters) > 0:
1517
            for row in rows_meters:
1518
                meter_dict[row[0]] = {"id": row[0],
1519
                                      "name": row[1],
1520
                                      "uuid": row[2]}
1521
        # query point dict
1522
        query = (" SELECT id, name "
1523
                 " FROM tbl_points ")
1524
        cursor.execute(query)
1525
        rows_points = cursor.fetchall()
1526
1527
        point_dict = dict()
1528
        if rows_points is not None and len(rows_points) > 0:
1529
            for row in rows_points:
1530
                point_dict[row[0]] = {"id": row[0],
1531
                                      "name": row[1]}
1532
1533
        query = (" SELECT id, name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power "
1534
                 " FROM tbl_microgrids_evchargers "
1535
                 " WHERE id = %s ")
1536
        cursor.execute(query, (eid,))
1537
        row = cursor.fetchone()
1538
        cursor.close()
1539
        cnx.close()
1540
1541
        if row is None:
1542
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1543
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
1544
        else:
1545
            meta_result = {"id": row[0],
1546
                           "name": row[1],
1547
                           "uuid": row[2],
1548
                           "microgrid": microgrid_dict.get(row[3]),
1549
                           "power_point": point_dict.get(row[4]),
1550
                           "meter": meter_dict.get(row[5]),
1551
                           "rated_output_power": row[6]}
1552
1553
        resp.text = json.dumps(meta_result)
1554
1555
    @staticmethod
1556
    @user_logger
1557
    def on_delete(req, resp, id_, eid):
1558
        admin_control(req)
1559
        if not id_.isdigit() or int(id_) <= 0:
1560
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1561
                                   description='API.INVALID_MICROGRID_ID')
1562
        if not eid.isdigit() or int(eid) <= 0:
1563
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1564
                                   description='API.INVALID_MICROGRID_EVCHARGER_ID')
1565
        cnx = mysql.connector.connect(**config.myems_system_db)
1566
        cursor = cnx.cursor()
1567
1568
        cursor.execute(" SELECT name "
1569
                       " FROM tbl_microgrids "
1570
                       " WHERE id = %s ", (id_,))
1571
        if cursor.fetchone() is None:
1572
            cursor.close()
1573
            cnx.close()
1574
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1575
                                   description='API.MICROGRID_NOT_FOUND')
1576
1577
        cursor.execute(" SELECT name "
1578
                       " FROM tbl_microgrids_evchargers "
1579
                       " WHERE id = %s ", (eid,))
1580
        if cursor.fetchone() is None:
1581
            cursor.close()
1582
            cnx.close()
1583
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1584
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
1585
1586
        cursor.execute(" DELETE FROM tbl_microgrids_evchargers "
1587
                       " WHERE id = %s ", (eid,))
1588
        cnx.commit()
1589
1590
        cursor.close()
1591
        cnx.close()
1592
1593
        resp.status = falcon.HTTP_204
1594
1595
    @staticmethod
1596
    @user_logger
1597
    def on_put(req, resp, id_, eid):
1598
        """Handles PUT requests"""
1599
        admin_control(req)
1600
        try:
1601
            raw_json = req.stream.read().decode('utf-8')
1602
        except Exception as ex:
1603
            raise falcon.HTTPError(status=falcon.HTTP_400,
1604
                                   title='API.BAD_REQUEST',
1605
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1606
        if not id_.isdigit() or int(id_) <= 0:
1607
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1608
                                   description='API.INVALID_MICROGRID_ID')
1609
        if not eid.isdigit() or int(eid) <= 0:
1610
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1611
                                   description='API.INVALID_MICROGRID_EVCHARGER_ID')
1612
1613
        new_values = json.loads(raw_json)
1614
1615
        if 'name' not in new_values['data'].keys() or \
1616
                not isinstance(new_values['data']['name'], str) or \
1617
                len(str.strip(new_values['data']['name'])) == 0:
1618
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1619
                                   description='API.INVALID_MICROGRID_EVCHARGER_NAME')
1620
        name = str.strip(new_values['data']['name'])
1621
1622
        if 'power_point_id' not in new_values['data'].keys() or \
1623
                not isinstance(new_values['data']['power_point_id'], int) or \
1624
                new_values['data']['power_point_id'] <= 0:
1625
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1626
                                   description='API.INVALID_POWER_POINT_ID')
1627
        power_point_id = new_values['data']['power_point_id']
1628
1629
        if 'meter_id' not in new_values['data'].keys() or \
1630
                not isinstance(new_values['data']['meter_id'], int) or \
1631
                new_values['data']['meter_id'] <= 0:
1632
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1633
                                   description='API.INVALID_METER_ID')
1634
        meter_id = new_values['data']['meter_id']
1635
1636
        if 'rated_output_power' not in new_values['data'].keys() or \
1637
                not (isinstance(new_values['data']['rated_output_power'], float) or
1638
                     isinstance(new_values['data']['rated_output_power'], int)):
1639
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1640
                                   description='API.INVALID_RATED_OUTPUT_POWER')
1641
        rated_output_power = float(new_values['data']['rated_output_power'])
1642
1643
        cnx = mysql.connector.connect(**config.myems_system_db)
1644
        cursor = cnx.cursor()
1645
1646
        cursor.execute(" SELECT name "
1647
                       " FROM tbl_microgrids "
1648
                       " WHERE id = %s ", (id_,))
1649
        if cursor.fetchone() is None:
1650
            cursor.close()
1651
            cnx.close()
1652
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1653
                                   description='API.MICROGRID_NOT_FOUND')
1654
1655
        cursor.execute(" SELECT name "
1656
                       " FROM tbl_microgrids_evchargers "
1657
                       " WHERE id = %s ", (eid,))
1658
        if cursor.fetchone() is None:
1659
            cursor.close()
1660
            cnx.close()
1661
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1662
                                   description='API.MICROGRID_EVCHARGER_NOT_FOUND')
1663
1664
        cursor.execute(" SELECT name "
1665
                       " FROM tbl_microgrids_evchargers "
1666
                       " WHERE microgrid_id = %s AND name = %s AND id != %s ",
1667
                       (id_, name, eid))
1668
        if cursor.fetchone() is not None:
1669
            cursor.close()
1670
            cnx.close()
1671
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1672
                                   description='API.MICROGRID_EVCHARGER_NAME_IS_ALREADY_IN_USE')
1673
1674
        cursor.execute(" SELECT name "
1675
                       " FROM tbl_points "
1676
                       " WHERE id = %s ",
1677
                       (power_point_id,))
1678
        if cursor.fetchone() is None:
1679
            cursor.close()
1680
            cnx.close()
1681
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1682
                                   description='API.POWER_POINT_NOT_FOUND')
1683
1684
        cursor.execute(" SELECT name "
1685
                       " FROM tbl_meters "
1686
                       " WHERE id = %s ",
1687
                       (meter_id,))
1688
        if cursor.fetchone() is None:
1689
            cursor.close()
1690
            cnx.close()
1691
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1692
                                   description='API.METER_NOT_FOUND')
1693
1694
        update_row = (" UPDATE tbl_microgrids_evchargers "
1695
                      " SET name = %s, microgrid_id = %s, power_point_id = %s, meter_id = %s, rated_output_power = %s "
1696
                      " WHERE id = %s ")
1697
        cursor.execute(update_row, (name,
1698
                                    id_,
1699
                                    power_point_id,
1700
                                    meter_id,
1701
                                    rated_output_power,
1702
                                    eid))
1703
        cnx.commit()
1704
1705
        cursor.close()
1706
        cnx.close()
1707
1708
        resp.status = falcon.HTTP_200
1709
1710
1711
class MicrogridGeneratorCollection:

myems-api/core/energystoragecontainer.py 1 location

@@ 3713-3958 (lines=246) @@
3710
        resp.location = '/energystoragecontainers/' + str(id_) + '/loads/' + str(new_id)
3711
3712
3713
class EnergyStorageContainerLoadItem:
3714
    def __init__(self):
3715
        """Initializes Class"""
3716
        pass
3717
3718
    @staticmethod
3719
    def on_options(req, resp, id_, lid):
3720
        resp.status = falcon.HTTP_200
3721
3722
    @staticmethod
3723
    def on_get(req, resp, id_, lid):
3724
        access_control(req)
3725
        if not id_.isdigit() or int(id_) <= 0:
3726
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3727
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3728
        if not lid.isdigit() or int(lid) <= 0:
3729
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3730
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_LOAD_ID')
3731
3732
        cnx = mysql.connector.connect(**config.myems_system_db)
3733
        cursor = cnx.cursor()
3734
3735
        cursor.execute(" SELECT name "
3736
                       " FROM tbl_energy_storage_containers "
3737
                       " WHERE id = %s ", (id_,))
3738
        if cursor.fetchone() is None:
3739
            cursor.close()
3740
            cnx.close()
3741
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3742
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
3743
3744
        query = (" SELECT id, name, uuid "
3745
                 " FROM tbl_energy_storage_containers ")
3746
        cursor.execute(query)
3747
        rows_energystoragecontainers = cursor.fetchall()
3748
3749
        energy_storage_container_dict = dict()
3750
        if rows_energystoragecontainers is not None and len(rows_energystoragecontainers) > 0:
3751
            for row in rows_energystoragecontainers:
3752
                energy_storage_container_dict[row[0]] = {"id": row[0],
3753
                                                         "name": row[1],
3754
                                                         "uuid": row[2]}
3755
        # query meter dict
3756
        query = (" SELECT id, name, uuid "
3757
                 " FROM tbl_meters ")
3758
        cursor.execute(query)
3759
        rows_meters = cursor.fetchall()
3760
3761
        meter_dict = dict()
3762
        if rows_meters is not None and len(rows_meters) > 0:
3763
            for row in rows_meters:
3764
                meter_dict[row[0]] = {"id": row[0],
3765
                                      "name": row[1],
3766
                                      "uuid": row[2]}
3767
        # query point dict
3768
        query = (" SELECT id, name "
3769
                 " FROM tbl_points ")
3770
        cursor.execute(query)
3771
        rows_points = cursor.fetchall()
3772
3773
        point_dict = dict()
3774
        if rows_points is not None and len(rows_points) > 0:
3775
            for row in rows_points:
3776
                point_dict[row[0]] = {"id": row[0],
3777
                                      "name": row[1]}
3778
3779
        query = (" SELECT id, name, uuid, "
3780
                 "        energy_storage_container_id, power_point_id, meter_id, rated_input_power "
3781
                 " FROM tbl_energy_storage_containers_loads "
3782
                 " WHERE id = %s ")
3783
        cursor.execute(query, (lid,))
3784
        row = cursor.fetchone()
3785
        cursor.close()
3786
        cnx.close()
3787
3788
        if row is None:
3789
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3790
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NOT_FOUND')
3791
        else:
3792
            meta_result = {"id": row[0],
3793
                           "name": row[1],
3794
                           "uuid": row[2],
3795
                           "energy_storage_container": energy_storage_container_dict.get(row[3]),
3796
                           "power_point": point_dict.get(row[4]),
3797
                           "meter": meter_dict.get(row[5]),
3798
                           "rated_input_power": row[6]
3799
                           }
3800
3801
        resp.text = json.dumps(meta_result)
3802
3803
    @staticmethod
3804
    @user_logger
3805
    def on_delete(req, resp, id_, lid):
3806
        admin_control(req)
3807
        if not id_.isdigit() or int(id_) <= 0:
3808
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3809
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3810
        if not lid.isdigit() or int(lid) <= 0:
3811
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3812
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_LOAD_ID')
3813
3814
        cnx = mysql.connector.connect(**config.myems_system_db)
3815
        cursor = cnx.cursor()
3816
3817
        cursor.execute(" SELECT name "
3818
                       " FROM tbl_energy_storage_containers "
3819
                       " WHERE id = %s ", (id_,))
3820
        if cursor.fetchone() is None:
3821
            cursor.close()
3822
            cnx.close()
3823
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3824
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
3825
3826
        cursor.execute(" SELECT name "
3827
                       " FROM tbl_energy_storage_containers_loads "
3828
                       " WHERE id = %s ", (lid,))
3829
        if cursor.fetchone() is None:
3830
            cursor.close()
3831
            cnx.close()
3832
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3833
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NOT_FOUND')
3834
3835
        cursor.execute(" DELETE FROM tbl_energy_storage_containers_loads "
3836
                       " WHERE id = %s ", (lid,))
3837
        cnx.commit()
3838
3839
        cursor.close()
3840
        cnx.close()
3841
3842
        resp.status = falcon.HTTP_204
3843
3844
    @staticmethod
3845
    @user_logger
3846
    def on_put(req, resp, id_, lid):
3847
        """Handles PUT requests"""
3848
        admin_control(req)
3849
        try:
3850
            raw_json = req.stream.read().decode('utf-8')
3851
        except Exception as ex:
3852
            raise falcon.HTTPError(status=falcon.HTTP_400,
3853
                                   title='API.BAD_REQUEST',
3854
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3855
        if not id_.isdigit() or int(id_) <= 0:
3856
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3857
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3858
        if not lid.isdigit() or int(lid) <= 0:
3859
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3860
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_LOAD_ID')
3861
3862
        new_values = json.loads(raw_json)
3863
3864
        if 'name' not in new_values['data'].keys() or \
3865
                not isinstance(new_values['data']['name'], str) or \
3866
                len(str.strip(new_values['data']['name'])) == 0:
3867
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3868
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_LOAD_NAME')
3869
        name = str.strip(new_values['data']['name'])
3870
3871
        if 'power_point_id' not in new_values['data'].keys() or \
3872
                not isinstance(new_values['data']['power_point_id'], int) or \
3873
                new_values['data']['power_point_id'] <= 0:
3874
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3875
                                   description='API.INVALID_POWER_POINT_ID')
3876
        power_point_id = new_values['data']['power_point_id']
3877
3878
        if 'meter_id' not in new_values['data'].keys() or \
3879
                not isinstance(new_values['data']['meter_id'], int) or \
3880
                new_values['data']['meter_id'] <= 0:
3881
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3882
                                   description='API.INVALID_METER_ID')
3883
        meter_id = new_values['data']['meter_id']
3884
3885
        if 'rated_input_power' not in new_values['data'].keys() or \
3886
                not (isinstance(new_values['data']['rated_input_power'], float) or
3887
                     isinstance(new_values['data']['rated_input_power'], int)):
3888
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3889
                                   description='API.INVALID_RATED_INPUT_POWER')
3890
        rated_input_power = Decimal(new_values['data']['rated_input_power'])
3891
3892
        cnx = mysql.connector.connect(**config.myems_system_db)
3893
        cursor = cnx.cursor()
3894
3895
        cursor.execute(" SELECT name "
3896
                       " FROM tbl_energy_storage_containers "
3897
                       " WHERE id = %s ", (id_,))
3898
        if cursor.fetchone() is None:
3899
            cursor.close()
3900
            cnx.close()
3901
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3902
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
3903
3904
        cursor.execute(" SELECT name "
3905
                       " FROM tbl_energy_storage_containers_loads "
3906
                       " WHERE id = %s ", (lid,))
3907
        if cursor.fetchone() is None:
3908
            cursor.close()
3909
            cnx.close()
3910
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3911
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NOT_FOUND')
3912
3913
        cursor.execute(" SELECT name "
3914
                       " FROM tbl_energy_storage_containers_loads "
3915
                       " WHERE energy_storage_container_id = %s AND name = %s AND id != %s ",
3916
                       (id_, name, lid))
3917
        if cursor.fetchone() is not None:
3918
            cursor.close()
3919
            cnx.close()
3920
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3921
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NAME_IS_ALREADY_IN_USE')
3922
3923
        cursor.execute(" SELECT name "
3924
                       " FROM tbl_points "
3925
                       " WHERE id = %s ",
3926
                       (power_point_id,))
3927
        if cursor.fetchone() is None:
3928
            cursor.close()
3929
            cnx.close()
3930
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3931
                                   description='API.POWER_POINT_NOT_FOUND')
3932
3933
        cursor.execute(" SELECT name "
3934
                       " FROM tbl_meters "
3935
                       " WHERE id = %s ",
3936
                       (meter_id,))
3937
        if cursor.fetchone() is None:
3938
            cursor.close()
3939
            cnx.close()
3940
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3941
                                   description='API.METER_NOT_FOUND')
3942
3943
        update_row = (" UPDATE tbl_energy_storage_containers_loads "
3944
                      " SET name = %s, energy_storage_container_id = %s, power_point_id = %s, "
3945
                      "     meter_id = %s, rated_input_power = %s "
3946
                      " WHERE id = %s ")
3947
        cursor.execute(update_row, (name,
3948
                                    id_,
3949
                                    power_point_id,
3950
                                    meter_id,
3951
                                    rated_input_power,
3952
                                    lid))
3953
        cnx.commit()
3954
3955
        cursor.close()
3956
        cnx.close()
3957
3958
        resp.status = falcon.HTTP_200
3959
3960
3961
class EnergyStorageContainerLoadPointCollection: