Code Duplication    Length = 211-214 lines in 2 locations

myems-api/core/energystoragecontainer.py 1 location

@@ 2425-2638 (lines=214) @@
2422
        resp.status = falcon.HTTP_204
2423
2424
2425
class EnergyStorageContainerGridCollection:
2426
    def __init__(self):
2427
        """Initializes Class"""
2428
        pass
2429
2430
    @staticmethod
2431
    def on_options(req, resp, id_):
2432
        _ = req
2433
        resp.status = falcon.HTTP_200
2434
        _ = id_
2435
2436
    @staticmethod
2437
    def on_get(req, resp, id_):
2438
        access_control(req)
2439
        if not id_.isdigit() or int(id_) <= 0:
2440
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2441
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2442
2443
        cnx = mysql.connector.connect(**config.myems_system_db)
2444
        cursor = cnx.cursor()
2445
2446
        cursor.execute(" SELECT name "
2447
                       " FROM tbl_energy_storage_containers "
2448
                       " WHERE id = %s ", (id_,))
2449
        if cursor.fetchone() is None:
2450
            cursor.close()
2451
            cnx.close()
2452
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2453
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
2454
2455
        # query meter dict
2456
        query = (" SELECT id, name, uuid "
2457
                 " FROM tbl_meters ")
2458
        cursor.execute(query)
2459
        rows_meters = cursor.fetchall()
2460
2461
        meter_dict = dict()
2462
        if rows_meters is not None and len(rows_meters) > 0:
2463
            for row in rows_meters:
2464
                meter_dict[row[0]] = {"id": row[0],
2465
                                      "name": row[1],
2466
                                      "uuid": row[2]}
2467
        # query point dict
2468
        query = (" SELECT id, name "
2469
                 " FROM tbl_points ")
2470
        cursor.execute(query)
2471
        rows_points = cursor.fetchall()
2472
2473
        point_dict = dict()
2474
        if rows_points is not None and len(rows_points) > 0:
2475
            for row in rows_points:
2476
                point_dict[row[0]] = {"id": row[0],
2477
                                      "name": row[1]}
2478
2479
        query = (" SELECT id, name, uuid, "
2480
                 "        power_point_id, buy_meter_id, sell_meter_id, capacity "
2481
                 " FROM tbl_energy_storage_containers_grids "
2482
                 " WHERE energy_storage_container_id = %s "
2483
                 " ORDER BY name ")
2484
        cursor.execute(query, (id_,))
2485
        rows = cursor.fetchall()
2486
2487
        result = list()
2488
        if rows is not None and len(rows) > 0:
2489
            for row in rows:
2490
                meta_result = {"id": row[0],
2491
                               "name": row[1],
2492
                               "uuid": row[2],
2493
                               "power_point": point_dict.get(row[3]),
2494
                               "buy_meter": meter_dict.get(row[4]),
2495
                               "sell_meter": meter_dict.get(row[5]),
2496
                               "capacity": row[6]
2497
                               }
2498
                result.append(meta_result)
2499
2500
        resp.text = json.dumps(result)
2501
2502
    @staticmethod
2503
    @user_logger
2504
    def on_post(req, resp, id_):
2505
        """Handles POST requests"""
2506
        admin_control(req)
2507
        try:
2508
            raw_json = req.stream.read().decode('utf-8')
2509
        except Exception as ex:
2510
            print(str(ex))
2511
            raise falcon.HTTPError(status=falcon.HTTP_400,
2512
                                   title='API.BAD_REQUEST',
2513
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2514
        if not id_.isdigit() or int(id_) <= 0:
2515
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2516
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2517
2518
        cnx = mysql.connector.connect(**config.myems_system_db)
2519
        cursor = cnx.cursor()
2520
2521
        cursor.execute(" SELECT name "
2522
                       " FROM tbl_energy_storage_containers "
2523
                       " WHERE id = %s ", (id_,))
2524
        if cursor.fetchone() is None:
2525
            cursor.close()
2526
            cnx.close()
2527
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2528
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
2529
2530
        new_values = json.loads(raw_json)
2531
2532
        if 'name' not in new_values['data'].keys() or \
2533
                not isinstance(new_values['data']['name'], str) or \
2534
                len(str.strip(new_values['data']['name'])) == 0:
2535
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2536
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_GRID_NAME')
2537
        name = str.strip(new_values['data']['name'])
2538
2539
        if 'power_point_id' not in new_values['data'].keys() or \
2540
                not isinstance(new_values['data']['power_point_id'], int) or \
2541
                new_values['data']['power_point_id'] <= 0:
2542
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2543
                                   description='API.INVALID_POWER_POINT_ID')
2544
        power_point_id = new_values['data']['power_point_id']
2545
2546
        if 'buy_meter_id' not in new_values['data'].keys() or \
2547
                not isinstance(new_values['data']['buy_meter_id'], int) or \
2548
                new_values['data']['buy_meter_id'] <= 0:
2549
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2550
                                   description='API.INVALID_BUY_METER_ID')
2551
        buy_meter_id = new_values['data']['buy_meter_id']
2552
2553
        if 'sell_meter_id' not in new_values['data'].keys() or \
2554
                not isinstance(new_values['data']['sell_meter_id'], int) or \
2555
                new_values['data']['sell_meter_id'] <= 0:
2556
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2557
                                   description='API.INVALID_SELL_METER_ID')
2558
        sell_meter_id = new_values['data']['sell_meter_id']
2559
2560
        if 'capacity' not in new_values['data'].keys() or \
2561
                not (isinstance(new_values['data']['capacity'], float) or
2562
                     isinstance(new_values['data']['capacity'], int)):
2563
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2564
                                   description='API.INVALID_CAPACITY')
2565
        capacity = Decimal(new_values['data']['capacity'])
2566
2567
        cnx = mysql.connector.connect(**config.myems_system_db)
2568
        cursor = cnx.cursor()
2569
2570
        cursor.execute(" SELECT name "
2571
                       " FROM tbl_energy_storage_containers "
2572
                       " WHERE id = %s ",
2573
                       (id_,))
2574
        if cursor.fetchone() is None:
2575
            cursor.close()
2576
            cnx.close()
2577
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2578
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
2579
2580
        cursor.execute(" SELECT name "
2581
                       " FROM tbl_energy_storage_containers_grids "
2582
                       " WHERE energy_storage_container_id = %s AND name = %s ",
2583
                       (id_, name,))
2584
        if cursor.fetchone() is not None:
2585
            cursor.close()
2586
            cnx.close()
2587
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2588
                                   description='API.ENERGY_STORAGE_CONTAINER_GRID_NAME_IS_ALREADY_IN_USE')
2589
2590
        cursor.execute(" SELECT name "
2591
                       " FROM tbl_points "
2592
                       " WHERE id = %s ",
2593
                       (power_point_id,))
2594
        if cursor.fetchone() is None:
2595
            cursor.close()
2596
            cnx.close()
2597
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2598
                                   description='API.POWER_POINT_NOT_FOUND')
2599
2600
        cursor.execute(" SELECT name "
2601
                       " FROM tbl_meters "
2602
                       " WHERE id = %s ",
2603
                       (buy_meter_id,))
2604
        if cursor.fetchone() is None:
2605
            cursor.close()
2606
            cnx.close()
2607
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2608
                                   description='API.BUY_METER_NOT_FOUND')
2609
2610
        cursor.execute(" SELECT name "
2611
                       " FROM tbl_meters "
2612
                       " WHERE id = %s ",
2613
                       (sell_meter_id,))
2614
        if cursor.fetchone() is None:
2615
            cursor.close()
2616
            cnx.close()
2617
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2618
                                   description='API.SELL_METER_NOT_FOUND')
2619
2620
        add_values = (" INSERT INTO tbl_energy_storage_containers_grids "
2621
                      "    (name, uuid, energy_storage_container_id, power_point_id, "
2622
                      "     buy_meter_id, sell_meter_id, capacity) "
2623
                      " VALUES (%s, %s, %s, %s, %s, %s, %s) ")
2624
        cursor.execute(add_values, (name,
2625
                                    str(uuid.uuid4()),
2626
                                    id_,
2627
                                    power_point_id,
2628
                                    buy_meter_id,
2629
                                    sell_meter_id,
2630
                                    capacity
2631
                                    ))
2632
        new_id = cursor.lastrowid
2633
        cnx.commit()
2634
        cursor.close()
2635
        cnx.close()
2636
2637
        resp.status = falcon.HTTP_201
2638
        resp.location = '/energystoragecontainers/' + str(id_) + '/grids/' + str(new_id)
2639
2640
2641
class EnergyStorageContainerGridItem:

myems-api/core/microgrid.py 1 location

@@ 2185-2395 (lines=211) @@
2182
        resp.status = falcon.HTTP_200
2183
2184
2185
class MicrogridGridCollection:
2186
    def __init__(self):
2187
        """Initializes MicrogridGridCollection"""
2188
        pass
2189
2190
    @staticmethod
2191
    def on_options(req, resp, id_):
2192
        _ = req
2193
        resp.status = falcon.HTTP_200
2194
        _ = id_
2195
2196
    @staticmethod
2197
    def on_get(req, resp, id_):
2198
        access_control(req)
2199
        if not id_.isdigit() or int(id_) <= 0:
2200
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2201
                                   description='API.INVALID_MICROGRID_ID')
2202
2203
        cnx = mysql.connector.connect(**config.myems_system_db)
2204
        cursor = cnx.cursor()
2205
2206
        cursor.execute(" SELECT name "
2207
                       " FROM tbl_microgrids "
2208
                       " WHERE id = %s ", (id_,))
2209
        if cursor.fetchone() is None:
2210
            cursor.close()
2211
            cnx.close()
2212
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2213
                                   description='API.MICROGRID_NOT_FOUND')
2214
2215
        # query meter dict
2216
        query = (" SELECT id, name, uuid "
2217
                 " FROM tbl_meters ")
2218
        cursor.execute(query)
2219
        rows_meters = cursor.fetchall()
2220
2221
        meter_dict = dict()
2222
        if rows_meters is not None and len(rows_meters) > 0:
2223
            for row in rows_meters:
2224
                meter_dict[row[0]] = {"id": row[0],
2225
                                      "name": row[1],
2226
                                      "uuid": row[2]}
2227
        # query point dict
2228
        query = (" SELECT id, name "
2229
                 " FROM tbl_points ")
2230
        cursor.execute(query)
2231
        rows_points = cursor.fetchall()
2232
2233
        point_dict = dict()
2234
        if rows_points is not None and len(rows_points) > 0:
2235
            for row in rows_points:
2236
                point_dict[row[0]] = {"id": row[0],
2237
                                      "name": row[1]}
2238
2239
        query = (" SELECT id, name, uuid, "
2240
                 "        power_point_id, buy_meter_id, sell_meter_id, capacity "
2241
                 " FROM tbl_microgrids_grids "
2242
                 " WHERE microgrid_id = %s "
2243
                 " ORDER BY name ")
2244
        cursor.execute(query, (id_,))
2245
        rows = cursor.fetchall()
2246
2247
        result = list()
2248
        if rows is not None and len(rows) > 0:
2249
            for row in rows:
2250
                meta_result = {"id": row[0],
2251
                               "name": row[1],
2252
                               "uuid": row[2],
2253
                               "power_point": point_dict.get(row[3]),
2254
                               "buy_meter": meter_dict.get(row[4]),
2255
                               "sell_meter": meter_dict.get(row[5]),
2256
                               "capacity": row[6]}
2257
                result.append(meta_result)
2258
2259
        resp.text = json.dumps(result)
2260
2261
    @staticmethod
2262
    @user_logger
2263
    def on_post(req, resp, id_):
2264
        """Handles POST requests"""
2265
        admin_control(req)
2266
        try:
2267
            raw_json = req.stream.read().decode('utf-8')
2268
        except Exception as ex:
2269
            print(str(ex))
2270
            raise falcon.HTTPError(status=falcon.HTTP_400,
2271
                                   title='API.BAD_REQUEST',
2272
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2273
        if not id_.isdigit() or int(id_) <= 0:
2274
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2275
                                   description='API.INVALID_MICROGRID_ID')
2276
2277
        cnx = mysql.connector.connect(**config.myems_system_db)
2278
        cursor = cnx.cursor()
2279
2280
        cursor.execute(" SELECT name "
2281
                       " FROM tbl_microgrids "
2282
                       " WHERE id = %s ", (id_,))
2283
        if cursor.fetchone() is None:
2284
            cursor.close()
2285
            cnx.close()
2286
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2287
                                   description='API.MICROGRID_NOT_FOUND')
2288
2289
        new_values = json.loads(raw_json)
2290
2291
        if 'name' not in new_values['data'].keys() or \
2292
                not isinstance(new_values['data']['name'], str) or \
2293
                len(str.strip(new_values['data']['name'])) == 0:
2294
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2295
                                   description='API.INVALID_MICROGRID_GRID_NAME')
2296
        name = str.strip(new_values['data']['name'])
2297
2298
        if 'power_point_id' not in new_values['data'].keys() or \
2299
                not isinstance(new_values['data']['power_point_id'], int) or \
2300
                new_values['data']['power_point_id'] <= 0:
2301
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2302
                                   description='API.INVALID_POWER_POINT_ID')
2303
        power_point_id = new_values['data']['power_point_id']
2304
2305
        if 'buy_meter_id' not in new_values['data'].keys() or \
2306
                not isinstance(new_values['data']['buy_meter_id'], int) or \
2307
                new_values['data']['buy_meter_id'] <= 0:
2308
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2309
                                   description='API.INVALID_BUY_METER_ID')
2310
        buy_meter_id = new_values['data']['buy_meter_id']
2311
2312
        if 'sell_meter_id' not in new_values['data'].keys() or \
2313
                not isinstance(new_values['data']['sell_meter_id'], int) or \
2314
                new_values['data']['sell_meter_id'] <= 0:
2315
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2316
                                   description='API.INVALID_SELL_METER_ID')
2317
        sell_meter_id = new_values['data']['sell_meter_id']
2318
2319
        if 'capacity' not in new_values['data'].keys() or \
2320
                not (isinstance(new_values['data']['capacity'], float) or
2321
                     isinstance(new_values['data']['capacity'], int)):
2322
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2323
                                   description='API.INVALID_CAPACITY')
2324
        capacity = float(new_values['data']['capacity'])
2325
2326
        cnx = mysql.connector.connect(**config.myems_system_db)
2327
        cursor = cnx.cursor()
2328
2329
        cursor.execute(" SELECT name "
2330
                       " FROM tbl_microgrids "
2331
                       " WHERE id = %s ",
2332
                       (id_,))
2333
        if cursor.fetchone() is None:
2334
            cursor.close()
2335
            cnx.close()
2336
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2337
                                   description='API.MICROGRID_NOT_FOUND')
2338
2339
        cursor.execute(" SELECT name "
2340
                       " FROM tbl_microgrids_grids "
2341
                       " WHERE microgrid_id = %s AND name = %s ",
2342
                       (id_, name,))
2343
        if cursor.fetchone() is not None:
2344
            cursor.close()
2345
            cnx.close()
2346
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2347
                                   description='API.MICROGRID_GRID_NAME_IS_ALREADY_IN_USE')
2348
2349
        cursor.execute(" SELECT name "
2350
                       " FROM tbl_points "
2351
                       " WHERE id = %s ",
2352
                       (power_point_id,))
2353
        if cursor.fetchone() is None:
2354
            cursor.close()
2355
            cnx.close()
2356
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2357
                                   description='API.POWER_POINT_NOT_FOUND')
2358
2359
        cursor.execute(" SELECT name "
2360
                       " FROM tbl_meters "
2361
                       " WHERE id = %s ",
2362
                       (buy_meter_id,))
2363
        if cursor.fetchone() is None:
2364
            cursor.close()
2365
            cnx.close()
2366
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2367
                                   description='API.BUY_METER_NOT_FOUND')
2368
2369
        cursor.execute(" SELECT name "
2370
                       " FROM tbl_meters "
2371
                       " WHERE id = %s ",
2372
                       (sell_meter_id,))
2373
        if cursor.fetchone() is None:
2374
            cursor.close()
2375
            cnx.close()
2376
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2377
                                   description='API.SELL_METER_NOT_FOUND')
2378
2379
        add_values = (" INSERT INTO tbl_microgrids_grids "
2380
                      "    (name, uuid, microgrid_id, power_point_id, buy_meter_id, sell_meter_id, capacity) "
2381
                      " VALUES (%s, %s, %s, %s, %s, %s, %s) ")
2382
        cursor.execute(add_values, (name,
2383
                                    str(uuid.uuid4()),
2384
                                    id_,
2385
                                    power_point_id,
2386
                                    buy_meter_id,
2387
                                    sell_meter_id,
2388
                                    capacity))
2389
        new_id = cursor.lastrowid
2390
        cnx.commit()
2391
        cursor.close()
2392
        cnx.close()
2393
2394
        resp.status = falcon.HTTP_201
2395
        resp.location = '/microgrids/' + str(id_) + '/grids/' + str(new_id)
2396
2397
2398
class MicrogridGridItem: