Code Duplication    Length = 189-191 lines in 5 locations

myems-api/core/microgrid.py 4 locations

@@ 3579-3768 (lines=190) @@
3576
        resp.status = falcon.HTTP_200
3577
3578
3579
class MicrogridPhotovoltaicCollection:
3580
    def __init__(self):
3581
        """Initializes MicrogridPhotovoltaicCollection"""
3582
        pass
3583
3584
    @staticmethod
3585
    def on_options(req, resp, id_):
3586
        resp.status = falcon.HTTP_200
3587
3588
    @staticmethod
3589
    def on_get(req, resp, id_):
3590
        access_control(req)
3591
        if not id_.isdigit() or int(id_) <= 0:
3592
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3593
                                   description='API.INVALID_MICROGRID_ID')
3594
3595
        cnx = mysql.connector.connect(**config.myems_system_db)
3596
        cursor = cnx.cursor()
3597
3598
        cursor.execute(" SELECT name "
3599
                       " FROM tbl_microgrids "
3600
                       " WHERE id = %s ", (id_,))
3601
        if cursor.fetchone() is None:
3602
            cursor.close()
3603
            cnx.close()
3604
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3605
                                   description='API.MICROGRID_NOT_FOUND')
3606
3607
        # query meter dict
3608
        query = (" SELECT id, name, uuid "
3609
                 " FROM tbl_meters ")
3610
        cursor.execute(query)
3611
        rows_meters = cursor.fetchall()
3612
3613
        meter_dict = dict()
3614
        if rows_meters is not None and len(rows_meters) > 0:
3615
            for row in rows_meters:
3616
                meter_dict[row[0]] = {"id": row[0],
3617
                                      "name": row[1],
3618
                                      "uuid": row[2]}
3619
        # query point dict
3620
        query = (" SELECT id, name "
3621
                 " FROM tbl_points ")
3622
        cursor.execute(query)
3623
        rows_points = cursor.fetchall()
3624
3625
        point_dict = dict()
3626
        if rows_points is not None and len(rows_points) > 0:
3627
            for row in rows_points:
3628
                point_dict[row[0]] = {"id": row[0],
3629
                                      "name": row[1]}
3630
3631
        query = (" SELECT id, name, uuid, "
3632
                 "        power_point_id, meter_id, rated_power "
3633
                 " FROM tbl_microgrids_photovoltaics "
3634
                 " WHERE microgrid_id = %s "
3635
                 " ORDER BY name ")
3636
        cursor.execute(query, (id_,))
3637
        rows = cursor.fetchall()
3638
3639
        result = list()
3640
        if rows is not None and len(rows) > 0:
3641
            for row in rows:
3642
                meta_result = {"id": row[0],
3643
                               "name": row[1],
3644
                               "uuid": row[2],
3645
                               "power_point": point_dict.get(row[3], None),
3646
                               "meter": meter_dict.get(row[4], None),
3647
                               "rated_power": row[5],
3648
                               }
3649
                result.append(meta_result)
3650
3651
        resp.text = json.dumps(result)
3652
3653
    @staticmethod
3654
    @user_logger
3655
    def on_post(req, resp, id_):
3656
        """Handles POST requests"""
3657
        admin_control(req)
3658
        try:
3659
            raw_json = req.stream.read().decode('utf-8')
3660
        except Exception as ex:
3661
            raise falcon.HTTPError(status=falcon.HTTP_400,
3662
                                   title='API.BAD_REQUEST',
3663
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3664
        if not id_.isdigit() or int(id_) <= 0:
3665
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3666
                                   description='API.INVALID_MICROGRID_ID')
3667
3668
        cnx = mysql.connector.connect(**config.myems_system_db)
3669
        cursor = cnx.cursor()
3670
3671
        cursor.execute(" SELECT name "
3672
                       " FROM tbl_microgrids "
3673
                       " WHERE id = %s ", (id_,))
3674
        if cursor.fetchone() is None:
3675
            cursor.close()
3676
            cnx.close()
3677
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3678
                                   description='API.MICROGRID_NOT_FOUND')
3679
3680
        new_values = json.loads(raw_json)
3681
3682
        if 'name' not in new_values['data'].keys() or \
3683
                not isinstance(new_values['data']['name'], str) or \
3684
                len(str.strip(new_values['data']['name'])) == 0:
3685
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3686
                                   description='API.INVALID_MICROGRID_PHOTOVOLTAIC_NAME')
3687
        name = str.strip(new_values['data']['name'])
3688
3689
        if 'power_point_id' not in new_values['data'].keys() or \
3690
                not isinstance(new_values['data']['power_point_id'], int) or \
3691
                new_values['data']['power_point_id'] <= 0:
3692
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3693
                                   description='API.INVALID_POWER_POINT_ID')
3694
        power_point_id = new_values['data']['power_point_id']
3695
3696
        if 'meter_id' not in new_values['data'].keys() or \
3697
                not isinstance(new_values['data']['meter_id'], int) or \
3698
                new_values['data']['meter_id'] <= 0:
3699
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3700
                                   description='API.INVALID_METER_ID')
3701
        meter_id = new_values['data']['meter_id']
3702
3703
        if 'rated_power' not in new_values['data'].keys() or \
3704
                not (isinstance(new_values['data']['rated_power'], float) or
3705
                     isinstance(new_values['data']['rated_power'], int)):
3706
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3707
                                   description='API.INVALID_RATED_POWER')
3708
        rated_power = float(new_values['data']['rated_power'])
3709
3710
        cnx = mysql.connector.connect(**config.myems_system_db)
3711
        cursor = cnx.cursor()
3712
3713
        cursor.execute(" SELECT name "
3714
                       " FROM tbl_microgrids "
3715
                       " WHERE id = %s ",
3716
                       (id_,))
3717
        if cursor.fetchone() is None:
3718
            cursor.close()
3719
            cnx.close()
3720
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3721
                                   description='API.MICROGRID_NOT_FOUND')
3722
3723
        cursor.execute(" SELECT name "
3724
                       " FROM tbl_microgrids_photovoltaics "
3725
                       " WHERE microgrid_id = %s AND name = %s ",
3726
                       (id_, name,))
3727
        if cursor.fetchone() is not None:
3728
            cursor.close()
3729
            cnx.close()
3730
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3731
                                   description='API.MICROGRID_PHOTOVOLTAIC_NAME_IS_ALREADY_IN_USE')
3732
3733
        cursor.execute(" SELECT name "
3734
                       " FROM tbl_points "
3735
                       " WHERE id = %s ",
3736
                       (power_point_id,))
3737
        if cursor.fetchone() is None:
3738
            cursor.close()
3739
            cnx.close()
3740
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3741
                                   description='API.POWER_POINT_NOT_FOUND')
3742
3743
        cursor.execute(" SELECT name "
3744
                       " FROM tbl_meters "
3745
                       " WHERE id = %s ",
3746
                       (meter_id,))
3747
        if cursor.fetchone() is None:
3748
            cursor.close()
3749
            cnx.close()
3750
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3751
                                   description='API.METER_NOT_FOUND')
3752
3753
        add_values = (" INSERT INTO tbl_microgrids_photovoltaics "
3754
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_power) "
3755
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
3756
        cursor.execute(add_values, (name,
3757
                                    str(uuid.uuid4()),
3758
                                    id_,
3759
                                    power_point_id,
3760
                                    meter_id,
3761
                                    rated_power))
3762
        new_id = cursor.lastrowid
3763
        cnx.commit()
3764
        cursor.close()
3765
        cnx.close()
3766
3767
        resp.status = falcon.HTTP_201
3768
        resp.location = '/microgrids' + str(id_) + '/photovoltaics/' + str(new_id)
3769
3770
3771
class MicrogridPhotovoltaicItem:
@@ 1274-1463 (lines=190) @@
1271
        resp.text = json.dumps(result)
1272
1273
1274
class MicrogridEVChargerCollection:
1275
    def __init__(self):
1276
        """Initializes MicrogridEVChargerCollection"""
1277
        pass
1278
1279
    @staticmethod
1280
    def on_options(req, resp, id_):
1281
        resp.status = falcon.HTTP_200
1282
1283
    @staticmethod
1284
    def on_get(req, resp, id_):
1285
        access_control(req)
1286
        if not id_.isdigit() or int(id_) <= 0:
1287
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1288
                                   description='API.INVALID_MICROGRID_ID')
1289
1290
        cnx = mysql.connector.connect(**config.myems_system_db)
1291
        cursor = cnx.cursor()
1292
1293
        cursor.execute(" SELECT name "
1294
                       " FROM tbl_microgrids "
1295
                       " WHERE id = %s ", (id_,))
1296
        if cursor.fetchone() is None:
1297
            cursor.close()
1298
            cnx.close()
1299
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1300
                                   description='API.MICROGRID_NOT_FOUND')
1301
1302
        # query meter dict
1303
        query = (" SELECT id, name, uuid "
1304
                 " FROM tbl_meters ")
1305
        cursor.execute(query)
1306
        rows_meters = cursor.fetchall()
1307
1308
        meter_dict = dict()
1309
        if rows_meters is not None and len(rows_meters) > 0:
1310
            for row in rows_meters:
1311
                meter_dict[row[0]] = {"id": row[0],
1312
                                      "name": row[1],
1313
                                      "uuid": row[2]}
1314
        # query point dict
1315
        query = (" SELECT id, name "
1316
                 " FROM tbl_points ")
1317
        cursor.execute(query)
1318
        rows_points = cursor.fetchall()
1319
1320
        point_dict = dict()
1321
        if rows_points is not None and len(rows_points) > 0:
1322
            for row in rows_points:
1323
                point_dict[row[0]] = {"id": row[0],
1324
                                      "name": row[1]}
1325
1326
        query = (" SELECT id, name, uuid, "
1327
                 "       power_point_id, meter_id, rated_output_power "
1328
                 " FROM tbl_microgrids_evchargers "
1329
                 " WHERE microgrid_id = %s "
1330
                 " ORDER BY name ")
1331
        cursor.execute(query, (id_,))
1332
        rows = cursor.fetchall()
1333
1334
        result = list()
1335
        if rows is not None and len(rows) > 0:
1336
            for row in rows:
1337
                meta_result = {"id": row[0],
1338
                               "name": row[1],
1339
                               "uuid": row[2],
1340
                               "power_point": point_dict.get(row[3]),
1341
                               "meter": meter_dict.get(row[4]),
1342
                               "rated_output_power": row[5]}
1343
                result.append(meta_result)
1344
1345
        resp.text = json.dumps(result)
1346
1347
    @staticmethod
1348
    @user_logger
1349
    def on_post(req, resp, id_):
1350
        """Handles POST requests"""
1351
        admin_control(req)
1352
        try:
1353
            raw_json = req.stream.read().decode('utf-8')
1354
        except Exception as ex:
1355
            raise falcon.HTTPError(status=falcon.HTTP_400,
1356
                                   title='API.BAD_REQUEST',
1357
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1358
1359
        if not id_.isdigit() or int(id_) <= 0:
1360
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1361
                                   description='API.INVALID_MICROGRID_ID')
1362
1363
        cnx = mysql.connector.connect(**config.myems_system_db)
1364
        cursor = cnx.cursor()
1365
1366
        cursor.execute(" SELECT name "
1367
                       " FROM tbl_microgrids "
1368
                       " WHERE id = %s ", (id_,))
1369
        if cursor.fetchone() is None:
1370
            cursor.close()
1371
            cnx.close()
1372
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1373
                                   description='API.MICROGRID_NOT_FOUND')
1374
1375
        new_values = json.loads(raw_json)
1376
1377
        if 'name' not in new_values['data'].keys() or \
1378
                not isinstance(new_values['data']['name'], str) or \
1379
                len(str.strip(new_values['data']['name'])) == 0:
1380
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1381
                                   description='API.INVALID_MICROGRID_EVCHARGER_NAME')
1382
        name = str.strip(new_values['data']['name'])
1383
1384
        if 'power_point_id' not in new_values['data'].keys() or \
1385
                not isinstance(new_values['data']['power_point_id'], int) or \
1386
                new_values['data']['power_point_id'] <= 0:
1387
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1388
                                   description='API.INVALID_POWER_POINT_ID')
1389
        power_point_id = new_values['data']['power_point_id']
1390
1391
        if 'meter_id' not in new_values['data'].keys() or \
1392
                not isinstance(new_values['data']['meter_id'], int) or \
1393
                new_values['data']['meter_id'] <= 0:
1394
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1395
                                   description='API.INVALID_METER_ID')
1396
        meter_id = new_values['data']['meter_id']
1397
1398
        if 'rated_output_power' not in new_values['data'].keys() or \
1399
                not (isinstance(new_values['data']['rated_output_power'], float) or
1400
                     isinstance(new_values['data']['rated_output_power'], int)):
1401
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1402
                                   description='API.INVALID_RATED_OUTPUT_POWER')
1403
        rated_output_power = float(new_values['data']['rated_output_power'])
1404
1405
        cnx = mysql.connector.connect(**config.myems_system_db)
1406
        cursor = cnx.cursor()
1407
1408
        cursor.execute(" SELECT name "
1409
                       " FROM tbl_microgrids "
1410
                       " WHERE id = %s ",
1411
                       (id_,))
1412
        if cursor.fetchone() is None:
1413
            cursor.close()
1414
            cnx.close()
1415
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1416
                                   description='API.MICROGRID_NOT_FOUND')
1417
1418
        cursor.execute(" SELECT name "
1419
                       " FROM tbl_microgrids_evchargers "
1420
                       " WHERE microgrid_id = %s AND name = %s ",
1421
                       (id_, name,))
1422
        if cursor.fetchone() is not None:
1423
            cursor.close()
1424
            cnx.close()
1425
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1426
                                   description='API.MICROGRID_EVCHARGER_NAME_IS_ALREADY_IN_USE')
1427
1428
        cursor.execute(" SELECT name "
1429
                       " FROM tbl_points "
1430
                       " WHERE id = %s ",
1431
                       (power_point_id,))
1432
        if cursor.fetchone() is None:
1433
            cursor.close()
1434
            cnx.close()
1435
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1436
                                   description='API.POWER_POINT_NOT_FOUND')
1437
1438
        cursor.execute(" SELECT name "
1439
                       " FROM tbl_meters "
1440
                       " WHERE id = %s ",
1441
                       (meter_id,))
1442
        if cursor.fetchone() is None:
1443
            cursor.close()
1444
            cnx.close()
1445
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1446
                                   description='API.METER_NOT_FOUND')
1447
1448
        add_values = (" INSERT INTO tbl_microgrids_evchargers "
1449
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power) "
1450
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
1451
        cursor.execute(add_values, (name,
1452
                                    str(uuid.uuid4()),
1453
                                    id_,
1454
                                    power_point_id,
1455
                                    meter_id,
1456
                                    rated_output_power))
1457
        new_id = cursor.lastrowid
1458
        cnx.commit()
1459
        cursor.close()
1460
        cnx.close()
1461
1462
        resp.status = falcon.HTTP_201
1463
        resp.location = '/microgrids/' + id_ + '/evchargers/' + str(new_id)
1464
1465
1466
class MicrogridEVChargerItem:
@@ 3142-3330 (lines=189) @@
3139
        resp.status = falcon.HTTP_200
3140
3141
3142
class MicrogridLoadCollection:
3143
    def __init__(self):
3144
        """Initializes MicrogridLoadCollection"""
3145
        pass
3146
3147
    @staticmethod
3148
    def on_options(req, resp, id_):
3149
        resp.status = falcon.HTTP_200
3150
3151
    @staticmethod
3152
    def on_get(req, resp, id_):
3153
        access_control(req)
3154
        if not id_.isdigit() or int(id_) <= 0:
3155
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3156
                                   description='API.INVALID_MICROGRID_ID')
3157
3158
        cnx = mysql.connector.connect(**config.myems_system_db)
3159
        cursor = cnx.cursor()
3160
3161
        cursor.execute(" SELECT name "
3162
                       " FROM tbl_microgrids "
3163
                       " WHERE id = %s ", (id_,))
3164
        if cursor.fetchone() is None:
3165
            cursor.close()
3166
            cnx.close()
3167
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3168
                                   description='API.MICROGRID_NOT_FOUND')
3169
3170
        # query meter dict
3171
        query = (" SELECT id, name, uuid "
3172
                 " FROM tbl_meters ")
3173
        cursor.execute(query)
3174
        rows_meters = cursor.fetchall()
3175
3176
        meter_dict = dict()
3177
        if rows_meters is not None and len(rows_meters) > 0:
3178
            for row in rows_meters:
3179
                meter_dict[row[0]] = {"id": row[0],
3180
                                      "name": row[1],
3181
                                      "uuid": row[2]}
3182
        # query point dict
3183
        query = (" SELECT id, name "
3184
                 " FROM tbl_points ")
3185
        cursor.execute(query)
3186
        rows_points = cursor.fetchall()
3187
3188
        point_dict = dict()
3189
        if rows_points is not None and len(rows_points) > 0:
3190
            for row in rows_points:
3191
                point_dict[row[0]] = {"id": row[0],
3192
                                      "name": row[1]}
3193
3194
        query = (" SELECT id, name, uuid, "
3195
                 "        power_point_id, meter_id, rated_input_power "
3196
                 " FROM tbl_microgrids_loads "
3197
                 " WHERE microgrid_id = %s "
3198
                 " ORDER BY name ")
3199
        cursor.execute(query, (id_,))
3200
        rows = cursor.fetchall()
3201
3202
        result = list()
3203
        if rows is not None and len(rows) > 0:
3204
            for row in rows:
3205
                meta_result = {"id": row[0],
3206
                               "name": row[1],
3207
                               "uuid": row[2],
3208
                               "power_point": point_dict.get(row[3], None),
3209
                               "meter": meter_dict.get(row[4], None),
3210
                               "rated_input_power": row[5]}
3211
                result.append(meta_result)
3212
3213
        resp.text = json.dumps(result)
3214
3215
    @staticmethod
3216
    @user_logger
3217
    def on_post(req, resp, id_):
3218
        """Handles POST requests"""
3219
        admin_control(req)
3220
        try:
3221
            raw_json = req.stream.read().decode('utf-8')
3222
        except Exception as ex:
3223
            raise falcon.HTTPError(status=falcon.HTTP_400,
3224
                                   title='API.BAD_REQUEST',
3225
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3226
        if not id_.isdigit() or int(id_) <= 0:
3227
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3228
                                   description='API.INVALID_MICROGRID_ID')
3229
3230
        cnx = mysql.connector.connect(**config.myems_system_db)
3231
        cursor = cnx.cursor()
3232
3233
        cursor.execute(" SELECT name "
3234
                       " FROM tbl_microgrids "
3235
                       " WHERE id = %s ", (id_,))
3236
        if cursor.fetchone() is None:
3237
            cursor.close()
3238
            cnx.close()
3239
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3240
                                   description='API.MICROGRID_NOT_FOUND')
3241
3242
        new_values = json.loads(raw_json)
3243
3244
        if 'name' not in new_values['data'].keys() or \
3245
                not isinstance(new_values['data']['name'], str) or \
3246
                len(str.strip(new_values['data']['name'])) == 0:
3247
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3248
                                   description='API.INVALID_MICROGRID_LOAD_NAME')
3249
        name = str.strip(new_values['data']['name'])
3250
3251
        if 'power_point_id' not in new_values['data'].keys() or \
3252
                not isinstance(new_values['data']['power_point_id'], int) or \
3253
                new_values['data']['power_point_id'] <= 0:
3254
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3255
                                   description='API.INVALID_POWER_POINT_ID')
3256
        power_point_id = new_values['data']['power_point_id']
3257
3258
        if 'meter_id' not in new_values['data'].keys() or \
3259
                not isinstance(new_values['data']['meter_id'], int) or \
3260
                new_values['data']['meter_id'] <= 0:
3261
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3262
                                   description='API.INVALID_METER_ID')
3263
        meter_id = new_values['data']['meter_id']
3264
3265
        if 'rated_input_power' not in new_values['data'].keys() or \
3266
                not (isinstance(new_values['data']['rated_input_power'], float) or
3267
                     isinstance(new_values['data']['rated_input_power'], int)):
3268
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3269
                                   description='API.INVALID_RATED_INPUT_POWER')
3270
        rated_input_power = float(new_values['data']['rated_input_power'])
3271
3272
        cnx = mysql.connector.connect(**config.myems_system_db)
3273
        cursor = cnx.cursor()
3274
3275
        cursor.execute(" SELECT name "
3276
                       " FROM tbl_microgrids "
3277
                       " WHERE id = %s ",
3278
                       (id_,))
3279
        if cursor.fetchone() is None:
3280
            cursor.close()
3281
            cnx.close()
3282
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3283
                                   description='API.MICROGRID_NOT_FOUND')
3284
3285
        cursor.execute(" SELECT name "
3286
                       " FROM tbl_microgrids_loads "
3287
                       " WHERE microgrid_id = %s AND name = %s ",
3288
                       (id_, name,))
3289
        if cursor.fetchone() is not None:
3290
            cursor.close()
3291
            cnx.close()
3292
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3293
                                   description='API.MICROGRID_LOAD_NAME_IS_ALREADY_IN_USE')
3294
3295
        cursor.execute(" SELECT name "
3296
                       " FROM tbl_points "
3297
                       " WHERE id = %s ",
3298
                       (power_point_id,))
3299
        if cursor.fetchone() is None:
3300
            cursor.close()
3301
            cnx.close()
3302
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3303
                                   description='API.POWER_POINT_NOT_FOUND')
3304
3305
        cursor.execute(" SELECT name "
3306
                       " FROM tbl_meters "
3307
                       " WHERE id = %s ",
3308
                       (meter_id,))
3309
        if cursor.fetchone() is None:
3310
            cursor.close()
3311
            cnx.close()
3312
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3313
                                   description='API.METER_NOT_FOUND')
3314
3315
        add_values = (" INSERT INTO tbl_microgrids_loads "
3316
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_input_power) "
3317
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
3318
        cursor.execute(add_values, (name,
3319
                                    str(uuid.uuid4()),
3320
                                    id_,
3321
                                    power_point_id,
3322
                                    meter_id,
3323
                                    rated_input_power))
3324
        new_id = cursor.lastrowid
3325
        cnx.commit()
3326
        cursor.close()
3327
        cnx.close()
3328
3329
        resp.status = falcon.HTTP_201
3330
        resp.location = '/microgrids/' + str(id_) + '/loads/' + str(new_id)
3331
3332
3333
class MicrogridLoadItem:
@@ 1711-1899 (lines=189) @@
1708
        resp.status = falcon.HTTP_200
1709
1710
1711
class MicrogridGeneratorCollection:
1712
    def __init__(self):
1713
        """Initializes MicrogridGeneratorCollection"""
1714
        pass
1715
1716
    @staticmethod
1717
    def on_options(req, resp, id_):
1718
        resp.status = falcon.HTTP_200
1719
1720
    @staticmethod
1721
    def on_get(req, resp, id_):
1722
        access_control(req)
1723
        if not id_.isdigit() or int(id_) <= 0:
1724
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1725
                                   description='API.INVALID_MICROGRID_ID')
1726
1727
        cnx = mysql.connector.connect(**config.myems_system_db)
1728
        cursor = cnx.cursor()
1729
1730
        cursor.execute(" SELECT name "
1731
                       " FROM tbl_microgrids "
1732
                       " WHERE id = %s ", (id_,))
1733
        if cursor.fetchone() is None:
1734
            cursor.close()
1735
            cnx.close()
1736
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1737
                                   description='API.MICROGRID_NOT_FOUND')
1738
1739
        # query meter dict
1740
        query = (" SELECT id, name, uuid "
1741
                 " FROM tbl_meters ")
1742
        cursor.execute(query)
1743
        rows_meters = cursor.fetchall()
1744
1745
        meter_dict = dict()
1746
        if rows_meters is not None and len(rows_meters) > 0:
1747
            for row in rows_meters:
1748
                meter_dict[row[0]] = {"id": row[0],
1749
                                      "name": row[1],
1750
                                      "uuid": row[2]}
1751
        # query point dict
1752
        query = (" SELECT id, name "
1753
                 " FROM tbl_points ")
1754
        cursor.execute(query)
1755
        rows_points = cursor.fetchall()
1756
1757
        point_dict = dict()
1758
        if rows_points is not None and len(rows_points) > 0:
1759
            for row in rows_points:
1760
                point_dict[row[0]] = {"id": row[0],
1761
                                      "name": row[1]}
1762
1763
        query = (" SELECT id, name, uuid, "
1764
                 "        power_point_id, meter_id, rated_output_power "
1765
                 " FROM tbl_microgrids_generators "
1766
                 " WHERE microgrid_id = %s "
1767
                 " ORDER BY name ")
1768
        cursor.execute(query, (id_,))
1769
        rows = cursor.fetchall()
1770
1771
        result = list()
1772
        if rows is not None and len(rows) > 0:
1773
            for row in rows:
1774
                meta_result = {"id": row[0],
1775
                               "name": row[1],
1776
                               "uuid": row[2],
1777
                               "power_point": point_dict.get(row[3]),
1778
                               "meter": meter_dict.get(row[4]),
1779
                               "rated_output_power": row[5]}
1780
                result.append(meta_result)
1781
1782
        resp.text = json.dumps(result)
1783
1784
    @staticmethod
1785
    @user_logger
1786
    def on_post(req, resp, id_):
1787
        """Handles POST requests"""
1788
        admin_control(req)
1789
        try:
1790
            raw_json = req.stream.read().decode('utf-8')
1791
        except Exception as ex:
1792
            raise falcon.HTTPError(status=falcon.HTTP_400,
1793
                                   title='API.BAD_REQUEST',
1794
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1795
        if not id_.isdigit() or int(id_) <= 0:
1796
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1797
                                   description='API.INVALID_MICROGRID_ID')
1798
1799
        cnx = mysql.connector.connect(**config.myems_system_db)
1800
        cursor = cnx.cursor()
1801
1802
        cursor.execute(" SELECT name "
1803
                       " FROM tbl_microgrids "
1804
                       " WHERE id = %s ", (id_,))
1805
        if cursor.fetchone() is None:
1806
            cursor.close()
1807
            cnx.close()
1808
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1809
                                   description='API.MICROGRID_NOT_FOUND')
1810
1811
        new_values = json.loads(raw_json)
1812
1813
        if 'name' not in new_values['data'].keys() or \
1814
                not isinstance(new_values['data']['name'], str) or \
1815
                len(str.strip(new_values['data']['name'])) == 0:
1816
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1817
                                   description='API.INVALID_MICROGRID_GENERATOR_NAME')
1818
        name = str.strip(new_values['data']['name'])
1819
1820
        if 'power_point_id' not in new_values['data'].keys() or \
1821
                not isinstance(new_values['data']['power_point_id'], int) or \
1822
                new_values['data']['power_point_id'] <= 0:
1823
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1824
                                   description='API.INVALID_POWER_POINT_ID')
1825
        power_point_id = new_values['data']['power_point_id']
1826
1827
        if 'meter_id' not in new_values['data'].keys() or \
1828
                not isinstance(new_values['data']['meter_id'], int) or \
1829
                new_values['data']['meter_id'] <= 0:
1830
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1831
                                   description='API.INVALID_METER_ID')
1832
        meter_id = new_values['data']['meter_id']
1833
1834
        if 'rated_output_power' not in new_values['data'].keys() or \
1835
                not (isinstance(new_values['data']['rated_output_power'], float) or
1836
                     isinstance(new_values['data']['rated_output_power'], int)):
1837
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1838
                                   description='API.INVALID_RATED_OUTPUT_POWER')
1839
        rated_output_power = float(new_values['data']['rated_output_power'])
1840
1841
        cnx = mysql.connector.connect(**config.myems_system_db)
1842
        cursor = cnx.cursor()
1843
1844
        cursor.execute(" SELECT name "
1845
                       " FROM tbl_microgrids "
1846
                       " WHERE id = %s ",
1847
                       (id_,))
1848
        if cursor.fetchone() is None:
1849
            cursor.close()
1850
            cnx.close()
1851
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1852
                                   description='API.MICROGRID_NOT_FOUND')
1853
1854
        cursor.execute(" SELECT name "
1855
                       " FROM tbl_microgrids_generators "
1856
                       " WHERE microgrid_id = %s AND name = %s ",
1857
                       (id_, name,))
1858
        if cursor.fetchone() is not None:
1859
            cursor.close()
1860
            cnx.close()
1861
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1862
                                   description='API.MICROGRID_GENERATOR_NAME_IS_ALREADY_IN_USE')
1863
1864
        cursor.execute(" SELECT name "
1865
                       " FROM tbl_points "
1866
                       " WHERE id = %s ",
1867
                       (power_point_id,))
1868
        if cursor.fetchone() is None:
1869
            cursor.close()
1870
            cnx.close()
1871
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1872
                                   description='API.POWER_POINT_NOT_FOUND')
1873
1874
        cursor.execute(" SELECT name "
1875
                       " FROM tbl_meters "
1876
                       " WHERE id = %s ",
1877
                       (meter_id,))
1878
        if cursor.fetchone() is None:
1879
            cursor.close()
1880
            cnx.close()
1881
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1882
                                   description='API.METER_NOT_FOUND')
1883
1884
        add_values = (" INSERT INTO tbl_microgrids_generators "
1885
                      "    (name, uuid, microgrid_id, power_point_id, meter_id, rated_output_power) "
1886
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
1887
        cursor.execute(add_values, (name,
1888
                                    str(uuid.uuid4()),
1889
                                    id_,
1890
                                    power_point_id,
1891
                                    meter_id,
1892
                                    rated_output_power))
1893
        new_id = cursor.lastrowid
1894
        cnx.commit()
1895
        cursor.close()
1896
        cnx.close()
1897
1898
        resp.status = falcon.HTTP_201
1899
        resp.location = '/microgrids/' + str(id_) + '/generators/' + str(new_id)
1900
1901
1902
class MicrogridGeneratorItem:

myems-api/core/energystoragecontainer.py 1 location

@@ 3520-3710 (lines=191) @@
3517
        resp.status = falcon.HTTP_204
3518
3519
3520
class EnergyStorageContainerLoadCollection:
3521
    def __init__(self):
3522
        """Initializes Class"""
3523
        pass
3524
3525
    @staticmethod
3526
    def on_options(req, resp, id_):
3527
        resp.status = falcon.HTTP_200
3528
3529
    @staticmethod
3530
    def on_get(req, resp, id_):
3531
        access_control(req)
3532
        if not id_.isdigit() or int(id_) <= 0:
3533
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3534
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3535
3536
        cnx = mysql.connector.connect(**config.myems_system_db)
3537
        cursor = cnx.cursor()
3538
3539
        cursor.execute(" SELECT name "
3540
                       " FROM tbl_energy_storage_containers "
3541
                       " WHERE id = %s ", (id_,))
3542
        if cursor.fetchone() is None:
3543
            cursor.close()
3544
            cnx.close()
3545
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3546
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
3547
3548
        # query meter dict
3549
        query = (" SELECT id, name, uuid "
3550
                 " FROM tbl_meters ")
3551
        cursor.execute(query)
3552
        rows_meters = cursor.fetchall()
3553
3554
        meter_dict = dict()
3555
        if rows_meters is not None and len(rows_meters) > 0:
3556
            for row in rows_meters:
3557
                meter_dict[row[0]] = {"id": row[0],
3558
                                      "name": row[1],
3559
                                      "uuid": row[2]}
3560
        # query point dict
3561
        query = (" SELECT id, name "
3562
                 " FROM tbl_points ")
3563
        cursor.execute(query)
3564
        rows_points = cursor.fetchall()
3565
3566
        point_dict = dict()
3567
        if rows_points is not None and len(rows_points) > 0:
3568
            for row in rows_points:
3569
                point_dict[row[0]] = {"id": row[0],
3570
                                      "name": row[1]}
3571
3572
        query = (" SELECT id, name, uuid, "
3573
                 "        power_point_id, meter_id, rated_input_power "
3574
                 " FROM tbl_energy_storage_containers_loads "
3575
                 " WHERE energy_storage_container_id = %s "
3576
                 " ORDER BY name ")
3577
        cursor.execute(query, (id_,))
3578
        rows = cursor.fetchall()
3579
3580
        result = list()
3581
        if rows is not None and len(rows) > 0:
3582
            for row in rows:
3583
                meta_result = {"id": row[0],
3584
                               "name": row[1],
3585
                               "uuid": row[2],
3586
                               "power_point": point_dict.get(row[3]),
3587
                               "meter": meter_dict.get(row[4]),
3588
                               "rated_input_power": row[5]
3589
                               }
3590
                result.append(meta_result)
3591
3592
        resp.text = json.dumps(result)
3593
3594
    @staticmethod
3595
    @user_logger
3596
    def on_post(req, resp, id_):
3597
        """Handles POST requests"""
3598
        admin_control(req)
3599
        try:
3600
            raw_json = req.stream.read().decode('utf-8')
3601
        except Exception as ex:
3602
            raise falcon.HTTPError(status=falcon.HTTP_400,
3603
                                   title='API.BAD_REQUEST',
3604
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
3605
        if not id_.isdigit() or int(id_) <= 0:
3606
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3607
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
3608
3609
        cnx = mysql.connector.connect(**config.myems_system_db)
3610
        cursor = cnx.cursor()
3611
3612
        cursor.execute(" SELECT name "
3613
                       " FROM tbl_energy_storage_containers "
3614
                       " WHERE id = %s ", (id_,))
3615
        if cursor.fetchone() is None:
3616
            cursor.close()
3617
            cnx.close()
3618
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3619
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
3620
3621
        new_values = json.loads(raw_json)
3622
3623
        if 'name' not in new_values['data'].keys() or \
3624
                not isinstance(new_values['data']['name'], str) or \
3625
                len(str.strip(new_values['data']['name'])) == 0:
3626
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3627
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_LOAD_NAME')
3628
        name = str.strip(new_values['data']['name'])
3629
3630
        if 'power_point_id' not in new_values['data'].keys() or \
3631
                not isinstance(new_values['data']['power_point_id'], int) or \
3632
                new_values['data']['power_point_id'] <= 0:
3633
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3634
                                   description='API.INVALID_POWER_POINT_ID')
3635
        power_point_id = new_values['data']['power_point_id']
3636
3637
        if 'meter_id' not in new_values['data'].keys() or \
3638
                not isinstance(new_values['data']['meter_id'], int) or \
3639
                new_values['data']['meter_id'] <= 0:
3640
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3641
                                   description='API.INVALID_METER_ID')
3642
        meter_id = new_values['data']['meter_id']
3643
3644
        if 'rated_input_power' not in new_values['data'].keys() or \
3645
                not (isinstance(new_values['data']['rated_input_power'], float) or
3646
                     isinstance(new_values['data']['rated_input_power'], int)):
3647
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3648
                                   description='API.INVALID_RATED_INPUT_POWER')
3649
        rated_input_power = Decimal(new_values['data']['rated_input_power'])
3650
3651
        cnx = mysql.connector.connect(**config.myems_system_db)
3652
        cursor = cnx.cursor()
3653
3654
        cursor.execute(" SELECT name "
3655
                       " FROM tbl_energy_storage_containers "
3656
                       " WHERE id = %s ",
3657
                       (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.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
3663
3664
        cursor.execute(" SELECT name "
3665
                       " FROM tbl_energy_storage_containers_loads "
3666
                       " WHERE energy_storage_container_id = %s AND name = %s ",
3667
                       (id_, name,))
3668
        if cursor.fetchone() is not None:
3669
            cursor.close()
3670
            cnx.close()
3671
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
3672
                                   description='API.ENERGY_STORAGE_CONTAINER_LOAD_NAME_IS_ALREADY_IN_USE')
3673
3674
        cursor.execute(" SELECT name "
3675
                       " FROM tbl_points "
3676
                       " WHERE id = %s ",
3677
                       (power_point_id,))
3678
        if cursor.fetchone() is None:
3679
            cursor.close()
3680
            cnx.close()
3681
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3682
                                   description='API.POWER_POINT_NOT_FOUND')
3683
3684
        cursor.execute(" SELECT name "
3685
                       " FROM tbl_meters "
3686
                       " WHERE id = %s ",
3687
                       (meter_id,))
3688
        if cursor.fetchone() is None:
3689
            cursor.close()
3690
            cnx.close()
3691
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
3692
                                   description='API.METER_NOT_FOUND')
3693
3694
        add_values = (" INSERT INTO tbl_energy_storage_containers_loads "
3695
                      "    (name, uuid, energy_storage_container_id, power_point_id, meter_id, rated_input_power) "
3696
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
3697
        cursor.execute(add_values, (name,
3698
                                    str(uuid.uuid4()),
3699
                                    id_,
3700
                                    power_point_id,
3701
                                    meter_id,
3702
                                    rated_input_power
3703
                                    ))
3704
        new_id = cursor.lastrowid
3705
        cnx.commit()
3706
        cursor.close()
3707
        cnx.close()
3708
3709
        resp.status = falcon.HTTP_201
3710
        resp.location = '/energystoragecontainers/' + str(id_) + '/loads/' + str(new_id)
3711
3712
3713
class EnergyStorageContainerLoadItem: