Code Duplication    Length = 192-194 lines in 5 locations

myems-api/core/microgrid.py 4 locations

@@ 3634-3826 (lines=193) @@
3631
        resp.status = falcon.HTTP_200
3632
3633
3634
class MicrogridPhotovoltaicCollection:
3635
    def __init__(self):
3636
        """Initializes MicrogridPhotovoltaicCollection"""
3637
        pass
3638
3639
    @staticmethod
3640
    def on_options(req, resp, id_):
3641
        _ = req
3642
        resp.status = falcon.HTTP_200
3643
        _ = id_
3644
3645
    @staticmethod
3646
    def on_get(req, resp, id_):
3647
        access_control(req)
3648
        if not id_.isdigit() or int(id_) <= 0:
3649
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3650
                                   description='API.INVALID_MICROGRID_ID')
3651
3652
        cnx = mysql.connector.connect(**config.myems_system_db)
3653
        cursor = cnx.cursor()
3654
3655
        cursor.execute(" SELECT name "
3656
                       " FROM tbl_microgrids "
3657
                       " WHERE id = %s ", (id_,))
3658
        if cursor.fetchone() is None:
3659
            cursor.close()
3660
            cnx.close()
3661
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3662
                                   description='API.MICROGRID_NOT_FOUND')
3663
3664
        # query meter dict
3665
        query = (" SELECT id, name, uuid "
3666
                 " FROM tbl_meters ")
3667
        cursor.execute(query)
3668
        rows_meters = cursor.fetchall()
3669
3670
        meter_dict = dict()
3671
        if rows_meters is not None and len(rows_meters) > 0:
3672
            for row in rows_meters:
3673
                meter_dict[row[0]] = {"id": row[0],
3674
                                      "name": row[1],
3675
                                      "uuid": row[2]}
3676
        # query point dict
3677
        query = (" SELECT id, name "
3678
                 " FROM tbl_points ")
3679
        cursor.execute(query)
3680
        rows_points = cursor.fetchall()
3681
3682
        point_dict = dict()
3683
        if rows_points is not None and len(rows_points) > 0:
3684
            for row in rows_points:
3685
                point_dict[row[0]] = {"id": row[0],
3686
                                      "name": row[1]}
3687
3688
        query = (" SELECT id, name, uuid, "
3689
                 "        power_point_id, meter_id, rated_power "
3690
                 " FROM tbl_microgrids_photovoltaics "
3691
                 " WHERE microgrid_id = %s "
3692
                 " ORDER BY name ")
3693
        cursor.execute(query, (id_,))
3694
        rows = cursor.fetchall()
3695
3696
        result = list()
3697
        if rows is not None and len(rows) > 0:
3698
            for row in rows:
3699
                meta_result = {"id": row[0],
3700
                               "name": row[1],
3701
                               "uuid": row[2],
3702
                               "power_point": point_dict.get(row[3], None),
3703
                               "meter": meter_dict.get(row[4], None),
3704
                               "rated_power": row[5],
3705
                               }
3706
                result.append(meta_result)
3707
3708
        resp.text = json.dumps(result)
3709
3710
    @staticmethod
3711
    @user_logger
3712
    def on_post(req, resp, id_):
3713
        """Handles POST requests"""
3714
        admin_control(req)
3715
        try:
3716
            raw_json = req.stream.read().decode('utf-8')
3717
        except Exception as ex:
3718
            print(str(ex))
3719
            raise falcon.HTTPError(status=falcon.HTTP_400,
3720
                                   title='API.BAD_REQUEST',
3721
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3722
        if not id_.isdigit() or int(id_) <= 0:
3723
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3724
                                   description='API.INVALID_MICROGRID_ID')
3725
3726
        cnx = mysql.connector.connect(**config.myems_system_db)
3727
        cursor = cnx.cursor()
3728
3729
        cursor.execute(" SELECT name "
3730
                       " FROM tbl_microgrids "
3731
                       " WHERE id = %s ", (id_,))
3732
        if cursor.fetchone() is None:
3733
            cursor.close()
3734
            cnx.close()
3735
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3736
                                   description='API.MICROGRID_NOT_FOUND')
3737
3738
        new_values = json.loads(raw_json)
3739
3740
        if 'name' not in new_values['data'].keys() or \
3741
                not isinstance(new_values['data']['name'], str) or \
3742
                len(str.strip(new_values['data']['name'])) == 0:
3743
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3744
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_NAME')
3745
        name = str.strip(new_values['data']['name'])
3746
3747
        if 'power_point_id' not in new_values['data'].keys() or \
3748
                not isinstance(new_values['data']['power_point_id'], int) or \
3749
                new_values['data']['power_point_id'] <= 0:
3750
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3751
                                   description='API.INVALID_POWER_POINT_ID')
3752
        power_point_id = new_values['data']['power_point_id']
3753
3754
        if 'meter_id' not in new_values['data'].keys() or \
3755
                not isinstance(new_values['data']['meter_id'], int) or \
3756
                new_values['data']['meter_id'] <= 0:
3757
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3758
                                   description='API.INVALID_METER_ID')
3759
        meter_id = new_values['data']['meter_id']
3760
3761
        if 'rated_power' not in new_values['data'].keys() or \
3762
                not (isinstance(new_values['data']['rated_power'], float) or
3763
                     isinstance(new_values['data']['rated_power'], int)):
3764
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3765
                                   description='API.INVALID_RATED_POWER')
3766
        rated_power = float(new_values['data']['rated_power'])
3767
3768
        cnx = mysql.connector.connect(**config.myems_system_db)
3769
        cursor = cnx.cursor()
3770
3771
        cursor.execute(" SELECT name "
3772
                       " FROM tbl_microgrids "
3773
                       " WHERE id = %s ",
3774
                       (id_,))
3775
        if cursor.fetchone() is None:
3776
            cursor.close()
3777
            cnx.close()
3778
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3779
                                   description='API.MICROGRID_NOT_FOUND')
3780
3781
        cursor.execute(" SELECT name "
3782
                       " FROM tbl_microgrids_photovoltaics "
3783
                       " WHERE microgrid_id = %s AND name = %s ",
3784
                       (id_, name,))
3785
        if cursor.fetchone() is not None:
3786
            cursor.close()
3787
            cnx.close()
3788
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3789
                                   description='API.MICROGRID_PHOTOVOLTAIC_NAME_IS_ALREADY_IN_USE')
3790
3791
        cursor.execute(" SELECT name "
3792
                       " FROM tbl_points "
3793
                       " WHERE id = %s ",
3794
                       (power_point_id,))
3795
        if cursor.fetchone() is None:
3796
            cursor.close()
3797
            cnx.close()
3798
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3799
                                   description='API.POWER_POINT_NOT_FOUND')
3800
3801
        cursor.execute(" SELECT name "
3802
                       " FROM tbl_meters "
3803
                       " WHERE id = %s ",
3804
                       (meter_id,))
3805
        if cursor.fetchone() is None:
3806
            cursor.close()
3807
            cnx.close()
3808
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3809
                                   description='API.METER_NOT_FOUND')
3810
3811
        add_values = (" INSERT INTO tbl_microgrids_photovoltaics "
3812
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_power) "
3813
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
3814
        cursor.execute(add_values, (name,
3815
                                    str(uuid.uuid4()),
3816
                                    id_,
3817
                                    power_point_id,
3818
                                    meter_id,
3819
                                    rated_power))
3820
        new_id = cursor.lastrowid
3821
        cnx.commit()
3822
        cursor.close()
3823
        cnx.close()
3824
3825
        resp.status = falcon.HTTP_201
3826
        resp.location = '/microgrids' + str(id_) + '/photovoltaics/' + str(new_id)
3827
3828
3829
class MicrogridPhotovoltaicItem:
@@ 1299-1491 (lines=193) @@
1296
        resp.text = json.dumps(result)
1297
1298
1299
class MicrogridEVChargerCollection:
1300
    def __init__(self):
1301
        """Initializes MicrogridEVChargerCollection"""
1302
        pass
1303
1304
    @staticmethod
1305
    def on_options(req, resp, id_):
1306
        _ = req
1307
        resp.status = falcon.HTTP_200
1308
        _ = id_
1309
1310
    @staticmethod
1311
    def on_get(req, resp, id_):
1312
        access_control(req)
1313
        if not id_.isdigit() or int(id_) <= 0:
1314
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1315
                                   description='API.INVALID_MICROGRID_ID')
1316
1317
        cnx = mysql.connector.connect(**config.myems_system_db)
1318
        cursor = cnx.cursor()
1319
1320
        cursor.execute(" SELECT name "
1321
                       " FROM tbl_microgrids "
1322
                       " WHERE id = %s ", (id_,))
1323
        if cursor.fetchone() is None:
1324
            cursor.close()
1325
            cnx.close()
1326
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1327
                                   description='API.MICROGRID_NOT_FOUND')
1328
1329
        # query meter dict
1330
        query = (" SELECT id, name, uuid "
1331
                 " FROM tbl_meters ")
1332
        cursor.execute(query)
1333
        rows_meters = cursor.fetchall()
1334
1335
        meter_dict = dict()
1336
        if rows_meters is not None and len(rows_meters) > 0:
1337
            for row in rows_meters:
1338
                meter_dict[row[0]] = {"id": row[0],
1339
                                      "name": row[1],
1340
                                      "uuid": row[2]}
1341
        # query point dict
1342
        query = (" SELECT id, name "
1343
                 " FROM tbl_points ")
1344
        cursor.execute(query)
1345
        rows_points = cursor.fetchall()
1346
1347
        point_dict = dict()
1348
        if rows_points is not None and len(rows_points) > 0:
1349
            for row in rows_points:
1350
                point_dict[row[0]] = {"id": row[0],
1351
                                      "name": row[1]}
1352
1353
        query = (" SELECT id, name, uuid, "
1354
                 "       power_point_id, meter_id, rated_output_power "
1355
                 " FROM tbl_microgrids_evchargers "
1356
                 " WHERE microgrid_id = %s "
1357
                 " ORDER BY name ")
1358
        cursor.execute(query, (id_,))
1359
        rows = cursor.fetchall()
1360
1361
        result = list()
1362
        if rows is not None and len(rows) > 0:
1363
            for row in rows:
1364
                meta_result = {"id": row[0],
1365
                               "name": row[1],
1366
                               "uuid": row[2],
1367
                               "power_point": point_dict.get(row[3]),
1368
                               "meter": meter_dict.get(row[4]),
1369
                               "rated_output_power": row[5]}
1370
                result.append(meta_result)
1371
1372
        resp.text = json.dumps(result)
1373
1374
    @staticmethod
1375
    @user_logger
1376
    def on_post(req, resp, id_):
1377
        """Handles POST requests"""
1378
        admin_control(req)
1379
        try:
1380
            raw_json = req.stream.read().decode('utf-8')
1381
        except Exception as ex:
1382
            print(str(ex))
1383
            raise falcon.HTTPError(status=falcon.HTTP_400,
1384
                                   title='API.BAD_REQUEST',
1385
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1386
1387
        if not id_.isdigit() or int(id_) <= 0:
1388
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1389
                                   description='API.INVALID_MICROGRID_ID')
1390
1391
        cnx = mysql.connector.connect(**config.myems_system_db)
1392
        cursor = cnx.cursor()
1393
1394
        cursor.execute(" SELECT name "
1395
                       " FROM tbl_microgrids "
1396
                       " WHERE id = %s ", (id_,))
1397
        if cursor.fetchone() is None:
1398
            cursor.close()
1399
            cnx.close()
1400
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1401
                                   description='API.MICROGRID_NOT_FOUND')
1402
1403
        new_values = json.loads(raw_json)
1404
1405
        if 'name' not in new_values['data'].keys() or \
1406
                not isinstance(new_values['data']['name'], str) or \
1407
                len(str.strip(new_values['data']['name'])) == 0:
1408
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1409
                                   description='API.INVALID_MICROGRID_EVCHARGER_NAME')
1410
        name = str.strip(new_values['data']['name'])
1411
1412
        if 'power_point_id' not in new_values['data'].keys() or \
1413
                not isinstance(new_values['data']['power_point_id'], int) or \
1414
                new_values['data']['power_point_id'] <= 0:
1415
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1416
                                   description='API.INVALID_POWER_POINT_ID')
1417
        power_point_id = new_values['data']['power_point_id']
1418
1419
        if 'meter_id' not in new_values['data'].keys() or \
1420
                not isinstance(new_values['data']['meter_id'], int) or \
1421
                new_values['data']['meter_id'] <= 0:
1422
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1423
                                   description='API.INVALID_METER_ID')
1424
        meter_id = new_values['data']['meter_id']
1425
1426
        if 'rated_output_power' not in new_values['data'].keys() or \
1427
                not (isinstance(new_values['data']['rated_output_power'], float) or
1428
                     isinstance(new_values['data']['rated_output_power'], int)):
1429
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1430
                                   description='API.INVALID_RATED_OUTPUT_POWER')
1431
        rated_output_power = float(new_values['data']['rated_output_power'])
1432
1433
        cnx = mysql.connector.connect(**config.myems_system_db)
1434
        cursor = cnx.cursor()
1435
1436
        cursor.execute(" SELECT name "
1437
                       " FROM tbl_microgrids "
1438
                       " WHERE id = %s ",
1439
                       (id_,))
1440
        if cursor.fetchone() is None:
1441
            cursor.close()
1442
            cnx.close()
1443
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1444
                                   description='API.MICROGRID_NOT_FOUND')
1445
1446
        cursor.execute(" SELECT name "
1447
                       " FROM tbl_microgrids_evchargers "
1448
                       " WHERE microgrid_id = %s AND name = %s ",
1449
                       (id_, name,))
1450
        if cursor.fetchone() is not None:
1451
            cursor.close()
1452
            cnx.close()
1453
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1454
                                   description='API.MICROGRID_EVCHARGER_NAME_IS_ALREADY_IN_USE')
1455
1456
        cursor.execute(" SELECT name "
1457
                       " FROM tbl_points "
1458
                       " WHERE id = %s ",
1459
                       (power_point_id,))
1460
        if cursor.fetchone() is None:
1461
            cursor.close()
1462
            cnx.close()
1463
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1464
                                   description='API.POWER_POINT_NOT_FOUND')
1465
1466
        cursor.execute(" SELECT name "
1467
                       " FROM tbl_meters "
1468
                       " WHERE id = %s ",
1469
                       (meter_id,))
1470
        if cursor.fetchone() is None:
1471
            cursor.close()
1472
            cnx.close()
1473
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1474
                                   description='API.METER_NOT_FOUND')
1475
1476
        add_values = (" INSERT INTO tbl_microgrids_evchargers "
1477
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power) "
1478
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
1479
        cursor.execute(add_values, (name,
1480
                                    str(uuid.uuid4()),
1481
                                    id_,
1482
                                    power_point_id,
1483
                                    meter_id,
1484
                                    rated_output_power))
1485
        new_id = cursor.lastrowid
1486
        cnx.commit()
1487
        cursor.close()
1488
        cnx.close()
1489
1490
        resp.status = falcon.HTTP_201
1491
        resp.location = '/microgrids/' + id_ + '/evchargers/' + str(new_id)
1492
1493
1494
class MicrogridEVChargerItem:
@@ 3191-3382 (lines=192) @@
3188
        resp.status = falcon.HTTP_200
3189
3190
3191
class MicrogridLoadCollection:
3192
    def __init__(self):
3193
        """Initializes MicrogridLoadCollection"""
3194
        pass
3195
3196
    @staticmethod
3197
    def on_options(req, resp, id_):
3198
        _ = req
3199
        resp.status = falcon.HTTP_200
3200
        _ = id_
3201
3202
    @staticmethod
3203
    def on_get(req, resp, id_):
3204
        access_control(req)
3205
        if not id_.isdigit() or int(id_) <= 0:
3206
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3207
                                   description='API.INVALID_MICROGRID_ID')
3208
3209
        cnx = mysql.connector.connect(**config.myems_system_db)
3210
        cursor = cnx.cursor()
3211
3212
        cursor.execute(" SELECT name "
3213
                       " FROM tbl_microgrids "
3214
                       " WHERE id = %s ", (id_,))
3215
        if cursor.fetchone() is None:
3216
            cursor.close()
3217
            cnx.close()
3218
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3219
                                   description='API.MICROGRID_NOT_FOUND')
3220
3221
        # query meter dict
3222
        query = (" SELECT id, name, uuid "
3223
                 " FROM tbl_meters ")
3224
        cursor.execute(query)
3225
        rows_meters = cursor.fetchall()
3226
3227
        meter_dict = dict()
3228
        if rows_meters is not None and len(rows_meters) > 0:
3229
            for row in rows_meters:
3230
                meter_dict[row[0]] = {"id": row[0],
3231
                                      "name": row[1],
3232
                                      "uuid": row[2]}
3233
        # query point dict
3234
        query = (" SELECT id, name "
3235
                 " FROM tbl_points ")
3236
        cursor.execute(query)
3237
        rows_points = cursor.fetchall()
3238
3239
        point_dict = dict()
3240
        if rows_points is not None and len(rows_points) > 0:
3241
            for row in rows_points:
3242
                point_dict[row[0]] = {"id": row[0],
3243
                                      "name": row[1]}
3244
3245
        query = (" SELECT id, name, uuid, "
3246
                 "        power_point_id, meter_id, rated_input_power "
3247
                 " FROM tbl_microgrids_loads "
3248
                 " WHERE microgrid_id = %s "
3249
                 " ORDER BY name ")
3250
        cursor.execute(query, (id_,))
3251
        rows = cursor.fetchall()
3252
3253
        result = list()
3254
        if rows is not None and len(rows) > 0:
3255
            for row in rows:
3256
                meta_result = {"id": row[0],
3257
                               "name": row[1],
3258
                               "uuid": row[2],
3259
                               "power_point": point_dict.get(row[3], None),
3260
                               "meter": meter_dict.get(row[4], None),
3261
                               "rated_input_power": row[5]}
3262
                result.append(meta_result)
3263
3264
        resp.text = json.dumps(result)
3265
3266
    @staticmethod
3267
    @user_logger
3268
    def on_post(req, resp, id_):
3269
        """Handles POST requests"""
3270
        admin_control(req)
3271
        try:
3272
            raw_json = req.stream.read().decode('utf-8')
3273
        except Exception as ex:
3274
            print(str(ex))
3275
            raise falcon.HTTPError(status=falcon.HTTP_400,
3276
                                   title='API.BAD_REQUEST',
3277
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3278
        if not id_.isdigit() or int(id_) <= 0:
3279
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3280
                                   description='API.INVALID_MICROGRID_ID')
3281
3282
        cnx = mysql.connector.connect(**config.myems_system_db)
3283
        cursor = cnx.cursor()
3284
3285
        cursor.execute(" SELECT name "
3286
                       " FROM tbl_microgrids "
3287
                       " WHERE id = %s ", (id_,))
3288
        if cursor.fetchone() is None:
3289
            cursor.close()
3290
            cnx.close()
3291
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3292
                                   description='API.MICROGRID_NOT_FOUND')
3293
3294
        new_values = json.loads(raw_json)
3295
3296
        if 'name' not in new_values['data'].keys() or \
3297
                not isinstance(new_values['data']['name'], str) or \
3298
                len(str.strip(new_values['data']['name'])) == 0:
3299
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3300
                                   description='API.INVALID_MICROGRID_LOAD_NAME')
3301
        name = str.strip(new_values['data']['name'])
3302
3303
        if 'power_point_id' not in new_values['data'].keys() or \
3304
                not isinstance(new_values['data']['power_point_id'], int) or \
3305
                new_values['data']['power_point_id'] <= 0:
3306
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3307
                                   description='API.INVALID_POWER_POINT_ID')
3308
        power_point_id = new_values['data']['power_point_id']
3309
3310
        if 'meter_id' not in new_values['data'].keys() or \
3311
                not isinstance(new_values['data']['meter_id'], int) or \
3312
                new_values['data']['meter_id'] <= 0:
3313
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3314
                                   description='API.INVALID_METER_ID')
3315
        meter_id = new_values['data']['meter_id']
3316
3317
        if 'rated_input_power' not in new_values['data'].keys() or \
3318
                not (isinstance(new_values['data']['rated_input_power'], float) or
3319
                     isinstance(new_values['data']['rated_input_power'], int)):
3320
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3321
                                   description='API.INVALID_RATED_INPUT_POWER')
3322
        rated_input_power = float(new_values['data']['rated_input_power'])
3323
3324
        cnx = mysql.connector.connect(**config.myems_system_db)
3325
        cursor = cnx.cursor()
3326
3327
        cursor.execute(" SELECT name "
3328
                       " FROM tbl_microgrids "
3329
                       " WHERE id = %s ",
3330
                       (id_,))
3331
        if cursor.fetchone() is None:
3332
            cursor.close()
3333
            cnx.close()
3334
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3335
                                   description='API.MICROGRID_NOT_FOUND')
3336
3337
        cursor.execute(" SELECT name "
3338
                       " FROM tbl_microgrids_loads "
3339
                       " WHERE microgrid_id = %s AND name = %s ",
3340
                       (id_, name,))
3341
        if cursor.fetchone() is not None:
3342
            cursor.close()
3343
            cnx.close()
3344
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3345
                                   description='API.MICROGRID_LOAD_NAME_IS_ALREADY_IN_USE')
3346
3347
        cursor.execute(" SELECT name "
3348
                       " FROM tbl_points "
3349
                       " WHERE id = %s ",
3350
                       (power_point_id,))
3351
        if cursor.fetchone() is None:
3352
            cursor.close()
3353
            cnx.close()
3354
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3355
                                   description='API.POWER_POINT_NOT_FOUND')
3356
3357
        cursor.execute(" SELECT name "
3358
                       " FROM tbl_meters "
3359
                       " WHERE id = %s ",
3360
                       (meter_id,))
3361
        if cursor.fetchone() is None:
3362
            cursor.close()
3363
            cnx.close()
3364
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3365
                                   description='API.METER_NOT_FOUND')
3366
3367
        add_values = (" INSERT INTO tbl_microgrids_loads "
3368
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_input_power) "
3369
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
3370
        cursor.execute(add_values, (name,
3371
                                    str(uuid.uuid4()),
3372
                                    id_,
3373
                                    power_point_id,
3374
                                    meter_id,
3375
                                    rated_input_power))
3376
        new_id = cursor.lastrowid
3377
        cnx.commit()
3378
        cursor.close()
3379
        cnx.close()
3380
3381
        resp.status = falcon.HTTP_201
3382
        resp.location = '/microgrids/' + str(id_) + '/loads/' + str(new_id)
3383
3384
3385
class MicrogridLoadItem:
@@ 1742-1933 (lines=192) @@
1739
        resp.status = falcon.HTTP_200
1740
1741
1742
class MicrogridGeneratorCollection:
1743
    def __init__(self):
1744
        """Initializes MicrogridGeneratorCollection"""
1745
        pass
1746
1747
    @staticmethod
1748
    def on_options(req, resp, id_):
1749
        _ = req
1750
        resp.status = falcon.HTTP_200
1751
        _ = id_
1752
1753
    @staticmethod
1754
    def on_get(req, resp, id_):
1755
        access_control(req)
1756
        if not id_.isdigit() or int(id_) <= 0:
1757
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1758
                                   description='API.INVALID_MICROGRID_ID')
1759
1760
        cnx = mysql.connector.connect(**config.myems_system_db)
1761
        cursor = cnx.cursor()
1762
1763
        cursor.execute(" SELECT name "
1764
                       " FROM tbl_microgrids "
1765
                       " WHERE id = %s ", (id_,))
1766
        if cursor.fetchone() is None:
1767
            cursor.close()
1768
            cnx.close()
1769
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1770
                                   description='API.MICROGRID_NOT_FOUND')
1771
1772
        # query meter dict
1773
        query = (" SELECT id, name, uuid "
1774
                 " FROM tbl_meters ")
1775
        cursor.execute(query)
1776
        rows_meters = cursor.fetchall()
1777
1778
        meter_dict = dict()
1779
        if rows_meters is not None and len(rows_meters) > 0:
1780
            for row in rows_meters:
1781
                meter_dict[row[0]] = {"id": row[0],
1782
                                      "name": row[1],
1783
                                      "uuid": row[2]}
1784
        # query point dict
1785
        query = (" SELECT id, name "
1786
                 " FROM tbl_points ")
1787
        cursor.execute(query)
1788
        rows_points = cursor.fetchall()
1789
1790
        point_dict = dict()
1791
        if rows_points is not None and len(rows_points) > 0:
1792
            for row in rows_points:
1793
                point_dict[row[0]] = {"id": row[0],
1794
                                      "name": row[1]}
1795
1796
        query = (" SELECT id, name, uuid, "
1797
                 "        power_point_id, meter_id, rated_output_power "
1798
                 " FROM tbl_microgrids_generators "
1799
                 " WHERE microgrid_id = %s "
1800
                 " ORDER BY name ")
1801
        cursor.execute(query, (id_,))
1802
        rows = cursor.fetchall()
1803
1804
        result = list()
1805
        if rows is not None and len(rows) > 0:
1806
            for row in rows:
1807
                meta_result = {"id": row[0],
1808
                               "name": row[1],
1809
                               "uuid": row[2],
1810
                               "power_point": point_dict.get(row[3]),
1811
                               "meter": meter_dict.get(row[4]),
1812
                               "rated_output_power": row[5]}
1813
                result.append(meta_result)
1814
1815
        resp.text = json.dumps(result)
1816
1817
    @staticmethod
1818
    @user_logger
1819
    def on_post(req, resp, id_):
1820
        """Handles POST requests"""
1821
        admin_control(req)
1822
        try:
1823
            raw_json = req.stream.read().decode('utf-8')
1824
        except Exception as ex:
1825
            print(str(ex))
1826
            raise falcon.HTTPError(status=falcon.HTTP_400,
1827
                                   title='API.BAD_REQUEST',
1828
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1829
        if not id_.isdigit() or int(id_) <= 0:
1830
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1831
                                   description='API.INVALID_MICROGRID_ID')
1832
1833
        cnx = mysql.connector.connect(**config.myems_system_db)
1834
        cursor = cnx.cursor()
1835
1836
        cursor.execute(" SELECT name "
1837
                       " FROM tbl_microgrids "
1838
                       " WHERE id = %s ", (id_,))
1839
        if cursor.fetchone() is None:
1840
            cursor.close()
1841
            cnx.close()
1842
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1843
                                   description='API.MICROGRID_NOT_FOUND')
1844
1845
        new_values = json.loads(raw_json)
1846
1847
        if 'name' not in new_values['data'].keys() or \
1848
                not isinstance(new_values['data']['name'], str) or \
1849
                len(str.strip(new_values['data']['name'])) == 0:
1850
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1851
                                   description='API.INVALID_MICROGRID_GENERATOR_NAME')
1852
        name = str.strip(new_values['data']['name'])
1853
1854
        if 'power_point_id' not in new_values['data'].keys() or \
1855
                not isinstance(new_values['data']['power_point_id'], int) or \
1856
                new_values['data']['power_point_id'] <= 0:
1857
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1858
                                   description='API.INVALID_POWER_POINT_ID')
1859
        power_point_id = new_values['data']['power_point_id']
1860
1861
        if 'meter_id' not in new_values['data'].keys() or \
1862
                not isinstance(new_values['data']['meter_id'], int) or \
1863
                new_values['data']['meter_id'] <= 0:
1864
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1865
                                   description='API.INVALID_METER_ID')
1866
        meter_id = new_values['data']['meter_id']
1867
1868
        if 'rated_output_power' not in new_values['data'].keys() or \
1869
                not (isinstance(new_values['data']['rated_output_power'], float) or
1870
                     isinstance(new_values['data']['rated_output_power'], int)):
1871
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1872
                                   description='API.INVALID_RATED_OUTPUT_POWER')
1873
        rated_output_power = float(new_values['data']['rated_output_power'])
1874
1875
        cnx = mysql.connector.connect(**config.myems_system_db)
1876
        cursor = cnx.cursor()
1877
1878
        cursor.execute(" SELECT name "
1879
                       " FROM tbl_microgrids "
1880
                       " WHERE id = %s ",
1881
                       (id_,))
1882
        if cursor.fetchone() is None:
1883
            cursor.close()
1884
            cnx.close()
1885
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1886
                                   description='API.MICROGRID_NOT_FOUND')
1887
1888
        cursor.execute(" SELECT name "
1889
                       " FROM tbl_microgrids_generators "
1890
                       " WHERE microgrid_id = %s AND name = %s ",
1891
                       (id_, name,))
1892
        if cursor.fetchone() is not None:
1893
            cursor.close()
1894
            cnx.close()
1895
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1896
                                   description='API.MICROGRID_GENERATOR_NAME_IS_ALREADY_IN_USE')
1897
1898
        cursor.execute(" SELECT name "
1899
                       " FROM tbl_points "
1900
                       " WHERE id = %s ",
1901
                       (power_point_id,))
1902
        if cursor.fetchone() is None:
1903
            cursor.close()
1904
            cnx.close()
1905
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1906
                                   description='API.POWER_POINT_NOT_FOUND')
1907
1908
        cursor.execute(" SELECT name "
1909
                       " FROM tbl_meters "
1910
                       " WHERE id = %s ",
1911
                       (meter_id,))
1912
        if cursor.fetchone() is None:
1913
            cursor.close()
1914
            cnx.close()
1915
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1916
                                   description='API.METER_NOT_FOUND')
1917
1918
        add_values = (" INSERT INTO tbl_microgrids_generators "
1919
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power) "
1920
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
1921
        cursor.execute(add_values, (name,
1922
                                    str(uuid.uuid4()),
1923
                                    id_,
1924
                                    power_point_id,
1925
                                    meter_id,
1926
                                    rated_output_power))
1927
        new_id = cursor.lastrowid
1928
        cnx.commit()
1929
        cursor.close()
1930
        cnx.close()
1931
1932
        resp.status = falcon.HTTP_201
1933
        resp.location = '/microgrids/' + str(id_) + '/generators/' + str(new_id)
1934
1935
1936
class MicrogridGeneratorItem:

myems-api/core/energystoragecontainer.py 1 location

@@ 3830-4023 (lines=194) @@
3827
        resp.status = falcon.HTTP_204
3828
3829
3830
class EnergyStorageContainerLoadCollection:
3831
    def __init__(self):
3832
        """Initializes Class"""
3833
        pass
3834
3835
    @staticmethod
3836
    def on_options(req, resp, id_):
3837
        _ = req
3838
        resp.status = falcon.HTTP_200
3839
        _ = id_
3840
3841
    @staticmethod
3842
    def on_get(req, resp, id_):
3843
        access_control(req)
3844
        if not id_.isdigit() or int(id_) <= 0:
3845
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3846
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3847
3848
        cnx = mysql.connector.connect(**config.myems_system_db)
3849
        cursor = cnx.cursor()
3850
3851
        cursor.execute(" SELECT name "
3852
                       " FROM tbl_energy_storage_containers "
3853
                       " WHERE id = %s ", (id_,))
3854
        if cursor.fetchone() is None:
3855
            cursor.close()
3856
            cnx.close()
3857
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3858
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
3859
3860
        # query meter dict
3861
        query = (" SELECT id, name, uuid "
3862
                 " FROM tbl_meters ")
3863
        cursor.execute(query)
3864
        rows_meters = cursor.fetchall()
3865
3866
        meter_dict = dict()
3867
        if rows_meters is not None and len(rows_meters) > 0:
3868
            for row in rows_meters:
3869
                meter_dict[row[0]] = {"id": row[0],
3870
                                      "name": row[1],
3871
                                      "uuid": row[2]}
3872
        # query point dict
3873
        query = (" SELECT id, name "
3874
                 " FROM tbl_points ")
3875
        cursor.execute(query)
3876
        rows_points = cursor.fetchall()
3877
3878
        point_dict = dict()
3879
        if rows_points is not None and len(rows_points) > 0:
3880
            for row in rows_points:
3881
                point_dict[row[0]] = {"id": row[0],
3882
                                      "name": row[1]}
3883
3884
        query = (" SELECT id, name, uuid, "
3885
                 "        power_point_id, meter_id, rated_input_power "
3886
                 " FROM tbl_energy_storage_containers_loads "
3887
                 " WHERE energy_storage_container_id = %s "
3888
                 " ORDER BY name ")
3889
        cursor.execute(query, (id_,))
3890
        rows = cursor.fetchall()
3891
3892
        result = list()
3893
        if rows is not None and len(rows) > 0:
3894
            for row in rows:
3895
                meta_result = {"id": row[0],
3896
                               "name": row[1],
3897
                               "uuid": row[2],
3898
                               "power_point": point_dict.get(row[3]),
3899
                               "meter": meter_dict.get(row[4]),
3900
                               "rated_input_power": row[5]
3901
                               }
3902
                result.append(meta_result)
3903
3904
        resp.text = json.dumps(result)
3905
3906
    @staticmethod
3907
    @user_logger
3908
    def on_post(req, resp, id_):
3909
        """Handles POST requests"""
3910
        admin_control(req)
3911
        try:
3912
            raw_json = req.stream.read().decode('utf-8')
3913
        except Exception as ex:
3914
            print(str(ex))
3915
            raise falcon.HTTPError(status=falcon.HTTP_400,
3916
                                   title='API.BAD_REQUEST',
3917
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3918
        if not id_.isdigit() or int(id_) <= 0:
3919
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3920
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3921
3922
        cnx = mysql.connector.connect(**config.myems_system_db)
3923
        cursor = cnx.cursor()
3924
3925
        cursor.execute(" SELECT name "
3926
                       " FROM tbl_energy_storage_containers "
3927
                       " WHERE id = %s ", (id_,))
3928
        if cursor.fetchone() is None:
3929
            cursor.close()
3930
            cnx.close()
3931
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3932
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
3933
3934
        new_values = json.loads(raw_json)
3935
3936
        if 'name' not in new_values['data'].keys() or \
3937
                not isinstance(new_values['data']['name'], str) or \
3938
                len(str.strip(new_values['data']['name'])) == 0:
3939
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3940
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_LOAD_NAME')
3941
        name = str.strip(new_values['data']['name'])
3942
3943
        if 'power_point_id' not in new_values['data'].keys() or \
3944
                not isinstance(new_values['data']['power_point_id'], int) or \
3945
                new_values['data']['power_point_id'] <= 0:
3946
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3947
                                   description='API.INVALID_POWER_POINT_ID')
3948
        power_point_id = new_values['data']['power_point_id']
3949
3950
        if 'meter_id' not in new_values['data'].keys() or \
3951
                not isinstance(new_values['data']['meter_id'], int) or \
3952
                new_values['data']['meter_id'] <= 0:
3953
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3954
                                   description='API.INVALID_METER_ID')
3955
        meter_id = new_values['data']['meter_id']
3956
3957
        if 'rated_input_power' not in new_values['data'].keys() or \
3958
                not (isinstance(new_values['data']['rated_input_power'], float) or
3959
                     isinstance(new_values['data']['rated_input_power'], int)):
3960
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3961
                                   description='API.INVALID_RATED_INPUT_POWER')
3962
        rated_input_power = Decimal(new_values['data']['rated_input_power'])
3963
3964
        cnx = mysql.connector.connect(**config.myems_system_db)
3965
        cursor = cnx.cursor()
3966
3967
        cursor.execute(" SELECT name "
3968
                       " FROM tbl_energy_storage_containers "
3969
                       " WHERE id = %s ",
3970
                       (id_,))
3971
        if cursor.fetchone() is None:
3972
            cursor.close()
3973
            cnx.close()
3974
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3975
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
3976
3977
        cursor.execute(" SELECT name "
3978
                       " FROM tbl_energy_storage_containers_loads "
3979
                       " WHERE energy_storage_container_id = %s AND name = %s ",
3980
                       (id_, name,))
3981
        if cursor.fetchone() is not None:
3982
            cursor.close()
3983
            cnx.close()
3984
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3985
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NAME_IS_ALREADY_IN_USE')
3986
3987
        cursor.execute(" SELECT name "
3988
                       " FROM tbl_points "
3989
                       " WHERE id = %s ",
3990
                       (power_point_id,))
3991
        if cursor.fetchone() is None:
3992
            cursor.close()
3993
            cnx.close()
3994
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3995
                                   description='API.POWER_POINT_NOT_FOUND')
3996
3997
        cursor.execute(" SELECT name "
3998
                       " FROM tbl_meters "
3999
                       " WHERE id = %s ",
4000
                       (meter_id,))
4001
        if cursor.fetchone() is None:
4002
            cursor.close()
4003
            cnx.close()
4004
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4005
                                   description='API.METER_NOT_FOUND')
4006
4007
        add_values = (" INSERT INTO tbl_energy_storage_containers_loads "
4008
                      "    (name, uuid, energy_storage_container_id, power_point_id, meter_id, rated_input_power) "
4009
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
4010
        cursor.execute(add_values, (name,
4011
                                    str(uuid.uuid4()),
4012
                                    id_,
4013
                                    power_point_id,
4014
                                    meter_id,
4015
                                    rated_input_power
4016
                                    ))
4017
        new_id = cursor.lastrowid
4018
        cnx.commit()
4019
        cursor.close()
4020
        cnx.close()
4021
4022
        resp.status = falcon.HTTP_201
4023
        resp.location = '/energystoragecontainers/' + str(id_) + '/loads/' + str(new_id)
4024
4025
4026
class EnergyStorageContainerLoadItem: