Code Duplication    Length = 211-214 lines in 2 locations

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:

myems-api/core/energystoragecontainer.py 1 location

@@ 2665-2878 (lines=214) @@
2662
        resp.status = falcon.HTTP_204
2663
2664
2665
class EnergyStorageContainerGridCollection:
2666
    def __init__(self):
2667
        """Initializes Class"""
2668
        pass
2669
2670
    @staticmethod
2671
    def on_options(req, resp, id_):
2672
        _ = req
2673
        resp.status = falcon.HTTP_200
2674
        _ = id_
2675
2676
    @staticmethod
2677
    def on_get(req, resp, id_):
2678
        access_control(req)
2679
        if not id_.isdigit() or int(id_) <= 0:
2680
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2681
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2682
2683
        cnx = mysql.connector.connect(**config.myems_system_db)
2684
        cursor = cnx.cursor()
2685
2686
        cursor.execute(" SELECT name "
2687
                       " FROM tbl_energy_storage_containers "
2688
                       " WHERE id = %s ", (id_,))
2689
        if cursor.fetchone() is None:
2690
            cursor.close()
2691
            cnx.close()
2692
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2693
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
2694
2695
        # query meter dict
2696
        query = (" SELECT id, name, uuid "
2697
                 " FROM tbl_meters ")
2698
        cursor.execute(query)
2699
        rows_meters = cursor.fetchall()
2700
2701
        meter_dict = dict()
2702
        if rows_meters is not None and len(rows_meters) > 0:
2703
            for row in rows_meters:
2704
                meter_dict[row[0]] = {"id": row[0],
2705
                                      "name": row[1],
2706
                                      "uuid": row[2]}
2707
        # query point dict
2708
        query = (" SELECT id, name "
2709
                 " FROM tbl_points ")
2710
        cursor.execute(query)
2711
        rows_points = cursor.fetchall()
2712
2713
        point_dict = dict()
2714
        if rows_points is not None and len(rows_points) > 0:
2715
            for row in rows_points:
2716
                point_dict[row[0]] = {"id": row[0],
2717
                                      "name": row[1]}
2718
2719
        query = (" SELECT id, name, uuid, "
2720
                 "        power_point_id, buy_meter_id, sell_meter_id, capacity "
2721
                 " FROM tbl_energy_storage_containers_grids "
2722
                 " WHERE energy_storage_container_id = %s "
2723
                 " ORDER BY name ")
2724
        cursor.execute(query, (id_,))
2725
        rows = cursor.fetchall()
2726
2727
        result = list()
2728
        if rows is not None and len(rows) > 0:
2729
            for row in rows:
2730
                meta_result = {"id": row[0],
2731
                               "name": row[1],
2732
                               "uuid": row[2],
2733
                               "power_point": point_dict.get(row[3]),
2734
                               "buy_meter": meter_dict.get(row[4]),
2735
                               "sell_meter": meter_dict.get(row[5]),
2736
                               "capacity": row[6]
2737
                               }
2738
                result.append(meta_result)
2739
2740
        resp.text = json.dumps(result)
2741
2742
    @staticmethod
2743
    @user_logger
2744
    def on_post(req, resp, id_):
2745
        """Handles POST requests"""
2746
        admin_control(req)
2747
        try:
2748
            raw_json = req.stream.read().decode('utf-8')
2749
        except Exception as ex:
2750
            print(str(ex))
2751
            raise falcon.HTTPError(status=falcon.HTTP_400,
2752
                                   title='API.BAD_REQUEST',
2753
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
2754
        if not id_.isdigit() or int(id_) <= 0:
2755
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2756
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_ID')
2757
2758
        cnx = mysql.connector.connect(**config.myems_system_db)
2759
        cursor = cnx.cursor()
2760
2761
        cursor.execute(" SELECT name "
2762
                       " FROM tbl_energy_storage_containers "
2763
                       " WHERE id = %s ", (id_,))
2764
        if cursor.fetchone() is None:
2765
            cursor.close()
2766
            cnx.close()
2767
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2768
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
2769
2770
        new_values = json.loads(raw_json)
2771
2772
        if 'name' not in new_values['data'].keys() or \
2773
                not isinstance(new_values['data']['name'], str) or \
2774
                len(str.strip(new_values['data']['name'])) == 0:
2775
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2776
                                   description='API.INVALID_ENERGY_STORAGE_CONTAINER_GRID_NAME')
2777
        name = str.strip(new_values['data']['name'])
2778
2779
        if 'power_point_id' not in new_values['data'].keys() or \
2780
                not isinstance(new_values['data']['power_point_id'], int) or \
2781
                new_values['data']['power_point_id'] <= 0:
2782
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2783
                                   description='API.INVALID_POWER_POINT_ID')
2784
        power_point_id = new_values['data']['power_point_id']
2785
2786
        if 'buy_meter_id' not in new_values['data'].keys() or \
2787
                not isinstance(new_values['data']['buy_meter_id'], int) or \
2788
                new_values['data']['buy_meter_id'] <= 0:
2789
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2790
                                   description='API.INVALID_BUY_METER_ID')
2791
        buy_meter_id = new_values['data']['buy_meter_id']
2792
2793
        if 'sell_meter_id' not in new_values['data'].keys() or \
2794
                not isinstance(new_values['data']['sell_meter_id'], int) or \
2795
                new_values['data']['sell_meter_id'] <= 0:
2796
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2797
                                   description='API.INVALID_SELL_METER_ID')
2798
        sell_meter_id = new_values['data']['sell_meter_id']
2799
2800
        if 'capacity' not in new_values['data'].keys() or \
2801
                not (isinstance(new_values['data']['capacity'], float) or
2802
                     isinstance(new_values['data']['capacity'], int)):
2803
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2804
                                   description='API.INVALID_CAPACITY')
2805
        capacity = Decimal(new_values['data']['capacity'])
2806
2807
        cnx = mysql.connector.connect(**config.myems_system_db)
2808
        cursor = cnx.cursor()
2809
2810
        cursor.execute(" SELECT name "
2811
                       " FROM tbl_energy_storage_containers "
2812
                       " WHERE id = %s ",
2813
                       (id_,))
2814
        if cursor.fetchone() is None:
2815
            cursor.close()
2816
            cnx.close()
2817
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2818
                                   description='API.ENERGY_STORAGE_CONTAINER_NOT_FOUND')
2819
2820
        cursor.execute(" SELECT name "
2821
                       " FROM tbl_energy_storage_containers_grids "
2822
                       " WHERE energy_storage_container_id = %s AND name = %s ",
2823
                       (id_, name,))
2824
        if cursor.fetchone() is not None:
2825
            cursor.close()
2826
            cnx.close()
2827
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
2828
                                   description='API.ENERGY_STORAGE_CONTAINER_GRID_NAME_IS_ALREADY_IN_USE')
2829
2830
        cursor.execute(" SELECT name "
2831
                       " FROM tbl_points "
2832
                       " WHERE id = %s ",
2833
                       (power_point_id,))
2834
        if cursor.fetchone() is None:
2835
            cursor.close()
2836
            cnx.close()
2837
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2838
                                   description='API.POWER_POINT_NOT_FOUND')
2839
2840
        cursor.execute(" SELECT name "
2841
                       " FROM tbl_meters "
2842
                       " WHERE id = %s ",
2843
                       (buy_meter_id,))
2844
        if cursor.fetchone() is None:
2845
            cursor.close()
2846
            cnx.close()
2847
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2848
                                   description='API.BUY_METER_NOT_FOUND')
2849
2850
        cursor.execute(" SELECT name "
2851
                       " FROM tbl_meters "
2852
                       " WHERE id = %s ",
2853
                       (sell_meter_id,))
2854
        if cursor.fetchone() is None:
2855
            cursor.close()
2856
            cnx.close()
2857
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
2858
                                   description='API.SELL_METER_NOT_FOUND')
2859
2860
        add_values = (" INSERT INTO tbl_energy_storage_containers_grids "
2861
                      "    (name, uuid, energy_storage_container_id, power_point_id, "
2862
                      "     buy_meter_id, sell_meter_id, capacity) "
2863
                      " VALUES (%s, %s, %s, %s, %s, %s, %s) ")
2864
        cursor.execute(add_values, (name,
2865
                                    str(uuid.uuid4()),
2866
                                    id_,
2867
                                    power_point_id,
2868
                                    buy_meter_id,
2869
                                    sell_meter_id,
2870
                                    capacity
2871
                                    ))
2872
        new_id = cursor.lastrowid
2873
        cnx.commit()
2874
        cursor.close()
2875
        cnx.close()
2876
2877
        resp.status = falcon.HTTP_201
2878
        resp.location = '/energystoragecontainers/' + str(id_) + '/grids/' + str(new_id)
2879
2880
2881
class EnergyStorageContainerGridItem: